From 54d6d129c2f84937c6ee0f5494aed9cecb677658 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 01/29] fix: validate .meta entries, lock stores with OS file locks, escape untrusted text parse_meta_config now checks every project once: names are a single path component, paths are relative, normalized and cannot leave the config's directory (no '..', absolute or drive paths, or escaping symlinks), no value holds control characters, repo cannot start with '-', tags hold no whitespace or ','. A bad entry fails the parse with the file and project named; nested configs no longer fail silently. The store lock is now an OS file lock (File::try_lock), released when the holder dies, so an empty or reused-PID lock file can no longer block every store write. The lock and data dirs must belong to the user and not be writable by others; ~/.meta is created 0700 and there is no /tmp fallback without a home dir. Adds display::escape for printing untrusted values. Implements [[tasks/harmony-2749]] --- src/config.rs | 331 ++++++++++++++++++++++++++++++++++++++++-------- src/data_dir.rs | 91 ++++++++++--- src/display.rs | 66 ++++++++++ src/lib.rs | 22 ++-- src/lock.rs | 252 +++++++++++------------------------- src/store.rs | 4 +- 6 files changed, 506 insertions(+), 260 deletions(-) create mode 100644 src/display.rs diff --git a/src/config.rs b/src/config.rs index 43f4904..0f66d4a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3,6 +3,7 @@ //! This module provides the core types and functions for finding and parsing //! .meta configuration files (JSON and YAML formats). +use crate::display::{escape, escape_path, is_unsafe_char}; use anyhow::Context; use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -175,9 +176,12 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, .with_context(|| format!("Failed to parse JSON config file: {}", meta_path.display()))? }; - // Convert project entries to normalized ProjectInfo - let mut projects: Vec = config - .projects + // Convert project entries to normalized, validated ProjectInfo + // in name order, so the first bad entry reported is always the same one + let base_dir = meta_path.parent().unwrap_or(Path::new(".")); + let mut entries: Vec<_> = config.projects.into_iter().collect(); + entries.sort_by(|a, b| a.0.cmp(&b.0)); + let projects: Vec = entries .into_iter() .map(|(name, entry)| { let (repo, path, tags, provides, depends_on, meta) = match entry { @@ -199,8 +203,7 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, (repo, resolved_path, tags, provides, depends_on, meta) } }; - let path = path.replace('\\', "/"); - ProjectInfo { + let mut info = ProjectInfo { name, path, repo, @@ -208,16 +211,130 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, provides, depends_on, meta, - } + }; + validate_project(base_dir, &mut info).map_err(|reason| { + anyhow::anyhow!( + "Invalid project '{}' in {}: {reason}", + escape(&info.name), + escape_path(meta_path) + ) + })?; + Ok(info) }) - .collect(); - - // Sort projects alphabetically by name for deterministic order - projects.sort_by(|a, b| a.name.cmp(&b.name)); + .collect::>()?; Ok((projects, config.ignore)) } +/// Check one project entry and normalize its path, or say what is wrong. +/// +/// These rules are checked once, when a config is parsed, so every caller can +/// join `path` onto the directory of the `.meta` file without checking again: +/// - No value (name, path, repo, tags, provides, depends_on) is empty or holds +/// a control or bidirectional-control character ([`is_unsafe_char`]). +/// - `name` is one path component: not `.` or `..`, no `/` or `\`. +/// - `path` (the name when omitted) is relative and stays inside the config's +/// directory: `\` reads as `/`, empty and `.` components are dropped, `..` +/// and drive prefixes (`C:`) are rejected, something must remain, and no +/// symlink along it may lead outside the directory. +/// - `repo` does not start with `-`, so git cannot read it as an option. +/// - Tags hold no whitespace and no `,`, which the `--tag` filter splits on. +fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result<(), String> { + let lists = [ + ("tag", &info.tags), + ("provides entry", &info.provides), + ("depends_on entry", &info.depends_on), + ]; + for (what, value) in [("name", &info.name), ("path", &info.path)] + .into_iter() + .chain(info.repo.iter().map(|r| ("repo", r))) + .chain( + lists + .into_iter() + .flat_map(|(what, l)| l.iter().map(move |v| (what, v))), + ) + { + if value.is_empty() { + return Err(format!("{what} is empty")); + } + if value.chars().any(is_unsafe_char) { + return Err(format!( + "{what} '{}' contains control characters", + escape(value) + )); + } + } + if matches!(info.name.as_str(), "." | "..") || info.name.contains(['/', '\\']) { + return Err("name must be a single path component (no '/', '\\', '.' or '..')".into()); + } + if info.repo.as_deref().is_some_and(|r| r.starts_with('-')) { + return Err("repo must not start with '-'".into()); + } + if let Some(tag) = info + .tags + .iter() + .find(|t| t.contains(|c: char| c.is_whitespace() || c == ',')) + { + return Err(format!("tag '{tag}' contains whitespace or ','")); + } + info.path = normalize_project_path(&info.path)?; + check_no_symlink_escape(base_dir, &info.path) +} + +/// Normalize a project path to `a/b` form, rejecting anything that is not a +/// plain relative path below the config's directory. +fn normalize_project_path(raw: &str) -> Result { + let unified = raw.replace('\\', "/"); + let mut chars = unified.chars(); + let drive = + matches!((chars.next(), chars.next()), (Some(c), Some(':')) if c.is_ascii_alphabetic()); + if unified.starts_with('/') || drive || Path::new(raw).is_absolute() { + return Err(format!("path '{raw}' must be relative")); + } + let mut parts = Vec::new(); + for part in unified.split('/') { + match part { + "" | "." => {} + ".." => return Err(format!("path '{raw}' must not contain '..'")), + part => parts.push(part), + } + } + if parts.is_empty() { + return Err(format!( + "path '{raw}' must name a directory below the .meta file" + )); + } + Ok(parts.join("/")) +} + +/// Refuse a path that reaches outside `base_dir` through a symlink that +/// already exists (in the workspace or in a checked-out repo). +fn check_no_symlink_escape(base_dir: &Path, rel: &str) -> Result<(), String> { + let Ok(base) = base_dir.canonicalize() else { + return Ok(()); // nothing on disk yet, so nothing to follow + }; + let mut current = base.clone(); + for part in rel.split('/') { + current.push(part); + let Ok(meta) = current.symlink_metadata() else { + return Ok(()); // the rest does not exist yet + }; + if meta.file_type().is_symlink() { + match current.canonicalize() { + Ok(target) if target.starts_with(&base) => current = target, + _ => { + return Err(format!( + "path '{rel}' leads outside {} through the symlink '{}'", + escape_path(&base), + escape_path(¤t) + )) + } + } + } + } + Ok(()) +} + /// Load defaults from a meta config file. /// Returns MetaDefaults::default() if no config found or on parse error. pub fn load_meta_defaults(start_dir: &Path) -> MetaDefaults { @@ -275,7 +392,7 @@ pub fn walk_meta_tree( visited.insert(meta_dir.canonicalize().unwrap_or(meta_dir.to_path_buf())); let depth = max_depth.unwrap_or(usize::MAX); - Ok(walk_inner(meta_dir, &projects, depth, 0, &mut visited)) + walk_inner(meta_dir, &projects, depth, 0, &mut visited) } /// Flatten a meta tree into fully-qualified path strings. @@ -418,43 +535,39 @@ fn walk_inner( max_depth: usize, current_depth: usize, visited: &mut std::collections::HashSet, -) -> Vec { +) -> anyhow::Result> { let mut nodes = Vec::new(); for project in projects { let project_dir = base_dir.join(&project.path); // Check if this project has its own .meta file directly in its directory - let has_meta = project_dir.is_dir() - && find_meta_config(&project_dir, None) - .map(|(path, _)| path.parent().map(|p| p == project_dir).unwrap_or(false)) - .unwrap_or(false); + let nested_config = if project_dir.is_dir() { + find_meta_config(&project_dir, None) + .filter(|(path, _)| path.parent() == Some(project_dir.as_path())) + } else { + None + }; + let has_meta = nested_config.is_some(); - // Recurse into children if within depth limit and this is a meta repo - let children = if has_meta && current_depth < max_depth { + // Recurse into children if within depth limit and this is a meta repo. + // A nested config that fails to parse or validate is an error, not an + // empty subtree: skipping it would silently drop its repos. + let mut children = vec![]; + if let Some((nested_config_path, _)) = nested_config { let canonical = project_dir.canonicalize().unwrap_or(project_dir.clone()); - if visited.insert(canonical) { - if let Some((nested_config_path, _)) = find_meta_config(&project_dir, None) { - if let Ok((nested_projects, _)) = parse_meta_config(&nested_config_path) { - walk_inner( - &project_dir, - &nested_projects, - max_depth, - current_depth + 1, - visited, - ) - } else { - vec![] - } - } else { - vec![] - } - } else { - vec![] // Cycle detected + // `visited` stops cycles through symlinks + if current_depth < max_depth && visited.insert(canonical) { + let (nested_projects, _) = parse_meta_config(&nested_config_path)?; + children = walk_inner( + &project_dir, + &nested_projects, + max_depth, + current_depth + 1, + visited, + )?; } - } else { - vec![] - }; + } nodes.push(MetaTreeNode { info: project.clone(), @@ -464,7 +577,7 @@ fn walk_inner( } nodes.sort_by(|a, b| a.info.name.cmp(&b.info.name)); - nodes + Ok(nodes) } #[cfg(test)] @@ -563,10 +676,11 @@ mod tests { let child = dir.path().join("child"); std::fs::create_dir(&child).unwrap(); - // Create a symlink from child/loop back to root + // Create a symlink from child/loop back to child itself (a link to an + // ancestor would leave child's directory and be rejected outright) #[cfg(unix)] { - std::os::unix::fs::symlink(dir.path(), child.join("loop")).unwrap(); + std::os::unix::fs::symlink(&child, child.join("loop")).unwrap(); } std::fs::write( @@ -1030,32 +1144,139 @@ mod tests { } #[test] - fn test_walk_meta_tree_handles_malformed_nested_meta() { - // When a nested .meta file is malformed, we should skip it gracefully + fn test_walk_meta_tree_fails_on_malformed_nested_meta() { + // A broken nested .meta must surface, not silently drop its repos let dir = tempfile::tempdir().unwrap(); let vendor = dir.path().join("vendor"); std::fs::create_dir(&vendor).unwrap(); - - // Root .meta is valid std::fs::write( dir.path().join(".meta"), r#"{"projects": {"vendor": {"repo": "git@github.com:org/vendor.git", "meta": true}}}"#, ) .unwrap(); - - // Nested .meta is malformed JSON std::fs::write( vendor.join(".meta"), - r#"{"projects": {this is not valid json}"#, + r#"{"projects": {"x": {"path": "../../escape"}}}"#, ) .unwrap(); - // Should still return the tree without the nested children - let tree = walk_meta_tree(dir.path(), None).unwrap(); - assert_eq!(tree.len(), 1); - assert_eq!(tree[0].info.name, "vendor"); - // Children should be empty because the nested .meta was malformed - assert_eq!(tree[0].children.len(), 0); + let err = walk_meta_tree(dir.path(), None).unwrap_err().to_string(); + assert!(err.contains("Invalid project 'x'"), "{err}"); + assert!(err.contains("vendor"), "{err}"); + } + + fn parse_err(json: &str) -> String { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join(".meta"), json).unwrap(); + parse_meta_config(&dir.path().join(".meta")) + .unwrap_err() + .to_string() + } + + #[test] + fn test_parse_rejects_paths_outside_the_workspace() { + for path in [ + "../../dropped", + "a/../../b", + "/abs/dir", + "C:/x", + "C:x", + "\\\\host\\s", + ".", + "./", + ] { + let err = parse_err(&format!( + r#"{{"projects": {{"p": {{"repo": "u", "path": {path:?}}}}}}}"# + )); + assert!(err.contains("Invalid project 'p' in "), "{path}: {err}"); + assert!(err.contains(".meta: path"), "{path}: {err}"); + } + } + + #[test] + fn test_parse_rejects_bad_names_tags_and_repos() { + for (json, what) in [ + ( + r#"{"projects": {"../../../../escaped-wt": {"repo": "u", "path": "a"}}}"#, + "single path component", + ), + (r#"{"projects": {"a/b": "u"}}"#, "single path component"), + ( + r#"{"projects": {"..": {"repo": "u", "path": "a"}}}"#, + "single path component", + ), + ( + r#"{"projects": {"x\u001b]0;T\u0007": "u"}}"#, + "control characters", + ), + ( + r#"{"projects": {"a": {"repo": "u", "tags": ["n\nfake"]}}}"#, + "control characters", + ), + ( + r#"{"projects": {"a": {"repo": "u", "tags": ["a,b"]}}}"#, + "whitespace or ','", + ), + ( + r#"{"projects": {"a": {"repo": "u", "tags": [""]}}}"#, + "tag is empty", + ), + ( + r#"{"projects": {"a": "--upload-pack=touch x"}}"#, + "must not start with '-'", + ), + ( + r#"{"projects": {"a": {"repo": "u", "path": "t\u001b[2J"}}}"#, + "control characters", + ), + ] { + let err = parse_err(json); + assert!(err.contains(what), "{json}: {err}"); + // The offending value is escaped in the message itself + assert!(!err.contains('\u{1b}'), "{json}: {err}"); + } + } + + #[test] + fn test_parse_normalizes_paths() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join(".meta"), + r#"{"projects": {"a": {"repo": "u", "path": "./third_party//vendor/"}, "b": {"repo": "u", "path": "x\\y"}}}"#, + ) + .unwrap(); + let (projects, _) = parse_meta_config(&dir.path().join(".meta")).unwrap(); + assert_eq!(projects[0].path, "third_party/vendor"); + assert_eq!(projects[1].path, "x/y"); + } + + #[cfg(unix)] + #[test] + fn test_parse_rejects_symlink_escape() { + let outside = tempfile::tempdir().unwrap(); + let dir = tempfile::tempdir().unwrap(); + std::os::unix::fs::symlink(outside.path(), dir.path().join("link")).unwrap(); + std::fs::create_dir(dir.path().join("real")).unwrap(); + std::os::unix::fs::symlink(dir.path().join("real"), dir.path().join("inside")).unwrap(); + let meta = dir.path().join(".meta"); + + for path in ["link", "link/sub"] { + std::fs::write( + &meta, + format!(r#"{{"projects": {{"p": {{"repo": "u", "path": "{path}"}}}}}}"#), + ) + .unwrap(); + let err = parse_meta_config(&meta).unwrap_err().to_string(); + assert!(err.contains("through the symlink"), "{path}: {err}"); + } + + // A symlink that stays inside the workspace is fine + std::fs::write( + &meta, + r#"{"projects": {"p": {"repo": "u", "path": "inside/sub"}}}"#, + ) + .unwrap(); + assert!(parse_meta_config(&meta).is_ok()); } #[test] diff --git a/src/data_dir.rs b/src/data_dir.rs index 49900a1..e7c7958 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -4,20 +4,20 @@ //! within the meta data directory. Any crate/plugin can use this module to //! store data at `~/.meta/.json` or `~/.meta//`. //! +//! The directory holds per-user state (stores, locks, plugins), so meta creates +//! it private to the user and refuses one that another user owns or can write +//! to. +//! //! Use `meta_core::meta_dir()` to get the directory path directly. use anyhow::{Context, Result}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; /// Ensure the meta data directory exists, creating it if needed. /// Returns the path to the directory. pub fn ensure_meta_dir() -> Result { - let dir = crate::meta_dir(); - if !dir.exists() { - std::fs::create_dir_all(&dir).with_context(|| { - format!("Failed to create meta data directory at {}", dir.display()) - })?; - } + let dir = crate::meta_dir()?; + create_private_dir(&dir)?; Ok(dir) } @@ -25,21 +25,63 @@ pub fn ensure_meta_dir() -> Result { /// /// The file may or may not exist. Use `store::read` to read with a default, /// or check existence manually. -pub fn data_file(namespace: &str) -> PathBuf { - crate::meta_dir().join(format!("{namespace}.json")) +pub fn data_file(namespace: &str) -> Result { + Ok(crate::meta_dir()?.join(format!("{namespace}.json"))) } /// Get the path for a namespaced subdirectory: `~/.meta//`. /// Creates the directory if it doesn't exist. pub fn data_subdir(namespace: &str) -> Result { - let dir = crate::meta_dir().join(namespace); - if !dir.exists() { - std::fs::create_dir_all(&dir) - .with_context(|| format!("Failed to create data subdirectory at {}", dir.display()))?; - } + let dir = ensure_meta_dir()?.join(namespace); + create_private_dir(&dir)?; Ok(dir) } +/// Create `dir` (mode 0700 on Unix) if missing, then check it is private. +fn create_private_dir(dir: &Path) -> Result<()> { + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); + builder + .create(dir) + .with_context(|| format!("Failed to create meta data directory at {}", dir.display()))?; + check_private_dir(dir) +} + +/// Refuse a directory that another user owns or can write to: they could +/// replace the stores, locks or plugins in it. +#[cfg(unix)] +pub fn check_private_dir(dir: &Path) -> Result<()> { + use std::os::unix::fs::MetadataExt; + + let meta = + std::fs::metadata(dir).with_context(|| format!("Failed to stat {}", dir.display()))?; + // SAFETY: geteuid has no preconditions and cannot fail. + let uid = unsafe { libc::geteuid() }; + if meta.uid() != uid { + anyhow::bail!( + "Refusing to use {}: it is owned by uid {}, not by you (uid {uid})", + dir.display(), + meta.uid() + ); + } + if meta.mode() & 0o022 != 0 { + anyhow::bail!( + "Refusing to use {}: other users can write to it (fix with: chmod go-w '{}')", + dir.display(), + dir.display() + ); + } + Ok(()) +} + +/// Refuse a directory that another user owns or can write to. +#[cfg(not(unix))] +pub fn check_private_dir(_dir: &Path) -> Result<()> { + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -47,7 +89,7 @@ mod tests { #[test] fn test_data_file_path() { std::env::set_var("META_DATA_DIR", "/tmp/test-meta"); - let path = data_file("worktree"); + let path = data_file("worktree").unwrap(); assert_eq!(path, PathBuf::from("/tmp/test-meta/worktree.json")); std::env::remove_var("META_DATA_DIR"); } @@ -58,6 +100,25 @@ mod tests { std::env::set_var("META_DATA_DIR", tmp.path().join("meta-test")); let result = ensure_meta_dir().unwrap(); assert!(result.exists()); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(&result).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o700); + } std::env::remove_var("META_DATA_DIR"); } + + #[cfg(unix)] + #[test] + fn test_refuses_dir_others_can_write() { + use std::os::unix::fs::PermissionsExt; + + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("shared"); + std::fs::create_dir(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o777)).unwrap(); + let err = check_private_dir(&dir).unwrap_err().to_string(); + assert!(err.contains("other users can write to it"), "{err}"); + } } diff --git a/src/display.rs b/src/display.rs new file mode 100644 index 0000000..b306c40 --- /dev/null +++ b/src/display.rs @@ -0,0 +1,66 @@ +//! Escaping for untrusted text in human-readable output. +//! +//! Names, paths, tags and URLs come from `.meta` files, git and the filesystem. +//! Printed raw, a control character in one of them can move the cursor, clear +//! the screen, set the window title or the clipboard, or break a line-based +//! format such as the `meta context` table. Every human-readable printer +//! passes such values through [`escape`]; `--json` output needs nothing more, +//! since JSON already escapes them. + +use std::borrow::Cow; +use std::fmt::Write; + +/// True for characters that must never reach a terminal raw: C0 and C1 +/// controls, DEL, and the Unicode bidirectional controls that reorder how a +/// line is displayed. +pub fn is_unsafe_char(c: char) -> bool { + c.is_control() + || matches!(c, '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') +} + +/// Return `s` with every unsafe character written as a visible escape +/// (`\n`, `\t`, `\r`, or `\u{1b}`). Borrows `s` unchanged when it is clean. +pub fn escape(s: &str) -> Cow<'_, str> { + if !s.chars().any(is_unsafe_char) { + return Cow::Borrowed(s); + } + let mut out = String::with_capacity(s.len() + 8); + for c in s.chars() { + match c { + '\n' => out.push_str("\\n"), + '\t' => out.push_str("\\t"), + '\r' => out.push_str("\\r"), + c if is_unsafe_char(c) => { + let _ = write!(out, "\\u{{{:x}}}", c as u32); + } + c => out.push(c), + } + } + Cow::Owned(out) +} + +/// [`escape`] for a path, which may also hold bytes that are not UTF-8. +pub fn escape_path(path: &std::path::Path) -> String { + escape(&path.to_string_lossy()).into_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clean_text_is_borrowed() { + assert!(matches!(escape("api/core-1.2 ✓"), Cow::Borrowed(_))); + } + + #[test] + fn terminal_sequences_are_made_visible() { + assert_eq!( + escape("x\u{1b}]0;PWNED\u{7}\u{1b}[2J"), + "x\\u{1b}]0;PWNED\\u{7}\\u{1b}[2J" + ); + assert_eq!(escape("n\nfake\r\t"), "n\\nfake\\r\\t"); + assert_eq!(escape("c1\u{9b}31m del\u{7f}"), "c1\\u{9b}31m del\\u{7f}"); + assert_eq!(escape("rtl\u{202e}txt"), "rtl\\u{202e}txt"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 7dd3d65..09d6146 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,13 +2,15 @@ //! //! Provides: //! - `data_dir` — Locate and create the `~/.meta/` data directory and namespaced files -//! - `lock` — File-based locking with PID staleness detection and retry +//! - `display` — Escaping untrusted text for human-readable output +//! - `lock` — Exclusive OS file locks that die with their holder //! - `store` — Atomic JSON read/write with lock-protected updates use std::path::PathBuf; pub mod config; pub mod data_dir; +pub mod display; pub mod lock; pub mod store; @@ -20,13 +22,15 @@ const META_DATA_DIR_ENV: &str = "META_DATA_DIR"; /// Get the meta data directory path. /// Respects `META_DATA_DIR` env var, otherwise defaults to `~/.meta/`. -pub fn meta_dir() -> PathBuf { - if let Ok(override_path) = std::env::var(META_DATA_DIR_ENV) { - return PathBuf::from(override_path); +/// +/// Fails when there is no home directory, rather than falling back to a +/// shared location such as `/tmp` that other users could control. +pub fn meta_dir() -> anyhow::Result { + if let Some(override_path) = std::env::var_os(META_DATA_DIR_ENV).filter(|p| !p.is_empty()) { + return Ok(PathBuf::from(override_path)); } - dirs_home().join(META_DIR_NAME) -} - -fn dirs_home() -> PathBuf { - dirs::home_dir().unwrap_or_else(|| PathBuf::from("/tmp/meta-fallback")) + let home = dirs::home_dir().ok_or_else(|| { + anyhow::anyhow!("Cannot find your home directory; set {META_DATA_DIR_ENV}") + })?; + Ok(home.join(META_DIR_NAME)) } diff --git a/src/lock.rs b/src/lock.rs index 9549c1d..5293789 100644 --- a/src/lock.rs +++ b/src/lock.rs @@ -1,27 +1,28 @@ -//! File-based locking with PID staleness detection and retry. +//! Exclusive locks for the `~/.meta/` stores. //! -//! Uses `O_CREAT | O_EXCL` semantics for atomic lock creation. -//! Writes the current PID into the lock file for stale lock detection. -//! Provides a RAII guard that releases the lock on drop. +//! The lock is an OS file lock (`flock` on Unix, `LockFileEx` on Windows) held +//! on an open lock file. The OS releases it when the holder exits, crashes or +//! is killed, so there is no stale state to detect or recover: a leftover lock +//! file, empty or holding a PID from an older meta, is just a file and gets +//! locked again. The file is never deleted, so two processes racing can never +//! end up holding locks on two different files at the same path. +//! +//! On Unix the lock's directory must belong to the current user and must not +//! be writable by group or others; anyone else who could write there could +//! replace the lock file or the store beside it. use anyhow::{Context, Result}; -use std::fs::{self, OpenOptions}; -use std::io::Write; +use std::fs::{self, File, OpenOptions, TryLockError}; use std::path::{Path, PathBuf}; use std::thread; -use std::time::Duration; +use std::time::{Duration, Instant}; -/// RAII guard that releases the lock file on drop. +/// RAII guard that holds the lock until dropped. pub struct LockGuard { + _file: File, path: PathBuf, } -impl Drop for LockGuard { - fn drop(&mut self) { - let _ = fs::remove_file(&self.path); - } -} - impl LockGuard { /// Get the path of the lock file. pub fn path(&self) -> &Path { @@ -29,167 +30,65 @@ impl LockGuard { } } -/// Acquire an exclusive lock at the given path. -/// -/// Creates the lock file with `O_CREAT | O_EXCL` and writes the current PID. -/// If the lock file already exists: -/// 1. Check if the PID inside is still alive (stale lock detection) -/// 2. If stale, remove and retry -/// 3. If alive, wait `retry_ms` milliseconds and retry up to `max_retries` times +/// Acquire an exclusive lock on `lock_path`, creating the file and its +/// directory if needed. /// -/// Returns a `LockGuard` that removes the lock file on drop. -pub fn acquire(lock_path: &Path, max_retries: u32, retry_ms: u64) -> Result { - // Ensure parent directory exists +/// Waits up to `timeout` while another process holds the lock, then fails. +pub fn acquire(lock_path: &Path, timeout: Duration) -> Result { if let Some(parent) = lock_path.parent() { - if !parent.exists() { - fs::create_dir_all(parent).with_context(|| { - format!("Failed to create lock directory: {}", parent.display()) - })?; - } + fs::create_dir_all(parent) + .with_context(|| format!("Failed to create lock directory: {}", parent.display()))?; + crate::data_dir::check_private_dir(parent)?; } - - for attempt in 0..=max_retries { - match try_create_lock(lock_path) { - Ok(guard) => return Ok(guard), - Err(_) if attempt < max_retries => { - // Lock exists — check if stale - if let Some(stale_pid) = stale_pid(lock_path) { - // Double-check: re-read PID to guard against race where - // another process acquired the lock between our checks - if read_lock_pid(lock_path) == Some(stale_pid) { - let _ = fs::remove_file(lock_path); - } - continue; - } - // Lock is held by a live process — wait and retry - thread::sleep(Duration::from_millis(retry_ms)); - } - Err(e) => { - return Err(e).with_context(|| { - format!( - "Failed to acquire lock at {} after {} attempts", - lock_path.display(), - max_retries + 1 - ) - }); - } - } - } - - anyhow::bail!( - "Failed to acquire lock at {} after {} retries", - lock_path.display(), - max_retries - ) -} - -/// Try to create the lock file atomically. -fn try_create_lock(lock_path: &Path) -> Result { - let mut file = OpenOptions::new() + let file = OpenOptions::new() + .read(true) .write(true) - .create_new(true) // O_CREAT | O_EXCL + .create(true) + .truncate(false) .open(lock_path) - .with_context(|| format!("Lock file already exists: {}", lock_path.display()))?; - - // Write current PID - let pid = std::process::id(); - writeln!(file, "{pid}") - .with_context(|| format!("Failed to write PID to lock file: {}", lock_path.display()))?; - - Ok(LockGuard { - path: lock_path.to_path_buf(), - }) -} - -/// Check if a lock file is stale (the PID inside is dead). -/// -/// Returns `true` if: -/// - The lock file doesn't exist -/// - The lock file can't be read -/// - The PID in the lock file is not a running process -pub fn is_stale(lock_path: &Path) -> bool { - stale_pid(lock_path).is_some() -} - -/// Read the PID from a lock file, returning None if unreadable or unparseable. -fn read_lock_pid(lock_path: &Path) -> Option { - let content = fs::read_to_string(lock_path).ok()?; - content.trim().parse().ok() -} - -/// If the lock is stale, return the dead PID. Otherwise return None. -fn stale_pid(lock_path: &Path) -> Option { - let pid = read_lock_pid(lock_path)?; - if is_process_alive(pid) { - None - } else { - Some(pid) - } -} - -/// Check if a process with the given PID is alive. -#[cfg(unix)] -fn is_process_alive(pid: u32) -> bool { - // kill(pid, 0) checks if process exists without sending a signal - unsafe { libc::kill(pid as i32, 0) == 0 } -} - -#[cfg(windows)] -fn is_process_alive(pid: u32) -> bool { - use std::ptr::null_mut; - - // PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 - const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000; - - #[link(name = "kernel32")] - extern "system" { - fn OpenProcess( - dwDesiredAccess: u32, - bInheritHandle: i32, - dwProcessId: u32, - ) -> *mut std::ffi::c_void; - fn CloseHandle(hObject: *mut std::ffi::c_void) -> i32; - } - - unsafe { - let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); - if handle.is_null() { - false - } else { - CloseHandle(handle); - true + .with_context(|| format!("Failed to open lock file: {}", lock_path.display()))?; + + let deadline = Instant::now() + timeout; + loop { + match file.try_lock() { + Ok(()) => { + return Ok(LockGuard { + _file: file, + path: lock_path.to_path_buf(), + }) + } + Err(TryLockError::WouldBlock) if Instant::now() < deadline => { + thread::sleep(Duration::from_millis(20)); + } + Err(TryLockError::WouldBlock) => anyhow::bail!( + "Timed out after {:?} waiting for the lock at {}: another meta process holds it", + timeout, + lock_path.display() + ), + Err(TryLockError::Error(e)) => { + return Err(e).with_context(|| format!("Failed to lock {}", lock_path.display())) + } } } } -#[cfg(not(any(unix, windows)))] -fn is_process_alive(_pid: u32) -> bool { - // On other platforms, conservatively assume the process is alive - true -} - #[cfg(test)] mod tests { use super::*; + const WAIT: Duration = Duration::from_millis(200); + #[test] fn test_acquire_and_release() { let tmp = tempfile::tempdir().unwrap(); let lock_path = tmp.path().join("test.lock"); - { - let guard = acquire(&lock_path, 0, 100).unwrap(); - assert!(lock_path.exists()); - assert_eq!(guard.path(), lock_path); - - // Verify PID was written - let content = fs::read_to_string(&lock_path).unwrap(); - let pid: u32 = content.trim().parse().unwrap(); - assert_eq!(pid, std::process::id()); - } + let guard = acquire(&lock_path, WAIT).unwrap(); + assert_eq!(guard.path(), lock_path); + drop(guard); - // Guard dropped — lock should be removed - assert!(!lock_path.exists()); + // Released on drop: the next acquire succeeds at once + acquire(&lock_path, Duration::ZERO).unwrap(); } #[test] @@ -197,39 +96,34 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); let lock_path = tmp.path().join("test.lock"); - let _guard = acquire(&lock_path, 0, 100).unwrap(); - - // Second acquire should fail (0 retries) - let result = acquire(&lock_path, 0, 10); - assert!(result.is_err()); + let _guard = acquire(&lock_path, WAIT).unwrap(); + let err = acquire(&lock_path, WAIT).err().unwrap().to_string(); + assert!(err.contains("another meta process holds it"), "{err}"); } #[test] - fn test_stale_lock_detection() { + fn test_leftover_lock_files_do_not_block() { let tmp = tempfile::tempdir().unwrap(); let lock_path = tmp.path().join("stale.lock"); - // Write a fake PID that definitely doesn't exist - fs::write(&lock_path, "999999999\n").unwrap(); - - assert!(is_stale(&lock_path)); - - // Write our own PID — should not be stale - fs::write(&lock_path, format!("{}\n", std::process::id())).unwrap(); - assert!(!is_stale(&lock_path)); + // Empty (crash between create and write), garbage, a dead PID, and a + // live but unrelated PID (our own, standing in for PID reuse) + let own_pid = format!("{}\n", std::process::id()); + for content in ["", "not a pid", "999999999\n", own_pid.as_str()] { + fs::write(&lock_path, content).unwrap(); + acquire(&lock_path, Duration::ZERO).unwrap(); + } } #[test] - fn test_acquire_recovers_stale_lock() { + fn test_lock_excludes_other_processes() { + // The lock belongs to the open file, so a second open (as another + // process would make) sees it held. let tmp = tempfile::tempdir().unwrap(); - let lock_path = tmp.path().join("stale.lock"); + let lock_path = tmp.path().join("x.lock"); + let _guard = acquire(&lock_path, WAIT).unwrap(); - // Create a stale lock (non-existent PID) - fs::write(&lock_path, "999999999\n").unwrap(); - - // Should succeed by detecting and removing the stale lock - let guard = acquire(&lock_path, 1, 10).unwrap(); - assert!(lock_path.exists()); - drop(guard); + let other = File::options().write(true).open(&lock_path).unwrap(); + assert!(matches!(other.try_lock(), Err(TryLockError::WouldBlock))); } } diff --git a/src/store.rs b/src/store.rs index 58028c2..c04eb02 100644 --- a/src/store.rs +++ b/src/store.rs @@ -69,7 +69,7 @@ where T: DeserializeOwned + Default + Serialize, F: FnOnce(&mut T), { - let _guard = crate::lock::acquire(lock_path, 50, 100)?; + let _guard = crate::lock::acquire(lock_path, std::time::Duration::from_secs(5))?; let mut data: T = read(data_path)?; f(&mut data); @@ -149,7 +149,7 @@ mod tests { assert_eq!(store.items.get("second").unwrap(), "2"); // Lock should be released - assert!(!lock_path.exists()); + assert!(crate::lock::acquire(&lock_path, std::time::Duration::ZERO).is_ok()); } #[test] From 28e280802c263d32835bccc8ecdc58ec3abb5e67 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 02/29] fix(config): reject overlapping project paths and drive prefixes; check the data dir before reads No two projects may share or nest paths, so a clone cannot plant a symlink that another project's path follows. Drive prefixes are rejected in every path component and in names. A bare config filename resolves its base dir as '.'. data_file and private_meta_dir refuse a data dir another user can write to before anything is read from it. Adds display::escape_lines for error text. Implements [[tasks/harmony-2749]] --- src/config.rs | 113 +++++++++++++++++++++++++++++++++++++++++++----- src/data_dir.rs | 12 ++++- src/display.rs | 15 +++++++ 3 files changed, 128 insertions(+), 12 deletions(-) diff --git a/src/config.rs b/src/config.rs index 0f66d4a..d71b91d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -162,6 +162,10 @@ pub fn find_meta_config( } /// Parse a meta config file (JSON or YAML) and return normalized project info and ignore list. +/// +/// Every project is checked by [`validate_project`] and no two projects may +/// share or nest paths ([`check_no_overlap`]); a bad entry fails the parse +/// with the file and project named. pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, Vec)> { let config_str = std::fs::read_to_string(meta_path) .with_context(|| format!("Failed to read meta config file: '{}'", meta_path.display()))?; @@ -178,7 +182,10 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, // Convert project entries to normalized, validated ProjectInfo // in name order, so the first bad entry reported is always the same one - let base_dir = meta_path.parent().unwrap_or(Path::new(".")); + let base_dir = meta_path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); let mut entries: Vec<_> = config.projects.into_iter().collect(); entries.sort_by(|a, b| a.0.cmp(&b.0)); let projects: Vec = entries @@ -222,6 +229,8 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, Ok(info) }) .collect::>()?; + check_no_overlap(&projects) + .map_err(|e| anyhow::anyhow!("Invalid projects in {}: {e}", escape_path(meta_path)))?; Ok((projects, config.ignore)) } @@ -232,7 +241,8 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, /// join `path` onto the directory of the `.meta` file without checking again: /// - No value (name, path, repo, tags, provides, depends_on) is empty or holds /// a control or bidirectional-control character ([`is_unsafe_char`]). -/// - `name` is one path component: not `.` or `..`, no `/` or `\`. +/// - `name` is one path component: not `.` or `..`, no `/`, `\` or drive +/// prefix. /// - `path` (the name when omitted) is relative and stays inside the config's /// directory: `\` reads as `/`, empty and `.` components are dropped, `..` /// and drive prefixes (`C:`) are rejected, something must remain, and no @@ -264,8 +274,13 @@ fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result<(), Strin )); } } - if matches!(info.name.as_str(), "." | "..") || info.name.contains(['/', '\\']) { - return Err("name must be a single path component (no '/', '\\', '.' or '..')".into()); + if matches!(info.name.as_str(), "." | "..") + || info.name.contains(['/', '\\']) + || starts_with_drive(&info.name) + { + return Err( + "name must be a single path component (no '/', '\\', drive prefix, '.' or '..')".into(), + ); } if info.repo.as_deref().is_some_and(|r| r.starts_with('-')) { return Err("repo must not start with '-'".into()); @@ -281,14 +296,50 @@ fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result<(), Strin check_no_symlink_escape(base_dir, &info.path) } +/// Refuse two projects at one path, or one project inside another's +/// directory: a clone of the outer repo could create a symlink that the +/// inner path then follows out of the workspace. A repo inside another +/// belongs in a nested `.meta` (`meta: true`). +fn check_no_overlap(projects: &[ProjectInfo]) -> Result<(), String> { + let mut by_path = HashMap::new(); + for p in projects { + if let Some(other) = by_path.insert(p.path.as_str(), p.name.as_str()) { + return Err(format!( + "Projects '{}' and '{}' have the same path '{}'", + escape(other), + escape(&p.name), + escape(&p.path) + )); + } + } + for p in projects { + for (i, _) in p.path.match_indices('/') { + let outer = p.path.get(..i).and_then(|prefix| by_path.get(prefix)); + if let Some(outer) = outer { + return Err(format!( + "Project '{}' (path '{}') is inside project '{}'; list it in a nested .meta instead", + escape(&p.name), + escape(&p.path), + escape(outer) + )); + } + } + } + Ok(()) +} + +/// True for a `C:` prefix, which makes a Windows path absolute or +/// drive-relative wherever it appears. +fn starts_with_drive(s: &str) -> bool { + let mut chars = s.chars(); + matches!((chars.next(), chars.next()), (Some(c), Some(':')) if c.is_ascii_alphabetic()) +} + /// Normalize a project path to `a/b` form, rejecting anything that is not a /// plain relative path below the config's directory. fn normalize_project_path(raw: &str) -> Result { let unified = raw.replace('\\', "/"); - let mut chars = unified.chars(); - let drive = - matches!((chars.next(), chars.next()), (Some(c), Some(':')) if c.is_ascii_alphabetic()); - if unified.starts_with('/') || drive || Path::new(raw).is_absolute() { + if unified.starts_with('/') { return Err(format!("path '{raw}' must be relative")); } let mut parts = Vec::new(); @@ -296,6 +347,9 @@ fn normalize_project_path(raw: &str) -> Result { match part { "" | "." => {} ".." => return Err(format!("path '{raw}' must not contain '..'")), + part if starts_with_drive(part) => { + return Err(format!("path '{raw}' must be relative (no drive prefix)")) + } part => parts.push(part), } } @@ -310,9 +364,9 @@ fn normalize_project_path(raw: &str) -> Result { /// Refuse a path that reaches outside `base_dir` through a symlink that /// already exists (in the workspace or in a checked-out repo). fn check_no_symlink_escape(base_dir: &Path, rel: &str) -> Result<(), String> { - let Ok(base) = base_dir.canonicalize() else { - return Ok(()); // nothing on disk yet, so nothing to follow - }; + let base = base_dir + .canonicalize() + .map_err(|e| format!("cannot resolve {}: {e}", escape_path(base_dir)))?; let mut current = base.clone(); for part in rel.split('/') { current.push(part); @@ -1237,6 +1291,43 @@ mod tests { } } + #[test] + fn test_parse_rejects_drive_prefixes_anywhere() { + for json in [ + r#"{"projects": {"p": {"repo": "u", "path": "./C:/outside"}}}"#, + r#"{"projects": {"p": {"repo": "u", "path": "a/C:b"}}}"#, + r#"{"projects": {"C:outside": {"repo": "u", "path": "safe"}}}"#, + ] { + let err = parse_err(json); + assert!(err.contains("drive prefix"), "{json}: {err}"); + } + } + + #[test] + fn test_parse_rejects_overlapping_paths() { + let err = parse_err( + r#"{"projects": {"outer": {"repo": "u", "path": "a"}, "inner": {"repo": "u", "path": "a/link/x"}}}"#, + ); + assert!( + err.contains("Project 'inner' (path 'a/link/x') is inside project 'outer'"), + "{err}" + ); + + let err = parse_err( + r#"{"projects": {"one": {"repo": "u", "path": "x"}, "two": {"repo": "u", "path": "./x/"}}}"#, + ); + assert!(err.contains("have the same path 'x'"), "{err}"); + + // A shared name prefix is not nesting + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join(".meta"), + r#"{"projects": {"a": "u", "a-b": "u", "ab": {"repo": "u", "path": "a.b/c"}}}"#, + ) + .unwrap(); + assert!(parse_meta_config(&dir.path().join(".meta")).is_ok()); + } + #[test] fn test_parse_normalizes_paths() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/data_dir.rs b/src/data_dir.rs index e7c7958..15fda08 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -21,12 +21,22 @@ pub fn ensure_meta_dir() -> Result { Ok(dir) } +/// The meta data directory, checked with [`check_private_dir`] when it exists, +/// so nothing is read from one that another user could have written to. +pub fn private_meta_dir() -> Result { + let dir = crate::meta_dir()?; + if dir.exists() { + check_private_dir(&dir)?; + } + Ok(dir) +} + /// Get the path for a namespaced data file: `~/.meta/.json`. /// /// The file may or may not exist. Use `store::read` to read with a default, /// or check existence manually. pub fn data_file(namespace: &str) -> Result { - Ok(crate::meta_dir()?.join(format!("{namespace}.json"))) + Ok(private_meta_dir()?.join(format!("{namespace}.json"))) } /// Get the path for a namespaced subdirectory: `~/.meta//`. diff --git a/src/display.rs b/src/display.rs index b306c40..3065b67 100644 --- a/src/display.rs +++ b/src/display.rs @@ -39,6 +39,15 @@ pub fn escape(s: &str) -> Cow<'_, str> { Cow::Owned(out) } +/// [`escape`] for multi-line text such as an error message: newlines stay, +/// every other unsafe character is escaped. +pub fn escape_lines(s: &str) -> Cow<'_, str> { + if !s.chars().any(|c| c != '\n' && is_unsafe_char(c)) { + return Cow::Borrowed(s); + } + Cow::Owned(s.split('\n').map(escape).collect::>().join("\n")) +} + /// [`escape`] for a path, which may also hold bytes that are not UTF-8. pub fn escape_path(path: &std::path::Path) -> String { escape(&path.to_string_lossy()).into_owned() @@ -63,4 +72,10 @@ mod tests { assert_eq!(escape("c1\u{9b}31m del\u{7f}"), "c1\\u{9b}31m del\\u{7f}"); assert_eq!(escape("rtl\u{202e}txt"), "rtl\\u{202e}txt"); } + + #[test] + fn escape_lines_keeps_newlines_only() { + assert!(matches!(escape_lines("a\nb"), Cow::Borrowed(_))); + assert_eq!(escape_lines("a\u{1b}[2J\nb\r"), "a\\u{1b}[2J\nb\\r"); + } } From 9873592e212a0f48ae9a66f8a7aef60cd3f9a15d Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 03/29] fix(config): compare project locations through symlinks; check data dir ancestors Overlap is checked on locations resolved through existing symlinks and without case, so an in-workspace symlink alias cannot hide that one project sits inside another. A project path that resolves to the config's own directory is refused. check_private_dir also refuses a data dir under a directory another user could rename it in (not owned by you or root, or writable by others without the sticky bit). Paths in lock and data dir errors are escaped. Implements [[tasks/harmony-2749]] --- src/config.rs | 158 ++++++++++++++++++++++++++++++------------------ src/data_dir.rs | 57 +++++++++++++---- src/lock.rs | 9 +-- 3 files changed, 150 insertions(+), 74 deletions(-) diff --git a/src/config.rs b/src/config.rs index d71b91d..f2014a6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -188,7 +188,7 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, .unwrap_or(Path::new(".")); let mut entries: Vec<_> = config.projects.into_iter().collect(); entries.sort_by(|a, b| a.0.cmp(&b.0)); - let projects: Vec = entries + let checked: Vec<(ProjectInfo, PathBuf)> = entries .into_iter() .map(|(name, entry)| { let (repo, path, tags, provides, depends_on, meta) = match entry { @@ -219,18 +219,19 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, depends_on, meta, }; - validate_project(base_dir, &mut info).map_err(|reason| { + let location = validate_project(base_dir, &mut info).map_err(|reason| { anyhow::anyhow!( "Invalid project '{}' in {}: {reason}", escape(&info.name), escape_path(meta_path) ) })?; - Ok(info) + Ok((info, location)) }) .collect::>()?; - check_no_overlap(&projects) + check_no_overlap(&checked) .map_err(|e| anyhow::anyhow!("Invalid projects in {}: {e}", escape_path(meta_path)))?; + let projects = checked.into_iter().map(|(info, _)| info).collect(); Ok((projects, config.ignore)) } @@ -249,7 +250,9 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, /// symlink along it may lead outside the directory. /// - `repo` does not start with `-`, so git cannot read it as an option. /// - Tags hold no whitespace and no `,`, which the `--tag` filter splits on. -fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result<(), String> { +/// +/// Returns where the project lives on disk (see [`resolve_inside`]). +fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result { let lists = [ ("tag", &info.tags), ("provides entry", &info.provides), @@ -293,38 +296,43 @@ fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result<(), Strin return Err(format!("tag '{tag}' contains whitespace or ','")); } info.path = normalize_project_path(&info.path)?; - check_no_symlink_escape(base_dir, &info.path) + resolve_inside(base_dir, &info.path) } -/// Refuse two projects at one path, or one project inside another's -/// directory: a clone of the outer repo could create a symlink that the -/// inner path then follows out of the workspace. A repo inside another -/// belongs in a nested `.meta` (`meta: true`). -fn check_no_overlap(projects: &[ProjectInfo]) -> Result<(), String> { - let mut by_path = HashMap::new(); - for p in projects { - if let Some(other) = by_path.insert(p.path.as_str(), p.name.as_str()) { +/// Refuse two projects at one location, or one inside another's directory: +/// a clone of the outer repo could check out a symlink that the inner path +/// then follows out of the workspace. Locations are compared as resolved +/// through existing symlinks, and without case, which some filesystems +/// ignore. A repo inside another belongs in a nested `.meta` (`meta: true`). +fn check_no_overlap(projects: &[(ProjectInfo, PathBuf)]) -> Result<(), String> { + let keyed: Vec<_> = projects + .iter() + .map(|(info, location)| { + ( + PathBuf::from(location.to_string_lossy().to_lowercase()), + info, + ) + }) + .collect(); + for (i, (outer_key, outer)) in keyed.iter().enumerate() { + for (inner_key, inner) in keyed.iter().skip(i + 1) { + let (outer, inner) = if inner_key.starts_with(outer_key) { + (outer, inner) + } else if outer_key.starts_with(inner_key) { + (inner, outer) + } else { + continue; + }; return Err(format!( - "Projects '{}' and '{}' have the same path '{}'", - escape(other), - escape(&p.name), - escape(&p.path) + "project '{}' (path '{}') is at or inside project '{}' (path '{}'); \ + list it in a nested .meta instead", + escape(&inner.name), + escape(&inner.path), + escape(&outer.name), + escape(&outer.path) )); } } - for p in projects { - for (i, _) in p.path.match_indices('/') { - let outer = p.path.get(..i).and_then(|prefix| by_path.get(prefix)); - if let Some(outer) = outer { - return Err(format!( - "Project '{}' (path '{}') is inside project '{}'; list it in a nested .meta instead", - escape(&p.name), - escape(&p.path), - escape(outer) - )); - } - } - } Ok(()) } @@ -361,21 +369,25 @@ fn normalize_project_path(raw: &str) -> Result { Ok(parts.join("/")) } -/// Refuse a path that reaches outside `base_dir` through a symlink that -/// already exists (in the workspace or in a checked-out repo). -fn check_no_symlink_escape(base_dir: &Path, rel: &str) -> Result<(), String> { +/// Resolve `rel` below `base_dir` through the symlinks that exist now, and +/// refuse it if one leads outside `base_dir` or if it is `base_dir` itself. +/// Returns the project's location: the real path of the part that exists, +/// followed by the part not created yet. +fn resolve_inside(base_dir: &Path, rel: &str) -> Result { let base = base_dir .canonicalize() .map_err(|e| format!("cannot resolve {}: {e}", escape_path(base_dir)))?; let mut current = base.clone(); + let mut exists = true; for part in rel.split('/') { current.push(part); - let Ok(meta) = current.symlink_metadata() else { - return Ok(()); // the rest does not exist yet - }; - if meta.file_type().is_symlink() { - match current.canonicalize() { - Ok(target) if target.starts_with(&base) => current = target, + if !exists { + continue; + } + match current.symlink_metadata() { + Err(_) => exists = false, + Ok(meta) if meta.file_type().is_symlink() => match current.canonicalize() { + Ok(target) if target.starts_with(&base) && target != base => current = target, _ => { return Err(format!( "path '{rel}' leads outside {} through the symlink '{}'", @@ -383,10 +395,11 @@ fn check_no_symlink_escape(base_dir: &Path, rel: &str) -> Result<(), String> { escape_path(¤t) )) } - } + }, + Ok(_) => {} } } - Ok(()) + Ok(current) } /// Load defaults from a meta config file. @@ -725,17 +738,14 @@ mod tests { } #[test] - fn test_walk_meta_tree_cycle_detection() { + fn test_walk_meta_tree_rejects_symlink_cycles() { + // A nested project that links back to its own meta dir (or any + // ancestor) is refused, so the walk cannot loop let dir = tempfile::tempdir().unwrap(); let child = dir.path().join("child"); std::fs::create_dir(&child).unwrap(); - - // Create a symlink from child/loop back to child itself (a link to an - // ancestor would leave child's directory and be rejected outright) #[cfg(unix)] - { - std::os::unix::fs::symlink(&child, child.join("loop")).unwrap(); - } + std::os::unix::fs::symlink(&child, child.join("loop")).unwrap(); std::fs::write( dir.path().join(".meta"), @@ -748,14 +758,11 @@ mod tests { ) .unwrap(); - // Should not infinite loop - cycle detection stops recursion - let tree = walk_meta_tree(dir.path(), None).unwrap(); - let paths = flatten_meta_tree(&tree); - assert!(paths.contains(&"child".to_string())); - // The cycle node is included but has no children - assert!(paths.contains(&"child/loop".to_string())); - let child_node = &tree[0]; - assert!(child_node.children[0].children.is_empty()); + #[cfg(unix)] + { + let err = walk_meta_tree(dir.path(), None).unwrap_err().to_string(); + assert!(err.contains("through the symlink"), "{err}"); + } } #[test] @@ -1291,6 +1298,30 @@ mod tests { } } + #[cfg(unix)] + #[test] + fn test_parse_rejects_overlap_through_symlink_alias() { + // `alias` points at `real`, so `alias/outer/link/x` sits inside + // `real/outer`, whose clone could plant `link` pointing anywhere. + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("real")).unwrap(); + std::os::unix::fs::symlink(dir.path().join("real"), dir.path().join("alias")).unwrap(); + std::fs::write( + dir.path().join(".meta"), + r#"{"projects": {"outer": {"repo": "u", "path": "real/outer"}, "inner": {"repo": "u", "path": "alias/outer/link/x"}}}"#, + ) + .unwrap(); + let err = parse_meta_config(&dir.path().join(".meta")) + .unwrap_err() + .to_string(); + assert!( + err.contains( + "project 'inner' (path 'alias/outer/link/x') is at or inside project 'outer'" + ), + "{err}" + ); + } + #[test] fn test_parse_rejects_drive_prefixes_anywhere() { for json in [ @@ -1309,14 +1340,23 @@ mod tests { r#"{"projects": {"outer": {"repo": "u", "path": "a"}, "inner": {"repo": "u", "path": "a/link/x"}}}"#, ); assert!( - err.contains("Project 'inner' (path 'a/link/x') is inside project 'outer'"), + err.contains("project 'inner' (path 'a/link/x') is at or inside project 'outer'"), "{err}" ); let err = parse_err( r#"{"projects": {"one": {"repo": "u", "path": "x"}, "two": {"repo": "u", "path": "./x/"}}}"#, ); - assert!(err.contains("have the same path 'x'"), "{err}"); + assert!( + err.contains("project 'two' (path 'x') is at or inside project 'one'"), + "{err}" + ); + + // Case differences don't separate paths (some filesystems ignore case) + let err = parse_err( + r#"{"projects": {"one": {"repo": "u", "path": "Lib"}, "two": {"repo": "u", "path": "lib/x"}}}"#, + ); + assert!(err.contains("is at or inside project 'one'"), "{err}"); // A shared name prefix is not nesting let dir = tempfile::tempdir().unwrap(); diff --git a/src/data_dir.rs b/src/data_dir.rs index 15fda08..9728241 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -53,36 +53,53 @@ fn create_private_dir(dir: &Path) -> Result<()> { builder.recursive(true); #[cfg(unix)] std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); - builder - .create(dir) - .with_context(|| format!("Failed to create meta data directory at {}", dir.display()))?; + builder.create(dir).with_context(|| { + format!( + "Failed to create meta data directory at {}", + crate::display::escape_path(dir) + ) + })?; check_private_dir(dir) } /// Refuse a directory that another user owns or can write to: they could -/// replace the stores, locks or plugins in it. +/// replace the stores, locks or plugins in it. The same goes for every +/// directory above it (after following symlinks), since another user who can +/// rename entries there could swap the whole directory: each must belong to +/// you or root and be writable by no one else, unless it is sticky (`/tmp`). #[cfg(unix)] pub fn check_private_dir(dir: &Path) -> Result<()> { use std::os::unix::fs::MetadataExt; - let meta = - std::fs::metadata(dir).with_context(|| format!("Failed to stat {}", dir.display()))?; + let shown = crate::display::escape_path(dir); + let real = dir + .canonicalize() + .with_context(|| format!("Failed to resolve {shown}"))?; // SAFETY: geteuid has no preconditions and cannot fail. let uid = unsafe { libc::geteuid() }; + let meta = std::fs::metadata(&real).with_context(|| format!("Failed to stat {shown}"))?; if meta.uid() != uid { anyhow::bail!( - "Refusing to use {}: it is owned by uid {}, not by you (uid {uid})", - dir.display(), + "Refusing to use {shown}: it is owned by uid {}, not by you (uid {uid})", meta.uid() ); } if meta.mode() & 0o022 != 0 { anyhow::bail!( - "Refusing to use {}: other users can write to it (fix with: chmod go-w '{}')", - dir.display(), - dir.display() + "Refusing to use {shown}: other users can write to it (fix with: chmod go-w '{shown}')" ); } + for ancestor in real.ancestors().skip(1) { + let meta = std::fs::metadata(ancestor) + .with_context(|| format!("Failed to stat {}", crate::display::escape_path(ancestor)))?; + let sticky = meta.mode() & 0o1000 != 0; + if (meta.uid() != uid && meta.uid() != 0) || (meta.mode() & 0o022 != 0 && !sticky) { + anyhow::bail!( + "Refusing to use {shown}: another user could replace it through {}", + crate::display::escape_path(ancestor) + ); + } + } Ok(()) } @@ -119,6 +136,24 @@ mod tests { std::env::remove_var("META_DATA_DIR"); } + #[cfg(unix)] + #[test] + fn test_refuses_private_dir_under_shared_parent() { + use std::os::unix::fs::PermissionsExt; + + let tmp = tempfile::tempdir().unwrap(); + let shared = tmp.path().join("shared"); + let dir = shared.join("mine"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o777)).unwrap(); + let err = check_private_dir(&dir).unwrap_err().to_string(); + assert!(err.contains("another user could replace it"), "{err}"); + + // A sticky parent, like /tmp, keeps others from renaming it + std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o1777)).unwrap(); + check_private_dir(&dir).unwrap(); + } + #[cfg(unix)] #[test] fn test_refuses_dir_others_can_write() { diff --git a/src/lock.rs b/src/lock.rs index 5293789..53e91ef 100644 --- a/src/lock.rs +++ b/src/lock.rs @@ -11,6 +11,7 @@ //! be writable by group or others; anyone else who could write there could //! replace the lock file or the store beside it. +use crate::display::escape_path; use anyhow::{Context, Result}; use std::fs::{self, File, OpenOptions, TryLockError}; use std::path::{Path, PathBuf}; @@ -37,7 +38,7 @@ impl LockGuard { pub fn acquire(lock_path: &Path, timeout: Duration) -> Result { if let Some(parent) = lock_path.parent() { fs::create_dir_all(parent) - .with_context(|| format!("Failed to create lock directory: {}", parent.display()))?; + .with_context(|| format!("Failed to create lock directory: {}", escape_path(parent)))?; crate::data_dir::check_private_dir(parent)?; } let file = OpenOptions::new() @@ -46,7 +47,7 @@ pub fn acquire(lock_path: &Path, timeout: Duration) -> Result { .create(true) .truncate(false) .open(lock_path) - .with_context(|| format!("Failed to open lock file: {}", lock_path.display()))?; + .with_context(|| format!("Failed to open lock file: {}", escape_path(lock_path)))?; let deadline = Instant::now() + timeout; loop { @@ -63,10 +64,10 @@ pub fn acquire(lock_path: &Path, timeout: Duration) -> Result { Err(TryLockError::WouldBlock) => anyhow::bail!( "Timed out after {:?} waiting for the lock at {}: another meta process holds it", timeout, - lock_path.display() + escape_path(lock_path) ), Err(TryLockError::Error(e)) => { - return Err(e).with_context(|| format!("Failed to lock {}", lock_path.display())) + return Err(e).with_context(|| format!("Failed to lock {}", escape_path(lock_path))) } } } From e6d2713df860dd0fea1eec51866a6aa4c5b5096b Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 04/29] fix: check the data dir's whole path, including symlinks it follows check_private_dir walks the path as written, one component at a time, and checks the directory holding each entry and each symlink it follows, so a link to a private dir placed in a shared dir is refused. Implements [[tasks/harmony-2749]] --- src/data_dir.rs | 104 +++++++++++++++++++++++++++++++++++++----------- 1 file changed, 80 insertions(+), 24 deletions(-) diff --git a/src/data_dir.rs b/src/data_dir.rs index 9728241..4629155 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -63,43 +63,86 @@ fn create_private_dir(dir: &Path) -> Result<()> { } /// Refuse a directory that another user owns or can write to: they could -/// replace the stores, locks or plugins in it. The same goes for every -/// directory above it (after following symlinks), since another user who can -/// rename entries there could swap the whole directory: each must belong to -/// you or root and be writable by no one else, unless it is sticky (`/tmp`). +/// replace the stores, locks or plugins in it. +/// +/// The same goes for every directory the path passes through, as written and +/// through each symlink it follows, since another user who can rename entries +/// in one of them could swap what the path leads to. Each such directory must +/// belong to you or root and be writable by no one else, unless it is sticky +/// like `/tmp` (then only an entry's owner can rename it). #[cfg(unix)] pub fn check_private_dir(dir: &Path) -> Result<()> { + use std::ffi::OsString; use std::os::unix::fs::MetadataExt; + use std::path::Component; let shown = crate::display::escape_path(dir); - let real = dir - .canonicalize() - .with_context(|| format!("Failed to resolve {shown}"))?; // SAFETY: geteuid has no preconditions and cannot fail. let uid = unsafe { libc::geteuid() }; - let meta = std::fs::metadata(&real).with_context(|| format!("Failed to stat {shown}"))?; - if meta.uid() != uid { - anyhow::bail!( - "Refusing to use {shown}: it is owned by uid {}, not by you (uid {uid})", - meta.uid() - ); + let stat = |path: &Path| { + std::fs::symlink_metadata(path).with_context(|| { + format!( + "Failed to check {shown}: cannot stat {}", + crate::display::escape_path(path) + ) + }) + }; + + // Resolve the path one component at a time, checking the directory that + // holds each entry before following it. + let absolute = std::env::current_dir() + .context("Failed to read the current directory")? + .join(dir); + let mut pending: Vec = Vec::new(); + let push_rev = |pending: &mut Vec, path: &Path| { + for c in path.components().rev() { + match c { + Component::Normal(n) => pending.push(n.to_os_string()), + Component::ParentDir => pending.push(OsString::from("..")), + Component::RootDir | Component::Prefix(_) | Component::CurDir => {} + } + } + }; + push_rev(&mut pending, &absolute); + let mut current = PathBuf::from("/"); + let mut hops = 0; + while let Some(name) = pending.pop() { + if name == ".." { + current.pop(); + continue; + } + let holder = stat(¤t)?; + let sticky = holder.mode() & 0o1000 != 0; + if (holder.uid() != uid && holder.uid() != 0) || (holder.mode() & 0o022 != 0 && !sticky) { + anyhow::bail!( + "Refusing to use {shown}: another user could replace it through {}", + crate::display::escape_path(¤t) + ); + } + let next = current.join(&name); + if stat(&next)?.file_type().is_symlink() { + hops += 1; + anyhow::ensure!(hops <= 40, "Failed to check {shown}: too many symlinks"); + let target = std::fs::read_link(&next) + .with_context(|| format!("Failed to check {shown}: cannot read a symlink"))?; + if target.is_absolute() { + current = PathBuf::from("/"); + } + push_rev(&mut pending, &target); + } else { + current = next; + } + } + + let meta = stat(¤t)?; + if !meta.is_dir() || meta.uid() != uid { + anyhow::bail!("Refusing to use {shown}: it is not a directory owned by you (uid {uid})"); } if meta.mode() & 0o022 != 0 { anyhow::bail!( "Refusing to use {shown}: other users can write to it (fix with: chmod go-w '{shown}')" ); } - for ancestor in real.ancestors().skip(1) { - let meta = std::fs::metadata(ancestor) - .with_context(|| format!("Failed to stat {}", crate::display::escape_path(ancestor)))?; - let sticky = meta.mode() & 0o1000 != 0; - if (meta.uid() != uid && meta.uid() != 0) || (meta.mode() & 0o022 != 0 && !sticky) { - anyhow::bail!( - "Refusing to use {shown}: another user could replace it through {}", - crate::display::escape_path(ancestor) - ); - } - } Ok(()) } @@ -149,6 +192,19 @@ mod tests { let err = check_private_dir(&dir).unwrap_err().to_string(); assert!(err.contains("another user could replace it"), "{err}"); + // A link to it from a shared dir is refused too: the link can be swapped + let link_home = tmp.path().join("links"); + std::fs::create_dir(&link_home).unwrap(); + std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o755)).unwrap(); + check_private_dir(&dir).unwrap(); + std::os::unix::fs::symlink(&dir, link_home.join("meta")).unwrap(); + check_private_dir(&link_home.join("meta")).unwrap(); + std::fs::set_permissions(&link_home, std::fs::Permissions::from_mode(0o777)).unwrap(); + let err = check_private_dir(&link_home.join("meta")) + .unwrap_err() + .to_string(); + assert!(err.contains("another user could replace it"), "{err}"); + // A sticky parent, like /tmp, keeps others from renaming it std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o1777)).unwrap(); check_private_dir(&dir).unwrap(); From d9b93ddce60ba459722ef3c21b2234ae2d3dd1d0 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 05/29] fix: refuse another user's symlink in the data dir path; allow alias steps to the workspace A symlink on the way to the data dir must belong to you or root: in a sticky shared dir its owner could still replace it. A project path may pass through a symlink to the config's own directory (here -> .), and is refused only when it ends there. Config and store errors escape their paths. Implements [[tasks/harmony-2749]] --- src/config.rs | 78 ++++++++++++++++++++++++++++++++++++++++++------- src/data_dir.rs | 13 +++++++-- src/store.rs | 11 +++---- 3 files changed, 85 insertions(+), 17 deletions(-) diff --git a/src/config.rs b/src/config.rs index f2014a6..da3d9d4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -167,17 +167,29 @@ pub fn find_meta_config( /// share or nest paths ([`check_no_overlap`]); a bad entry fails the parse /// with the file and project named. pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, Vec)> { - let config_str = std::fs::read_to_string(meta_path) - .with_context(|| format!("Failed to read meta config file: '{}'", meta_path.display()))?; + let config_str = std::fs::read_to_string(meta_path).with_context(|| { + format!( + "Failed to read meta config file: '{}'", + escape_path(meta_path) + ) + })?; // Determine format from file extension let path_str = meta_path.to_string_lossy(); let config: MetaConfig = if path_str.ends_with(".yaml") || path_str.ends_with(".yml") { - serde_yaml_ng::from_str(&config_str) - .with_context(|| format!("Failed to parse YAML config file: {}", meta_path.display()))? + serde_yaml_ng::from_str(&config_str).with_context(|| { + format!( + "Failed to parse YAML config file: {}", + escape_path(meta_path) + ) + })? } else { - serde_json::from_str(&config_str) - .with_context(|| format!("Failed to parse JSON config file: {}", meta_path.display()))? + serde_json::from_str(&config_str).with_context(|| { + format!( + "Failed to parse JSON config file: {}", + escape_path(meta_path) + ) + })? }; // Convert project entries to normalized, validated ProjectInfo @@ -370,7 +382,7 @@ fn normalize_project_path(raw: &str) -> Result { } /// Resolve `rel` below `base_dir` through the symlinks that exist now, and -/// refuse it if one leads outside `base_dir` or if it is `base_dir` itself. +/// refuse it if one leads outside `base_dir` or if it ends at `base_dir`. /// Returns the project's location: the real path of the part that exists, /// followed by the part not created yet. fn resolve_inside(base_dir: &Path, rel: &str) -> Result { @@ -387,7 +399,7 @@ fn resolve_inside(base_dir: &Path, rel: &str) -> Result { match current.symlink_metadata() { Err(_) => exists = false, Ok(meta) if meta.file_type().is_symlink() => match current.canonicalize() { - Ok(target) if target.starts_with(&base) && target != base => current = target, + Ok(target) if target.starts_with(&base) => current = target, _ => { return Err(format!( "path '{rel}' leads outside {} through the symlink '{}'", @@ -399,6 +411,11 @@ fn resolve_inside(base_dir: &Path, rel: &str) -> Result { Ok(_) => {} } } + if current == base { + return Err(format!( + "path '{rel}' leads to the directory of the .meta file itself" + )); + } Ok(current) } @@ -450,7 +467,7 @@ pub fn walk_meta_tree( max_depth: Option, ) -> anyhow::Result> { let (config_path, _format) = find_meta_config(start_dir, None) - .ok_or_else(|| anyhow::anyhow!("No .meta config found in {}", start_dir.display()))?; + .ok_or_else(|| anyhow::anyhow!("No .meta config found in {}", escape_path(start_dir)))?; let (projects, _ignore) = parse_meta_config(&config_path)?; let meta_dir = config_path.parent().unwrap_or(Path::new(".")); @@ -761,7 +778,10 @@ mod tests { #[cfg(unix)] { let err = walk_meta_tree(dir.path(), None).unwrap_err().to_string(); - assert!(err.contains("through the symlink"), "{err}"); + assert!( + err.contains("leads to the directory of the .meta file itself"), + "{err}" + ); } } @@ -1322,6 +1342,44 @@ mod tests { ); } + #[cfg(unix)] + #[test] + fn test_parse_allows_symlink_alias_of_the_workspace_itself() { + // `here -> .` is harmless as a step on the way; only ending at the + // config's own directory is refused + let dir = tempfile::tempdir().unwrap(); + std::os::unix::fs::symlink(dir.path(), dir.path().join("here")).unwrap(); + let meta = dir.path().join(".meta"); + std::fs::write( + &meta, + r#"{"projects": {"svc": {"repo": "u", "path": "here/service"}}}"#, + ) + .unwrap(); + assert!(parse_meta_config(&meta).is_ok()); + + std::fs::write( + &meta, + r#"{"projects": {"svc": {"repo": "u", "path": "here"}}}"#, + ) + .unwrap(); + let err = parse_meta_config(&meta).unwrap_err().to_string(); + assert!( + err.contains("leads to the directory of the .meta file itself"), + "{err}" + ); + } + + #[test] + fn test_config_errors_escape_the_path() { + let dir = tempfile::tempdir().unwrap(); + let ws = dir.path().join("ws\nfake line\u{1b}[2J"); + std::fs::create_dir(&ws).unwrap(); + std::fs::write(ws.join(".meta"), "{not json").unwrap(); + let err = format!("{:#}", parse_meta_config(&ws.join(".meta")).unwrap_err()); + assert!(!err.contains('\n') && !err.contains('\u{1b}'), "{err}"); + assert!(err.contains("ws\\nfake line\\u{1b}[2J"), "{err}"); + } + #[test] fn test_parse_rejects_drive_prefixes_anywhere() { for json in [ diff --git a/src/data_dir.rs b/src/data_dir.rs index 4629155..c55b026 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -69,7 +69,8 @@ fn create_private_dir(dir: &Path) -> Result<()> { /// through each symlink it follows, since another user who can rename entries /// in one of them could swap what the path leads to. Each such directory must /// belong to you or root and be writable by no one else, unless it is sticky -/// like `/tmp` (then only an entry's owner can rename it). +/// like `/tmp` (then only an entry's owner can rename it), and every symlink +/// followed must belong to you or root. #[cfg(unix)] pub fn check_private_dir(dir: &Path) -> Result<()> { use std::ffi::OsString; @@ -120,7 +121,15 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { ); } let next = current.join(&name); - if stat(&next)?.file_type().is_symlink() { + let entry = stat(&next)?; + if entry.file_type().is_symlink() { + // In a sticky directory the link's owner can still replace it + if entry.uid() != uid && entry.uid() != 0 { + anyhow::bail!( + "Refusing to use {shown}: the symlink {} belongs to another user", + crate::display::escape_path(&next) + ); + } hops += 1; anyhow::ensure!(hops <= 40, "Failed to check {shown}: too many symlinks"); let target = std::fs::read_link(&next) diff --git a/src/store.rs b/src/store.rs index c04eb02..c2eff46 100644 --- a/src/store.rs +++ b/src/store.rs @@ -4,6 +4,7 @@ //! with atomic write semantics (write to `.tmp`, then rename) and optional //! lock protection for concurrent access. +use crate::display::escape_path; use anyhow::{Context, Result}; use serde::de::DeserializeOwned; use serde::Serialize; @@ -18,14 +19,14 @@ pub fn read(path: &Path) -> Result { } let content = std::fs::read_to_string(path) - .with_context(|| format!("Failed to read store file: {}", path.display()))?; + .with_context(|| format!("Failed to read store file: {}", escape_path(path)))?; if content.trim().is_empty() { return Ok(T::default()); } serde_json::from_str(&content) - .with_context(|| format!("Failed to parse store file: {}", path.display())) + .with_context(|| format!("Failed to parse store file: {}", escape_path(path))) } /// Write data to a JSON file atomically. @@ -37,7 +38,7 @@ pub fn write_atomic(path: &Path, data: &T) -> Result<()> { if let Some(parent) = path.parent() { if !parent.exists() { std::fs::create_dir_all(parent) - .with_context(|| format!("Failed to create directory: {}", parent.display()))?; + .with_context(|| format!("Failed to create directory: {}", escape_path(parent)))?; } } @@ -47,10 +48,10 @@ pub fn write_atomic(path: &Path, data: &T) -> Result<()> { serde_json::to_string_pretty(data).with_context(|| "Failed to serialize store data")?; std::fs::write(&tmp_path, &json) - .with_context(|| format!("Failed to write temp file: {}", tmp_path.display()))?; + .with_context(|| format!("Failed to write temp file: {}", escape_path(&tmp_path)))?; std::fs::rename(&tmp_path, path) - .with_context(|| format!("Failed to rename temp file to: {}", path.display()))?; + .with_context(|| format!("Failed to rename temp file to: {}", escape_path(path)))?; Ok(()) } From aecf80cfa28da15f3ba8bb31c1e557a57adcbb5f Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 06/29] fix: check a directory before leaving it through '..'; keep a Unix-only test off Windows check_private_dir now checks the current directory before every step of the walk, '..' included, so a replaceable directory cannot be skipped by stepping back out of it. Implements [[tasks/harmony-2749]] --- src/config.rs | 1 + src/data_dir.rs | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/config.rs b/src/config.rs index da3d9d4..cceecc3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1369,6 +1369,7 @@ mod tests { ); } + #[cfg(unix)] // Windows refuses control characters in file names #[test] fn test_config_errors_escape_the_path() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/data_dir.rs b/src/data_dir.rs index c55b026..130fe44 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -108,10 +108,9 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { let mut current = PathBuf::from("/"); let mut hops = 0; while let Some(name) = pending.pop() { - if name == ".." { - current.pop(); - continue; - } + // Check the directory we are in before any step, `..` included: + // leaving a directory through `..` depends on it as much as entering + // one of its entries does let holder = stat(¤t)?; let sticky = holder.mode() & 0o1000 != 0; if (holder.uid() != uid && holder.uid() != 0) || (holder.mode() & 0o022 != 0 && !sticky) { @@ -120,6 +119,10 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { crate::display::escape_path(¤t) ); } + if name == ".." { + current.pop(); + continue; + } let next = current.join(&name); let entry = stat(&next)?; if entry.file_type().is_symlink() { @@ -214,6 +217,12 @@ mod tests { .to_string(); assert!(err.contains("another user could replace it"), "{err}"); + // `..` leaves a directory, which must be safe as well + let err = check_private_dir(&tmp.path().join("links/../shared/mine")) + .unwrap_err() + .to_string(); + assert!(err.contains("another user could replace it"), "{err}"); + // A sticky parent, like /tmp, keeps others from renaming it std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o1777)).unwrap(); check_private_dir(&dir).unwrap(); From 825c7ef31522e5ee278f6a637639ea84636d7bee Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 07/29] fix: check data dir ownership and access on Windows; one private-dir create path On Windows check_private_dir reads the directory's owner and access list (and those of the directories above it) and refuses one that an account other than you, SYSTEM, Administrators or TrustedInstaller owns or may change. Lock and store directories are created through create_private_dir. The current directory is read only for a relative path, and a refusal through a parent says what it requires. Implements [[tasks/harmony-2749]] --- Cargo.toml | 8 +++ src/data_dir.rs | 82 +++++++++++++++++++++-- src/lib.rs | 2 + src/lock.rs | 7 +- src/store.rs | 3 +- src/win_acl.rs | 171 ++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 260 insertions(+), 13 deletions(-) create mode 100644 src/win_acl.rs diff --git a/Cargo.toml b/Cargo.toml index f01ce21..fbed290 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,5 +17,13 @@ chrono = { version = "0.4", features = ["serde"] } [target.'cfg(unix)'.dependencies] libc = "0.2" +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_Security_Authorization", + "Win32_System_Threading", +] } + [dev-dependencies] tempfile = "3.3" diff --git a/src/data_dir.rs b/src/data_dir.rs index 130fe44..a2da93f 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -48,7 +48,7 @@ pub fn data_subdir(namespace: &str) -> Result { } /// Create `dir` (mode 0700 on Unix) if missing, then check it is private. -fn create_private_dir(dir: &Path) -> Result<()> { +pub(crate) fn create_private_dir(dir: &Path) -> Result<()> { let mut builder = std::fs::DirBuilder::new(); builder.recursive(true); #[cfg(unix)] @@ -91,9 +91,13 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { // Resolve the path one component at a time, checking the directory that // holds each entry before following it. - let absolute = std::env::current_dir() - .context("Failed to read the current directory")? - .join(dir); + let absolute = if dir.is_absolute() { + dir.to_path_buf() + } else { + std::env::current_dir() + .context("Failed to read the current directory")? + .join(dir) + }; let mut pending: Vec = Vec::new(); let push_rev = |pending: &mut Vec, path: &Path| { for c in path.components().rev() { @@ -115,7 +119,8 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { let sticky = holder.mode() & 0o1000 != 0; if (holder.uid() != uid && holder.uid() != 0) || (holder.mode() & 0o022 != 0 && !sticky) { anyhow::bail!( - "Refusing to use {shown}: another user could replace it through {}", + "Refusing to use {shown}: another user could replace it through {} \ + (it must belong to you or root and not be writable by others)", crate::display::escape_path(¤t) ); } @@ -158,8 +163,35 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { Ok(()) } -/// Refuse a directory that another user owns or can write to. -#[cfg(not(unix))] +/// Refuse a directory that an account other than you, SYSTEM, +/// Administrators or TrustedInstaller owns or may change, or that sits in a +/// directory where such an account could rename or replace it. +#[cfg(windows)] +pub fn check_private_dir(dir: &Path) -> Result<()> { + use crate::win_acl::{current_user_sid, untrusted_access, ANCESTOR_RIGHTS, DIR_RIGHTS}; + + let shown = crate::display::escape_path(dir); + let user = current_user_sid()?; + let written = std::path::absolute(dir).with_context(|| format!("Failed to resolve {shown}"))?; + let real = dir + .canonicalize() + .with_context(|| format!("Failed to resolve {shown}"))?; + if let Some(why) = untrusted_access(&real, &user, DIR_RIGHTS)? { + anyhow::bail!("Refusing to use {shown}: {why}"); + } + for ancestor in real.ancestors().skip(1).chain(written.ancestors().skip(1)) { + if let Some(why) = untrusted_access(ancestor, &user, ANCESTOR_RIGHTS)? { + anyhow::bail!( + "Refusing to use {shown}: another user could replace it through {} ({why})", + crate::display::escape_path(ancestor) + ); + } + } + Ok(()) +} + +/// No ownership model to check on other platforms. +#[cfg(not(any(unix, windows)))] pub fn check_private_dir(_dir: &Path) -> Result<()> { Ok(()) } @@ -228,6 +260,42 @@ mod tests { check_private_dir(&dir).unwrap(); } + #[cfg(windows)] + #[test] + fn test_windows_refuses_dir_others_can_change() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("shared"); + std::fs::create_dir(&dir).unwrap(); + check_private_dir(&dir).unwrap(); + + // Let Everyone modify it + let granted = std::process::Command::new("icacls") + .arg(&dir) + .args(["/grant", "*S-1-1-0:(OI)(CI)M"]) + .status() + .unwrap(); + assert!(granted.success()); + let err = check_private_dir(&dir).unwrap_err().to_string(); + assert!(err.contains("S-1-1-0 may change it"), "{err}"); + + // A private directory inside it can be replaced through it + let inner = dir.join("inner"); + std::fs::create_dir(&inner).unwrap(); + let removed = std::process::Command::new("icacls") + .arg(&inner) + .args([ + "/inheritance:r", + "/grant:r", + "*S-1-5-32-544:(OI)(CI)F", + "*S-1-5-18:(OI)(CI)F", + ]) + .status() + .unwrap(); + assert!(removed.success()); + let err = check_private_dir(&inner).unwrap_err().to_string(); + assert!(err.contains("another user could replace it"), "{err}"); + } + #[cfg(unix)] #[test] fn test_refuses_dir_others_can_write() { diff --git a/src/lib.rs b/src/lib.rs index 09d6146..407b1f8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,6 +13,8 @@ pub mod data_dir; pub mod display; pub mod lock; pub mod store; +#[cfg(windows)] +mod win_acl; /// Default meta data directory name. const META_DIR_NAME: &str = ".meta"; diff --git a/src/lock.rs b/src/lock.rs index 53e91ef..827870d 100644 --- a/src/lock.rs +++ b/src/lock.rs @@ -13,7 +13,7 @@ use crate::display::escape_path; use anyhow::{Context, Result}; -use std::fs::{self, File, OpenOptions, TryLockError}; +use std::fs::{File, OpenOptions, TryLockError}; use std::path::{Path, PathBuf}; use std::thread; use std::time::{Duration, Instant}; @@ -37,9 +37,7 @@ impl LockGuard { /// Waits up to `timeout` while another process holds the lock, then fails. pub fn acquire(lock_path: &Path, timeout: Duration) -> Result { if let Some(parent) = lock_path.parent() { - fs::create_dir_all(parent) - .with_context(|| format!("Failed to create lock directory: {}", escape_path(parent)))?; - crate::data_dir::check_private_dir(parent)?; + crate::data_dir::create_private_dir(parent)?; } let file = OpenOptions::new() .read(true) @@ -76,6 +74,7 @@ pub fn acquire(lock_path: &Path, timeout: Duration) -> Result { #[cfg(test)] mod tests { use super::*; + use std::fs; const WAIT: Duration = Duration::from_millis(200); diff --git a/src/store.rs b/src/store.rs index c2eff46..7a218ce 100644 --- a/src/store.rs +++ b/src/store.rs @@ -37,8 +37,7 @@ pub fn write_atomic(path: &Path, data: &T) -> Result<()> { // Ensure parent directory exists if let Some(parent) = path.parent() { if !parent.exists() { - std::fs::create_dir_all(parent) - .with_context(|| format!("Failed to create directory: {}", escape_path(parent)))?; + crate::data_dir::create_private_dir(parent)?; } } diff --git a/src/win_acl.rs b/src/win_acl.rs new file mode 100644 index 0000000..6cf31cc --- /dev/null +++ b/src/win_acl.rs @@ -0,0 +1,171 @@ +//! The Windows side of `data_dir::check_private_dir`: read a directory's +//! owner and access list, and report an account other than you, SYSTEM, +//! Administrators or TrustedInstaller that owns it or holds given rights on it. + +use anyhow::{bail, Result}; +use std::ffi::c_void; +use std::os::windows::ffi::OsStrExt; +use std::path::Path; +use std::ptr::null_mut; +use windows_sys::Win32::Foundation::{CloseHandle, LocalFree, HANDLE}; +use windows_sys::Win32::Security::Authorization::{ + ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT, +}; +use windows_sys::Win32::Security::{ + GetAce, GetTokenInformation, TokenUser, ACCESS_ALLOWED_ACE, ACE_HEADER, ACL, + DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID, TOKEN_QUERY, + TOKEN_USER, +}; +use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken}; + +const ACCESS_ALLOWED_ACE_TYPE: u8 = 0; +const ACCESS_ALLOWED_CALLBACK_ACE_TYPE: u8 = 9; +const INHERIT_ONLY_ACE: u8 = 0x08; + +const FILE_ADD_FILE: u32 = 0x2; +const FILE_ADD_SUBDIRECTORY: u32 = 0x4; +const FILE_DELETE_CHILD: u32 = 0x40; +const DELETE: u32 = 0x1_0000; +const WRITE_DAC: u32 = 0x4_0000; +const WRITE_OWNER: u32 = 0x8_0000; +const GENERIC_ALL: u32 = 0x1000_0000; +const GENERIC_WRITE: u32 = 0x4000_0000; + +/// Rights on the data directory itself that would let an account change +/// what it holds, or who may. +pub const DIR_RIGHTS: u32 = FILE_ADD_FILE + | FILE_ADD_SUBDIRECTORY + | FILE_DELETE_CHILD + | DELETE + | WRITE_DAC + | WRITE_OWNER + | GENERIC_ALL + | GENERIC_WRITE; + +/// Rights on a directory above it that would let an account rename or +/// replace what it holds, or change who may. +pub const ANCESTOR_RIGHTS: u32 = FILE_DELETE_CHILD | DELETE | WRITE_DAC | WRITE_OWNER | GENERIC_ALL; + +/// SYSTEM, Administrators and TrustedInstaller, which can change anything anyway. +const SYSTEM_SIDS: [&str; 3] = [ + "S-1-5-18", + "S-1-5-32-544", + "S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464", +]; + +/// The current user's SID, such as `S-1-5-21-…`. +pub fn current_user_sid() -> Result { + // SAFETY: the token handle is closed before returning; the buffer is + // u64-aligned and as long as GetTokenInformation asked for, so it holds + // a TOKEN_USER whose SID points into the buffer. + unsafe { + let mut token: HANDLE = null_mut(); + if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 { + bail!( + "Cannot read the current user: {}", + std::io::Error::last_os_error() + ); + } + let mut len = 0u32; + GetTokenInformation(token, TokenUser, null_mut(), 0, &mut len); + let mut buf = vec![0u64; (len as usize).div_ceil(8)]; + let ok = GetTokenInformation(token, TokenUser, buf.as_mut_ptr().cast(), len, &mut len); + let error = std::io::Error::last_os_error(); + CloseHandle(token); + if ok == 0 { + bail!("Cannot read the current user: {error}"); + } + let user = &*buf.as_ptr().cast::(); + sid_string(user.User.Sid) + } +} + +/// Why an account other than `user` and the system's own could change +/// `dir`, if one could: it owns `dir`, there is no access list, or an entry +/// that applies to `dir` grants it any of `rights`. +pub fn untrusted_access(dir: &Path, user: &str, rights: u32) -> Result> { + let wide: Vec = dir.as_os_str().encode_wide().chain(Some(0)).collect(); + let trusted = |sid: &str| sid == user || SYSTEM_SIDS.contains(&sid); + // SAFETY: GetNamedSecurityInfoW fills `owner` and `dacl` with pointers + // into the descriptor `sd`, which stays allocated until LocalFree below; + // GetAce returns pointers into that same access list. + unsafe { + let mut owner: PSID = null_mut(); + let mut dacl: *mut ACL = null_mut(); + let mut sd: PSECURITY_DESCRIPTOR = null_mut(); + let error = GetNamedSecurityInfoW( + wide.as_ptr(), + SE_FILE_OBJECT, + OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, + &mut owner, + null_mut(), + &mut dacl, + null_mut(), + &mut sd, + ); + if error != 0 { + bail!( + "Cannot read who may change {}: {}", + crate::display::escape_path(dir), + std::io::Error::from_raw_os_error(error as i32) + ); + } + let found = (|| -> Result> { + let owner = sid_string(owner)?; + if !trusted(&owner) { + return Ok(Some(format!("it is owned by {owner}"))); + } + if dacl.is_null() { + return Ok(Some( + "it has no access list, so anyone may change it".into(), + )); + } + for index in 0..u32::from((*dacl).AceCount) { + let mut ace: *mut c_void = null_mut(); + if GetAce(dacl, index, &mut ace) == 0 { + bail!( + "Cannot read its access list: {}", + std::io::Error::last_os_error() + ); + } + let header = &*ace.cast::(); + // Entries for children only, and deny or audit entries, + // grant nothing on this directory. + if header.AceFlags & INHERIT_ONLY_ACE != 0 + || !matches!( + header.AceType, + ACCESS_ALLOWED_ACE_TYPE | ACCESS_ALLOWED_CALLBACK_ACE_TYPE + ) + { + continue; + } + let allowed = &*ace.cast::(); + if allowed.Mask & rights == 0 { + continue; + } + let sid = sid_string(std::ptr::addr_of!(allowed.SidStart).cast_mut().cast())?; + if !trusted(&sid) { + return Ok(Some(format!("{sid} may change it"))); + } + } + Ok(None) + })(); + LocalFree(sd); + found + } +} + +/// A SID as text, such as `S-1-5-18`. +unsafe fn sid_string(sid: PSID) -> Result { + let mut wide = null_mut(); + if ConvertSidToStringSidW(sid, &mut wide) == 0 { + bail!("Cannot read a SID: {}", std::io::Error::last_os_error()); + } + let mut len = 0; + while *wide.add(len) != 0 { + len += 1; + } + let text = String::from_utf16_lossy(std::slice::from_raw_parts(wide, len)); + LocalFree(wide.cast()); + Ok(text) +} From f001473d0789a1c3fc5f903b1a003739d105ef59 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 08/29] fix: accept your private group and root-owned dirs; refuse links on Windows; escape invisible format characters A group-writable directory is fine when its group is your own private group (named after you, no other members), as umask 002 systems create them. A root-owned directory passes like a root-owned parent. On Windows, a link or junction anywhere in the data dir path is refused and each directory on the way is checked. U+061C, zero-width and tag characters are escaped like bidi controls. A symlink that cannot be resolved gets its own message; a uid 65534 owner gets a note about user namespaces. Implements [[tasks/harmony-2749]] --- src/config.rs | 10 ++- src/data_dir.rs | 179 +++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 162 insertions(+), 27 deletions(-) diff --git a/src/config.rs b/src/config.rs index cceecc3..133a480 100644 --- a/src/config.rs +++ b/src/config.rs @@ -400,13 +400,21 @@ fn resolve_inside(base_dir: &Path, rel: &str) -> Result { Err(_) => exists = false, Ok(meta) if meta.file_type().is_symlink() => match current.canonicalize() { Ok(target) if target.starts_with(&base) => current = target, - _ => { + Ok(_) => { return Err(format!( "path '{rel}' leads outside {} through the symlink '{}'", escape_path(&base), escape_path(¤t) )) } + // Its target may not exist yet, but where it would lead + // cannot be checked, so it is refused + Err(e) => { + return Err(format!( + "path '{rel}' goes through the symlink '{}', which cannot be resolved: {e}", + escape_path(¤t) + )) + } }, Ok(_) => {} } diff --git a/src/data_dir.rs b/src/data_dir.rs index a2da93f..9f0d382 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -74,7 +74,6 @@ pub(crate) fn create_private_dir(dir: &Path) -> Result<()> { #[cfg(unix)] pub fn check_private_dir(dir: &Path) -> Result<()> { use std::ffi::OsString; - use std::os::unix::fs::MetadataExt; use std::path::Component; let shown = crate::display::escape_path(dir); @@ -116,12 +115,12 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { // leaving a directory through `..` depends on it as much as entering // one of its entries does let holder = stat(¤t)?; - let sticky = holder.mode() & 0o1000 != 0; - if (holder.uid() != uid && holder.uid() != 0) || (holder.mode() & 0o022 != 0 && !sticky) { + if !owned_by_you_or_root(&holder, uid) || !only_you_can_write(&holder, uid, true) { anyhow::bail!( "Refusing to use {shown}: another user could replace it through {} \ - (it must belong to you or root and not be writable by others)", - crate::display::escape_path(¤t) + (it must belong to you or root and not be writable by others){}", + crate::display::escape_path(¤t), + outside_namespace_note(&holder) ); } if name == ".." { @@ -132,10 +131,11 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { let entry = stat(&next)?; if entry.file_type().is_symlink() { // In a sticky directory the link's owner can still replace it - if entry.uid() != uid && entry.uid() != 0 { + if !owned_by_you_or_root(&entry, uid) { anyhow::bail!( - "Refusing to use {shown}: the symlink {} belongs to another user", - crate::display::escape_path(&next) + "Refusing to use {shown}: the symlink {} belongs to another user{}", + crate::display::escape_path(&next), + outside_namespace_note(&entry) ); } hops += 1; @@ -152,10 +152,13 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { } let meta = stat(¤t)?; - if !meta.is_dir() || meta.uid() != uid { - anyhow::bail!("Refusing to use {shown}: it is not a directory owned by you (uid {uid})"); + if !meta.is_dir() || !owned_by_you_or_root(&meta, uid) { + anyhow::bail!( + "Refusing to use {shown}: it is not a directory owned by you (uid {uid}){}", + outside_namespace_note(&meta) + ); } - if meta.mode() & 0o022 != 0 { + if !only_you_can_write(&meta, uid, false) { anyhow::bail!( "Refusing to use {shown}: other users can write to it (fix with: chmod go-w '{shown}')" ); @@ -163,29 +166,117 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { Ok(()) } +#[cfg(unix)] +fn owned_by_you_or_root(meta: &std::fs::Metadata, uid: u32) -> bool { + use std::os::unix::fs::MetadataExt; + meta.uid() == uid || meta.uid() == 0 +} + +/// No one but you (and root) can change the entries of this directory: it is +/// not writable by others, or only for its group when that group is your own +/// private group, or (when `sticky_ok`) it is sticky, so only an entry's +/// owner can rename that entry. +#[cfg(unix)] +fn only_you_can_write(meta: &std::fs::Metadata, uid: u32, sticky_ok: bool) -> bool { + use std::os::unix::fs::MetadataExt; + if sticky_ok && meta.mode() & 0o1000 != 0 { + return true; + } + meta.mode() & 0o002 == 0 && (meta.mode() & 0o020 == 0 || is_private_group(meta.gid(), uid)) +} + +/// Whether `gid` is the user's own private group, as on systems that give +/// every user a group of their own (and umask 002): the user's primary +/// group, named after the user, with no other members. +#[cfg(unix)] +fn is_private_group(gid: u32, uid: u32) -> bool { + use std::ffi::CStr; + use std::ptr::null_mut; + + // SAFETY: the reentrant lookups write only into the structs and buffers + // passed in, and the strings read here point into those buffers. + unsafe { + let mut pwd: libc::passwd = std::mem::zeroed(); + let mut found: *mut libc::passwd = null_mut(); + let mut pw_buf = vec![0 as libc::c_char; 16 * 1024]; + if libc::getpwuid_r(uid, &mut pwd, pw_buf.as_mut_ptr(), pw_buf.len(), &mut found) != 0 + || found.is_null() + || pwd.pw_gid != gid + { + return false; + } + let user = CStr::from_ptr(pwd.pw_name); + + let mut grp: libc::group = std::mem::zeroed(); + let mut found: *mut libc::group = null_mut(); + let mut gr_buf = vec![0 as libc::c_char; 64 * 1024]; + if libc::getgrgid_r(gid, &mut grp, gr_buf.as_mut_ptr(), gr_buf.len(), &mut found) != 0 + || found.is_null() + || CStr::from_ptr(grp.gr_name) != user + { + return false; + } + let mut member = grp.gr_mem; + while !member.is_null() && !(*member).is_null() { + if CStr::from_ptr(*member) != user { + return false; + } + member = member.add(1); + } + true + } +} + +/// In a user namespace that maps only you (some sandboxes), files of every +/// other account, root included, show as the overflow uid 65534. +#[cfg(unix)] +fn outside_namespace_note(meta: &std::fs::Metadata) -> &'static str { + use std::os::unix::fs::MetadataExt; + if meta.uid() == 65534 { + "; it shows as uid 65534, an account outside this user namespace, as inside \ + some sandboxes, which meta cannot tell apart from another user" + } else { + "" + } +} + /// Refuse a directory that an account other than you, SYSTEM, /// Administrators or TrustedInstaller owns or may change, or that sits in a -/// directory where such an account could rename or replace it. +/// directory where such an account could rename or replace it. A link or +/// junction on the way is refused too: whoever controls it could point it +/// elsewhere after this check. #[cfg(windows)] pub fn check_private_dir(dir: &Path) -> Result<()> { use crate::win_acl::{current_user_sid, untrusted_access, ANCESTOR_RIGHTS, DIR_RIGHTS}; let shown = crate::display::escape_path(dir); let user = current_user_sid()?; + // Windows resolves `..` by the name, so the absolute path is the one used let written = std::path::absolute(dir).with_context(|| format!("Failed to resolve {shown}"))?; - let real = dir - .canonicalize() - .with_context(|| format!("Failed to resolve {shown}"))?; - if let Some(why) = untrusted_access(&real, &user, DIR_RIGHTS)? { - anyhow::bail!("Refusing to use {shown}: {why}"); - } - for ancestor in real.ancestors().skip(1).chain(written.ancestors().skip(1)) { - if let Some(why) = untrusted_access(ancestor, &user, ANCESTOR_RIGHTS)? { - anyhow::bail!( - "Refusing to use {shown}: another user could replace it through {} ({why})", - crate::display::escape_path(ancestor) - ); + let mut ancestors: Vec<&Path> = written.ancestors().collect(); + ancestors.reverse(); + let mut holder: Option<&Path> = None; + for path in ancestors { + if let Some(holder) = holder { + if let Some(why) = untrusted_access(holder, &user, ANCESTOR_RIGHTS)? { + anyhow::bail!( + "Refusing to use {shown}: another user could replace it through {} ({why})", + crate::display::escape_path(holder) + ); + } + let meta = std::fs::symlink_metadata(path) + .with_context(|| format!("Failed to check {shown}"))?; + if meta.file_type().is_symlink() { + anyhow::bail!( + "Refusing to use {shown}: {} is a link or junction; use the real directory", + crate::display::escape_path(path) + ); + } } + holder = Some(path); + } + if let Some(why) = untrusted_access(&written, &user, DIR_RIGHTS)? { + anyhow::bail!("Refusing to use {shown}: {why}"); } Ok(()) } @@ -202,9 +293,10 @@ mod tests { #[test] fn test_data_file_path() { - std::env::set_var("META_DATA_DIR", "/tmp/test-meta"); + let tmp = tempfile::tempdir().unwrap(); + std::env::set_var("META_DATA_DIR", tmp.path()); let path = data_file("worktree").unwrap(); - assert_eq!(path, PathBuf::from("/tmp/test-meta/worktree.json")); + assert_eq!(path, tmp.path().join("worktree.json")); std::env::remove_var("META_DATA_DIR"); } @@ -294,6 +386,41 @@ mod tests { assert!(removed.success()); let err = check_private_dir(&inner).unwrap_err().to_string(); assert!(err.contains("another user could replace it"), "{err}"); + + // A junction to a private directory is refused: it could be repointed + let private = tmp.path().join("private"); + std::fs::create_dir(&private).unwrap(); + let junction = tmp.path().join("junction"); + let made = std::process::Command::new("cmd") + .args(["/C", "mklink", "/J"]) + .arg(&junction) + .arg(&private) + .status() + .unwrap(); + assert!(made.success()); + check_private_dir(&private).unwrap(); + let err = check_private_dir(&junction).unwrap_err().to_string(); + assert!(err.contains("is a link or junction"), "{err}"); + } + + #[cfg(unix)] + #[test] + fn test_group_write_is_fine_only_for_your_private_group() { + use std::os::unix::fs::PermissionsExt; + + // A 0775 directory gets your primary group; whether that group is + // private to you depends on the machine, and decides the outcome + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("ws"); + std::fs::create_dir(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o775)).unwrap(); + // SAFETY: no preconditions + let (uid, gid) = unsafe { (libc::geteuid(), libc::getegid()) }; + let gid_of_dir = std::os::unix::fs::MetadataExt::gid(&std::fs::metadata(&dir).unwrap()); + let private = gid_of_dir == gid && is_private_group(gid, uid); + assert_eq!(check_private_dir(&dir).is_ok(), private); + // A group that is not yours never counts + assert!(!is_private_group(gid.wrapping_add(1), uid)); } #[cfg(unix)] From 173959e8f36e441ea2ec33c726a3890eb0f9b9ab Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 09/29] fix: escape U+061C, zero-width and tag characters like bidi controls Implements [[tasks/harmony-2749]] --- src/display.rs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/display.rs b/src/display.rs index 3065b67..7109958 100644 --- a/src/display.rs +++ b/src/display.rs @@ -11,11 +11,22 @@ use std::borrow::Cow; use std::fmt::Write; /// True for characters that must never reach a terminal raw: C0 and C1 -/// controls, DEL, and the Unicode bidirectional controls that reorder how a -/// line is displayed. +/// controls and DEL; the Unicode bidirectional controls, which reorder how a +/// line is displayed (U+061C, U+200E-F, U+202A-E, U+2066-9); and invisible +/// format characters that hide text from a reader (soft hyphen, zero-width +/// characters, word joiners, BOM, tag characters). pub fn is_unsafe_char(c: char) -> bool { c.is_control() - || matches!(c, '\u{200E}' | '\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') + || matches!( + c, + '\u{AD}' + | '\u{061C}' + | '\u{200B}'..='\u{200F}' + | '\u{202A}'..='\u{202E}' + | '\u{2060}'..='\u{2069}' + | '\u{FEFF}' + | '\u{E0000}'..='\u{E007F}' + ) } /// Return `s` with every unsafe character written as a visible escape @@ -71,6 +82,11 @@ mod tests { assert_eq!(escape("n\nfake\r\t"), "n\\nfake\\r\\t"); assert_eq!(escape("c1\u{9b}31m del\u{7f}"), "c1\\u{9b}31m del\\u{7f}"); assert_eq!(escape("rtl\u{202e}txt"), "rtl\\u{202e}txt"); + assert_eq!(escape("alm\u{61c}x"), "alm\\u{61c}x"); + assert_eq!( + escape("zw\u{200b}j\u{2060}t\u{e0041}"), + "zw\\u{200b}j\\u{2060}t\\u{e0041}" + ); } #[test] From e4a6217633290f082cc4c16cdb098afcd8d4b27a Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 10/29] fix: refuse group-writable dirs even for a private group; escape U+2028/2029 The private-group exception is dropped: POSIX ACLs and other accounts with the same primary group can widen group access beyond what the mode bits show. Line and paragraph separators are escaped, since many renderers treat them as line breaks. Implements [[tasks/harmony-2749]] --- src/data_dir.rs | 82 ++++++------------------------------------------- src/display.rs | 10 +++--- 2 files changed, 15 insertions(+), 77 deletions(-) diff --git a/src/data_dir.rs b/src/data_dir.rs index 9f0d382..40ee09c 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -115,7 +115,7 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { // leaving a directory through `..` depends on it as much as entering // one of its entries does let holder = stat(¤t)?; - if !owned_by_you_or_root(&holder, uid) || !only_you_can_write(&holder, uid, true) { + if !owned_by_you_or_root(&holder, uid) || !only_you_can_write(&holder, true) { anyhow::bail!( "Refusing to use {shown}: another user could replace it through {} \ (it must belong to you or root and not be writable by others){}", @@ -158,7 +158,7 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { outside_namespace_note(&meta) ); } - if !only_you_can_write(&meta, uid, false) { + if !only_you_can_write(&meta, false) { anyhow::bail!( "Refusing to use {shown}: other users can write to it (fix with: chmod go-w '{shown}')" ); @@ -172,59 +172,15 @@ fn owned_by_you_or_root(meta: &std::fs::Metadata, uid: u32) -> bool { meta.uid() == uid || meta.uid() == 0 } -/// No one but you (and root) can change the entries of this directory: it is -/// not writable by others, or only for its group when that group is your own -/// private group, or (when `sticky_ok`) it is sticky, so only an entry's -/// owner can rename that entry. +/// No one but you (and root) can change the entries of this directory: it +/// is writable by no one else, or (when `sticky_ok`) it is sticky, so only an +/// entry's owner can rename that entry. Group write is refused even for your +/// own private group: ACLs and other accounts with that primary group can +/// widen it in ways the mode bits do not show. #[cfg(unix)] -fn only_you_can_write(meta: &std::fs::Metadata, uid: u32, sticky_ok: bool) -> bool { +fn only_you_can_write(meta: &std::fs::Metadata, sticky_ok: bool) -> bool { use std::os::unix::fs::MetadataExt; - if sticky_ok && meta.mode() & 0o1000 != 0 { - return true; - } - meta.mode() & 0o002 == 0 && (meta.mode() & 0o020 == 0 || is_private_group(meta.gid(), uid)) -} - -/// Whether `gid` is the user's own private group, as on systems that give -/// every user a group of their own (and umask 002): the user's primary -/// group, named after the user, with no other members. -#[cfg(unix)] -fn is_private_group(gid: u32, uid: u32) -> bool { - use std::ffi::CStr; - use std::ptr::null_mut; - - // SAFETY: the reentrant lookups write only into the structs and buffers - // passed in, and the strings read here point into those buffers. - unsafe { - let mut pwd: libc::passwd = std::mem::zeroed(); - let mut found: *mut libc::passwd = null_mut(); - let mut pw_buf = vec![0 as libc::c_char; 16 * 1024]; - if libc::getpwuid_r(uid, &mut pwd, pw_buf.as_mut_ptr(), pw_buf.len(), &mut found) != 0 - || found.is_null() - || pwd.pw_gid != gid - { - return false; - } - let user = CStr::from_ptr(pwd.pw_name); - - let mut grp: libc::group = std::mem::zeroed(); - let mut found: *mut libc::group = null_mut(); - let mut gr_buf = vec![0 as libc::c_char; 64 * 1024]; - if libc::getgrgid_r(gid, &mut grp, gr_buf.as_mut_ptr(), gr_buf.len(), &mut found) != 0 - || found.is_null() - || CStr::from_ptr(grp.gr_name) != user - { - return false; - } - let mut member = grp.gr_mem; - while !member.is_null() && !(*member).is_null() { - if CStr::from_ptr(*member) != user { - return false; - } - member = member.add(1); - } - true - } + meta.mode() & 0o022 == 0 || (sticky_ok && meta.mode() & 0o1000 != 0) } /// In a user namespace that maps only you (some sandboxes), files of every @@ -403,26 +359,6 @@ mod tests { assert!(err.contains("is a link or junction"), "{err}"); } - #[cfg(unix)] - #[test] - fn test_group_write_is_fine_only_for_your_private_group() { - use std::os::unix::fs::PermissionsExt; - - // A 0775 directory gets your primary group; whether that group is - // private to you depends on the machine, and decides the outcome - let tmp = tempfile::tempdir().unwrap(); - let dir = tmp.path().join("ws"); - std::fs::create_dir(&dir).unwrap(); - std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o775)).unwrap(); - // SAFETY: no preconditions - let (uid, gid) = unsafe { (libc::geteuid(), libc::getegid()) }; - let gid_of_dir = std::os::unix::fs::MetadataExt::gid(&std::fs::metadata(&dir).unwrap()); - let private = gid_of_dir == gid && is_private_group(gid, uid); - assert_eq!(check_private_dir(&dir).is_ok(), private); - // A group that is not yours never counts - assert!(!is_private_group(gid.wrapping_add(1), uid)); - } - #[cfg(unix)] #[test] fn test_refuses_dir_others_can_write() { diff --git a/src/display.rs b/src/display.rs index 7109958..feac442 100644 --- a/src/display.rs +++ b/src/display.rs @@ -12,9 +12,10 @@ use std::fmt::Write; /// True for characters that must never reach a terminal raw: C0 and C1 /// controls and DEL; the Unicode bidirectional controls, which reorder how a -/// line is displayed (U+061C, U+200E-F, U+202A-E, U+2066-9); and invisible -/// format characters that hide text from a reader (soft hyphen, zero-width -/// characters, word joiners, BOM, tag characters). +/// line is displayed (U+061C, U+200E-F, U+202A-E, U+2066-9); the line and +/// paragraph separators (U+2028-9), which many renderers treat as line +/// breaks; and invisible format characters that hide text from a reader +/// (soft hyphen, zero-width characters, word joiners, BOM, tag characters). pub fn is_unsafe_char(c: char) -> bool { c.is_control() || matches!( @@ -22,7 +23,7 @@ pub fn is_unsafe_char(c: char) -> bool { '\u{AD}' | '\u{061C}' | '\u{200B}'..='\u{200F}' - | '\u{202A}'..='\u{202E}' + | '\u{2028}'..='\u{202E}' | '\u{2060}'..='\u{2069}' | '\u{FEFF}' | '\u{E0000}'..='\u{E007F}' @@ -83,6 +84,7 @@ mod tests { assert_eq!(escape("c1\u{9b}31m del\u{7f}"), "c1\\u{9b}31m del\\u{7f}"); assert_eq!(escape("rtl\u{202e}txt"), "rtl\\u{202e}txt"); assert_eq!(escape("alm\u{61c}x"), "alm\\u{61c}x"); + assert_eq!(escape("a\u{2028}## b"), "a\\u{2028}## b"); assert_eq!( escape("zw\u{200b}j\u{2060}t\u{e0041}"), "zw\\u{200b}j\\u{2060}t\\u{e0041}" From 8ba410302879461d79172c5ba1d1481868cd2c89 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 11/29] fix: refuse names Windows reads differently; private lock file; resolve_inside for callers Names and path components may not end in a dot or space, contain <>:"|?*, look like a short name (~ and digit) or be a device name, all of which alias other names on Windows. The lock file is 0600 (an older one is tightened), since anyone who can open it can hold the lock. resolve_inside is public so worktree creation can check destinations inside a checkout. Declares rust-version 1.89 for File::try_lock. Implements [[tasks/harmony-2749]] --- Cargo.toml | 2 + src/config.rs | 125 +++++++++++++++++++++++++++++++++++++++++--------- src/lock.rs | 44 +++++++++++++++--- 3 files changed, 144 insertions(+), 27 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index fbed290..d63994c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,8 @@ version.workspace = true edition.workspace = true license.workspace = true repository.workspace = true +# File::try_lock +rust-version = "1.89" description = "Shared infrastructure for ~/.meta/ directory management, lockfile, and atomic JSON store" [dependencies] diff --git a/src/config.rs b/src/config.rs index 133a480..f1c4d7a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -254,12 +254,14 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, /// join `path` onto the directory of the `.meta` file without checking again: /// - No value (name, path, repo, tags, provides, depends_on) is empty or holds /// a control or bidirectional-control character ([`is_unsafe_char`]). -/// - `name` is one path component: not `.` or `..`, no `/`, `\` or drive -/// prefix. +/// - `name` is one path component: not `.` or `..`, no `/` or `\`. +/// - Neither the name nor any path component means something else on +/// Windows ([`windows_ambiguity`]): no drive prefix, `<>:"|?*`, trailing +/// dot or space, `~` and digit, or device name. /// - `path` (the name when omitted) is relative and stays inside the config's /// directory: `\` reads as `/`, empty and `.` components are dropped, `..` -/// and drive prefixes (`C:`) are rejected, something must remain, and no -/// symlink along it may lead outside the directory. +/// is rejected, something must remain, and no symlink along it may lead +/// outside the directory. /// - `repo` does not start with `-`, so git cannot read it as an option. /// - Tags hold no whitespace and no `,`, which the `--tag` filter splits on. /// @@ -289,13 +291,11 @@ fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result Result<(), String> { Ok(()) } -/// True for a `C:` prefix, which makes a Windows path absolute or -/// drive-relative wherever it appears. -fn starts_with_drive(s: &str) -> bool { - let mut chars = s.chars(); - matches!((chars.next(), chars.next()), (Some(c), Some(':')) if c.is_ascii_alphabetic()) +/// What would make a name or path component mean something else on +/// Windows, where the same `.meta` may be used: a drive prefix, a character +/// Windows refuses or treats specially, a trailing dot or space (which +/// Windows drops, so `a.` is `a`), a `~` and digit as in a short name like +/// `PROGRA~1` (an alias of another name), or a device name like `NUL`. +fn windows_ambiguity(part: &str) -> Option<&'static str> { + let mut chars = part.chars(); + if matches!((chars.next(), chars.next()), (Some(c), Some(':')) if c.is_ascii_alphabetic()) { + return Some("a drive prefix"); + } + if part.contains(['<', '>', ':', '"', '|', '?', '*']) { + return Some("a character Windows does not allow (<>:\"|?*)"); + } + if part.ends_with(['.', ' ']) { + return Some("a trailing dot or space, which Windows drops"); + } + let short_name = part.match_indices('~').any(|(i, _)| { + part.get(i + 1..) + .is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit())) + }); + if short_name { + return Some("a '~' and digit, as in a Windows short name"); + } + let stem = part + .split('.') + .next() + .unwrap_or(part) + .trim_end() + .to_ascii_uppercase(); + let numbered = |prefix: &str| { + stem.strip_prefix(prefix) + .is_some_and(|n| n.len() == 1 && n.chars().all(|c| c.is_ascii_digit())) + }; + if matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || numbered("COM") || numbered("LPT") + { + return Some("a Windows device name"); + } + None } /// Normalize a project path to `a/b` form, rejecting anything that is not a @@ -367,10 +400,10 @@ fn normalize_project_path(raw: &str) -> Result { match part { "" | "." => {} ".." => return Err(format!("path '{raw}' must not contain '..'")), - part if starts_with_drive(part) => { - return Err(format!("path '{raw}' must be relative (no drive prefix)")) - } - part => parts.push(part), + part => match windows_ambiguity(part) { + Some(why) => return Err(format!("path '{raw}' has a component with {why}")), + None => parts.push(part), + }, } } if parts.is_empty() { @@ -385,7 +418,7 @@ fn normalize_project_path(raw: &str) -> Result { /// refuse it if one leads outside `base_dir` or if it ends at `base_dir`. /// Returns the project's location: the real path of the part that exists, /// followed by the part not created yet. -fn resolve_inside(base_dir: &Path, rel: &str) -> Result { +pub fn resolve_inside(base_dir: &Path, rel: &str) -> Result { let base = base_dir .canonicalize() .map_err(|e| format!("cannot resolve {}: {e}", escape_path(base_dir)))?; @@ -1401,6 +1434,56 @@ mod tests { } } + #[test] + fn test_parse_rejects_names_and_paths_windows_reads_differently() { + for (json, what) in [ + ( + r#"{"projects": {"p": {"repo": "u", "path": "a./x"}}}"#, + "trailing dot", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": "a /x"}}}"#, + "trailing dot or space", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": "PROGRA~1/x"}}}"#, + "short name", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": "x/nul"}}}"#, + "device name", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": "con.txt"}}}"#, + "device name", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": "x/com1"}}}"#, + "device name", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": "ab:c"}}}"#, + "does not allow", + ), + (r#"{"projects": {"x|y": "u"}}"#, "does not allow"), + ( + r#"{"projects": {"a.": {"repo": "u", "path": "b"}}}"#, + "trailing dot", + ), + ] { + let err = parse_err(json); + assert!(err.contains(what), "{json}: {err}"); + } + // Ordinary names that only look similar are fine + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join(".meta"), + r#"{"projects": {"console": "u", "a.b": "u", "com10": "u", "x~y": "u", "lpt": "u"}}"#, + ) + .unwrap(); + assert!(parse_meta_config(&dir.path().join(".meta")).is_ok()); + } + #[test] fn test_parse_rejects_overlapping_paths() { let err = parse_err( diff --git a/src/lock.rs b/src/lock.rs index 827870d..53e09ed 100644 --- a/src/lock.rs +++ b/src/lock.rs @@ -9,7 +9,8 @@ //! //! On Unix the lock's directory must belong to the current user and must not //! be writable by group or others; anyone else who could write there could -//! replace the lock file or the store beside it. +//! replace the lock file or the store beside it. The lock file itself is +//! 0600, since anyone who can open it can hold the lock. use crate::display::escape_path; use anyhow::{Context, Result}; @@ -39,13 +40,29 @@ pub fn acquire(lock_path: &Path, timeout: Duration) -> Result { if let Some(parent) = lock_path.parent() { crate::data_dir::create_private_dir(parent)?; } - let file = OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(false) + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + // Readable by no one else: anyone who can open the file can hold the + // lock and block every store write + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let file = options .open(lock_path) .with_context(|| format!("Failed to open lock file: {}", escape_path(lock_path)))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + // a lock file left by an older meta may still be 0644 + let mode = file + .metadata() + .with_context(|| format!("Failed to stat {}", escape_path(lock_path)))? + .permissions() + .mode(); + if mode & 0o077 != 0 { + file.set_permissions(std::fs::Permissions::from_mode(0o600)) + .with_context(|| format!("Failed to restrict {}", escape_path(lock_path)))?; + } + } let deadline = Instant::now() + timeout; loop { @@ -115,6 +132,21 @@ mod tests { } } + #[cfg(unix)] + #[test] + fn test_lock_file_is_private() { + use std::os::unix::fs::PermissionsExt; + + let tmp = tempfile::tempdir().unwrap(); + let lock_path = tmp.path().join("x.lock"); + // An older meta's leftover lock file, readable by everyone + fs::write(&lock_path, "123\n").unwrap(); + fs::set_permissions(&lock_path, fs::Permissions::from_mode(0o644)).unwrap(); + drop(acquire(&lock_path, WAIT).unwrap()); + let mode = fs::metadata(&lock_path).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600); + } + #[test] fn test_lock_excludes_other_processes() { // The lock belongs to the open file, so a second open (as another From d2534c86b56a30a33c102f6259a775ff13637698 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 12/29] fix: ASCII-only names and paths, no .git; private store files; macOS ACLs; Windows lock dir Names and path components are ASCII letters, digits, space and ._-+@ (plus the trailing dot/space and device-name rules), so no normalization, case folding or short name can make two of them one directory on any platform; a .git component and a path under .worktrees are refused. Store files are written 0600 and read only when they are regular files owned by you that no one else can write. On macOS a directory whose ACL has an allow entry is refused. On Windows a lock directory other accounts can read is refused, and refusals say how to fix them. Implements [[tasks/harmony-2749]] --- src/config.rs | 101 +++++++++++++++++++++++++++++++--------------- src/data_dir.rs | 105 ++++++++++++++++++++++++++++++++++++++++++++++-- src/lock.rs | 14 +++++++ src/store.rs | 80 ++++++++++++++++++++++++++++++++++-- src/win_acl.rs | 12 ++++-- 5 files changed, 269 insertions(+), 43 deletions(-) diff --git a/src/config.rs b/src/config.rs index f1c4d7a..d60e811 100644 --- a/src/config.rs +++ b/src/config.rs @@ -255,9 +255,9 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, /// - No value (name, path, repo, tags, provides, depends_on) is empty or holds /// a control or bidirectional-control character ([`is_unsafe_char`]). /// - `name` is one path component: not `.` or `..`, no `/` or `\`. -/// - Neither the name nor any path component means something else on -/// Windows ([`windows_ambiguity`]): no drive prefix, `<>:"|?*`, trailing -/// dot or space, `~` and digit, or device name. +/// - The name and every path component pass [`component_problem`]: ASCII +/// letters, digits, space and `._-+@` only, no trailing dot or space, no +/// Windows device name, not `.git`. The first component is not `.worktrees`. /// - `path` (the name when omitted) is relative and stays inside the config's /// directory: `\` reads as `/`, empty and `.` components are dropped, `..` /// is rejected, something must remain, and no symlink along it may lead @@ -294,7 +294,7 @@ fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result Result<(), String> { Ok(()) } -/// What would make a name or path component mean something else on -/// Windows, where the same `.meta` may be used: a drive prefix, a character -/// Windows refuses or treats specially, a trailing dot or space (which -/// Windows drops, so `a.` is `a`), a `~` and digit as in a short name like -/// `PROGRA~1` (an alias of another name), or a device name like `NUL`. -fn windows_ambiguity(part: &str) -> Option<&'static str> { - let mut chars = part.chars(); - if matches!((chars.next(), chars.next()), (Some(c), Some(':')) if c.is_ascii_alphabetic()) { - return Some("a drive prefix"); - } - if part.contains(['<', '>', ':', '"', '|', '?', '*']) { - return Some("a character Windows does not allow (<>:\"|?*)"); +/// What is wrong with a name or path component, if anything. The same +/// `.meta` serves every platform, so each must name one and the same +/// directory everywhere: +/// - only ASCII letters, digits, space and `._-+@`, which no filesystem +/// folds, normalizes or treats specially (Unicode names can alias each +/// other on macOS and Windows; `<>:"|?*` and `C:` mean something on Windows); +/// - no trailing dot or space, which Windows drops (`a.` is `a` there); +/// - not a Windows device name such as `NUL` or `COM1`; +/// - not `.git`, which would put a repo inside a git directory (hooks). +fn component_problem(part: &str) -> Option<&'static str> { + if !part + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '.' | '_' | '-' | '+' | '@')) + { + return Some("a character other than ASCII letters, digits, space and ._-+@"); } if part.ends_with(['.', ' ']) { return Some("a trailing dot or space, which Windows drops"); } - let short_name = part.match_indices('~').any(|(i, _)| { - part.get(i + 1..) - .is_some_and(|rest| rest.starts_with(|c: char| c.is_ascii_digit())) - }); - if short_name { - return Some("a '~' and digit, as in a Windows short name"); - } let stem = part .split('.') .next() @@ -385,6 +381,9 @@ fn windows_ambiguity(part: &str) -> Option<&'static str> { { return Some("a Windows device name"); } + if part.eq_ignore_ascii_case(".git") { + return Some("the name .git"); + } None } @@ -400,7 +399,7 @@ fn normalize_project_path(raw: &str) -> Result { match part { "" | "." => {} ".." => return Err(format!("path '{raw}' must not contain '..'")), - part => match windows_ambiguity(part) { + part => match component_problem(part) { Some(why) => return Err(format!("path '{raw}' has a component with {why}")), None => parts.push(part), }, @@ -411,6 +410,14 @@ fn normalize_project_path(raw: &str) -> Result { "path '{raw}' must name a directory below the .meta file" )); } + if parts + .first() + .is_some_and(|first| first.eq_ignore_ascii_case(".worktrees")) + { + return Err(format!( + "path '{raw}' is inside .worktrees, where worktrees live" + )); + } Ok(parts.join("/")) } @@ -1430,12 +1437,12 @@ mod tests { r#"{"projects": {"C:outside": {"repo": "u", "path": "safe"}}}"#, ] { let err = parse_err(json); - assert!(err.contains("drive prefix"), "{json}: {err}"); + assert!(err.contains("ASCII letters"), "{json}: {err}"); } } #[test] - fn test_parse_rejects_names_and_paths_windows_reads_differently() { + fn test_parse_rejects_names_and_paths_that_alias_or_mislead() { for (json, what) in [ ( r#"{"projects": {"p": {"repo": "u", "path": "a./x"}}}"#, @@ -1445,10 +1452,6 @@ mod tests { r#"{"projects": {"p": {"repo": "u", "path": "a /x"}}}"#, "trailing dot or space", ), - ( - r#"{"projects": {"p": {"repo": "u", "path": "PROGRA~1/x"}}}"#, - "short name", - ), ( r#"{"projects": {"p": {"repo": "u", "path": "x/nul"}}}"#, "device name", @@ -1461,11 +1464,43 @@ mod tests { r#"{"projects": {"p": {"repo": "u", "path": "x/com1"}}}"#, "device name", ), + ( + r#"{"projects": {"p": {"repo": "u", "path": "C:x"}}}"#, + "ASCII letters", + ), ( r#"{"projects": {"p": {"repo": "u", "path": "ab:c"}}}"#, - "does not allow", + "ASCII letters", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": "PROGRA~1/x"}}}"#, + "ASCII letters", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": "caf\u00e9"}}}"#, + "ASCII letters", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": "cafe\u0301"}}}"#, + "ASCII letters", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": "COM\u00b9"}}}"#, + "ASCII letters", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": ".git/hooks"}}}"#, + "the name .git", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": "x/.GIT/hooks"}}}"#, + "the name .git", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": ".worktrees/t"}}}"#, + "inside .worktrees", ), - (r#"{"projects": {"x|y": "u"}}"#, "does not allow"), + (r#"{"projects": {"x|y": "u"}}"#, "ASCII letters"), ( r#"{"projects": {"a.": {"repo": "u", "path": "b"}}}"#, "trailing dot", @@ -1478,7 +1513,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); std::fs::write( dir.path().join(".meta"), - r#"{"projects": {"console": "u", "a.b": "u", "com10": "u", "x~y": "u", "lpt": "u"}}"#, + r#"{"projects": {"console": "u", "a.b": "u", "com10": "u", "x y+z@w": "u", ".github": "u"}}"#, ) .unwrap(); assert!(parse_meta_config(&dir.path().join(".meta")).is_ok()); diff --git a/src/data_dir.rs b/src/data_dir.rs index 40ee09c..807ea62 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -115,7 +115,10 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { // leaving a directory through `..` depends on it as much as entering // one of its entries does let holder = stat(¤t)?; - if !owned_by_you_or_root(&holder, uid) || !only_you_can_write(&holder, true) { + if !owned_by_you_or_root(&holder, uid) + || !only_you_can_write(&holder, true) + || acl_allows_others(¤t) + { anyhow::bail!( "Refusing to use {shown}: another user could replace it through {} \ (it must belong to you or root and not be writable by others){}", @@ -163,6 +166,12 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { "Refusing to use {shown}: other users can write to it (fix with: chmod go-w '{shown}')" ); } + if acl_allows_others(¤t) { + anyhow::bail!( + "Refusing to use {shown}: its access control list grants access beyond the mode \ + bits (see: ls -led '{shown}'; remove with: chmod -N '{shown}')" + ); + } Ok(()) } @@ -183,6 +192,58 @@ fn only_you_can_write(meta: &std::fs::Metadata, sticky_ok: bool) -> bool { meta.mode() & 0o022 == 0 || (sticky_ok && meta.mode() & 0o1000 != 0) } +/// Whether a macOS access control list on `path` has an allow entry, which +/// can grant write access that the mode bits do not show. (Deny entries, +/// like the one macOS puts on home folders, only take access away.) On Linux +/// an ACL cannot grant more than the group bits allow, so the mode check +/// covers it. +#[cfg(target_os = "macos")] +fn acl_allows_others(path: &Path) -> bool { + use std::ffi::{c_char, c_int, c_void, CString}; + use std::os::unix::ffi::OsStrExt; + + const ACL_TYPE_EXTENDED: c_int = 0x100; + const ACL_FIRST_ENTRY: c_int = 0; + const ACL_NEXT_ENTRY: c_int = -1; + const ACL_EXTENDED_ALLOW: c_int = 1; + extern "C" { + fn acl_get_link_np(path: *const c_char, kind: c_int) -> *mut c_void; + fn acl_get_entry(acl: *mut c_void, entry_id: c_int, entry: *mut *mut c_void) -> c_int; + fn acl_get_tag_type(entry: *mut c_void, tag: *mut c_int) -> c_int; + fn acl_free(obj: *mut c_void) -> c_int; + } + + let Ok(c_path) = CString::new(path.as_os_str().as_bytes()) else { + return true; + }; + // SAFETY: the ACL is freed once; entries point into it and are not used + // after that. + unsafe { + let acl = acl_get_link_np(c_path.as_ptr(), ACL_TYPE_EXTENDED); + if acl.is_null() { + return false; // no ACL + } + let mut allows = false; + let mut entry: *mut c_void = std::ptr::null_mut(); + let mut which = ACL_FIRST_ENTRY; + while acl_get_entry(acl, which, &mut entry) == 0 { + which = ACL_NEXT_ENTRY; + let mut tag: c_int = 0; + if acl_get_tag_type(entry, &mut tag) != 0 || tag == ACL_EXTENDED_ALLOW { + allows = true; + break; + } + } + acl_free(acl); + allows + } +} + +#[cfg(all(unix, not(target_os = "macos")))] +fn acl_allows_others(_path: &Path) -> bool { + false +} + /// In a user namespace that maps only you (some sandboxes), files of every /// other account, root included, show as the overflow uid 65534. #[cfg(unix)] @@ -214,7 +275,7 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { let mut holder: Option<&Path> = None; for path in ancestors { if let Some(holder) = holder { - if let Some(why) = untrusted_access(holder, &user, ANCESTOR_RIGHTS)? { + if let Some(why) = untrusted_access(holder, &user, ANCESTOR_RIGHTS, "change")? { anyhow::bail!( "Refusing to use {shown}: another user could replace it through {} ({why})", crate::display::escape_path(holder) @@ -231,8 +292,11 @@ pub fn check_private_dir(dir: &Path) -> Result<()> { } holder = Some(path); } - if let Some(why) = untrusted_access(&written, &user, DIR_RIGHTS)? { - anyhow::bail!("Refusing to use {shown}: {why}"); + if let Some(why) = untrusted_access(&written, &user, DIR_RIGHTS, "change")? { + anyhow::bail!( + "Refusing to use {shown}: {why} (remove other accounts' write access, for \ + example with icacls, or use a directory in your profile)" + ); } Ok(()) } @@ -357,6 +421,39 @@ mod tests { check_private_dir(&private).unwrap(); let err = check_private_dir(&junction).unwrap_err().to_string(); assert!(err.contains("is a link or junction"), "{err}"); + + // A lock in a directory others can read is refused: they could hold it + let readable = tmp.path().join("readable"); + std::fs::create_dir(&readable).unwrap(); + crate::lock::acquire(&readable.join("x.lock"), std::time::Duration::ZERO).unwrap(); + let granted = std::process::Command::new("icacls") + .arg(&readable) + .args(["/grant", "*S-1-1-0:(OI)(CI)R"]) + .status() + .unwrap(); + assert!(granted.success()); + let err = crate::lock::acquire(&readable.join("x.lock"), std::time::Duration::ZERO) + .err() + .unwrap() + .to_string(); + assert!(err.contains("could hold the lock"), "{err}"); + } + + #[cfg(target_os = "macos")] + #[test] + fn test_macos_refuses_an_acl_that_allows_others() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("acl"); + std::fs::create_dir(&dir).unwrap(); + check_private_dir(&dir).unwrap(); + let added = std::process::Command::new("chmod") + .args(["+a", "everyone allow add_file,delete_child"]) + .arg(&dir) + .status() + .unwrap(); + assert!(added.success()); + let err = check_private_dir(&dir).unwrap_err().to_string(); + assert!(err.contains("access control list"), "{err}"); } #[cfg(unix)] diff --git a/src/lock.rs b/src/lock.rs index 53e09ed..57065ec 100644 --- a/src/lock.rs +++ b/src/lock.rs @@ -39,6 +39,20 @@ impl LockGuard { pub fn acquire(lock_path: &Path, timeout: Duration) -> Result { if let Some(parent) = lock_path.parent() { crate::data_dir::create_private_dir(parent)?; + // Anyone who can open the lock file can hold the lock; on Unix the + // file is made 0600 below, on Windows it inherits the directory's + // access list + #[cfg(windows)] + { + use crate::win_acl::{current_user_sid, untrusted_access, READ_RIGHTS}; + let user = current_user_sid()?; + if let Some(why) = untrusted_access(parent, &user, READ_RIGHTS, "open files in")? { + anyhow::bail!( + "Refusing to lock in {}: {why}, so another account could hold the lock", + escape_path(parent) + ); + } + } } let mut options = OpenOptions::new(); options.read(true).write(true).create(true).truncate(false); diff --git a/src/store.rs b/src/store.rs index 7a218ce..9e0ce3a 100644 --- a/src/store.rs +++ b/src/store.rs @@ -12,11 +12,13 @@ use std::path::Path; /// Read a JSON file, returning `T::default()` if the file doesn't exist. /// -/// Returns an error if the file exists but can't be parsed. +/// Returns an error if the file exists but can't be parsed, or if another +/// user could have written it (see [`check_private_file`]). pub fn read(path: &Path) -> Result { - if !path.exists() { + if std::fs::symlink_metadata(path).is_err() { return Ok(T::default()); } + check_private_file(path)?; let content = std::fs::read_to_string(path) .with_context(|| format!("Failed to read store file: {}", escape_path(path)))?; @@ -46,8 +48,19 @@ pub fn write_atomic(path: &Path, data: &T) -> Result<()> { let json = serde_json::to_string_pretty(data).with_context(|| "Failed to serialize store data")?; - std::fs::write(&tmp_path, &json) + // A fresh file readable and writable by you alone (a leftover one from a + // crash is replaced, whatever its mode) + let _ = std::fs::remove_file(&tmp_path); + let mut options = std::fs::OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + let mut file = options + .open(&tmp_path) + .with_context(|| format!("Failed to create temp file: {}", escape_path(&tmp_path)))?; + std::io::Write::write_all(&mut file, json.as_bytes()) .with_context(|| format!("Failed to write temp file: {}", escape_path(&tmp_path)))?; + drop(file); std::fs::rename(&tmp_path, path) .with_context(|| format!("Failed to rename temp file to: {}", escape_path(path)))?; @@ -55,6 +68,43 @@ pub fn write_atomic(path: &Path, data: &T) -> Result<()> { Ok(()) } +/// Refuse to read a store file another user could have written: anything but +/// a regular file (such as a symlink to their file), a file owned by someone +/// else, or one writable by group or others. The directory alone does not +/// settle this: a file can be writable even where the directory is not. +#[cfg(unix)] +pub fn check_private_file(path: &Path) -> Result<()> { + use std::os::unix::fs::MetadataExt; + + let meta = std::fs::symlink_metadata(path) + .with_context(|| format!("Failed to stat {}", escape_path(path)))?; + // SAFETY: geteuid has no preconditions and cannot fail. + let uid = unsafe { libc::geteuid() }; + if !meta.is_file() || meta.uid() != uid || meta.mode() & 0o022 != 0 { + anyhow::bail!( + "Refusing to read {}: it must be a regular file owned by you that no one else can \ + write (fix with: chmod go-w, or remove it)", + escape_path(path) + ); + } + Ok(()) +} + +/// On Windows the directory's access list (checked by `data_dir`) is what +/// the files in it inherit; a symlink is still refused. +#[cfg(not(unix))] +pub fn check_private_file(path: &Path) -> Result<()> { + let meta = std::fs::symlink_metadata(path) + .with_context(|| format!("Failed to stat {}", escape_path(path)))?; + if !meta.is_file() { + anyhow::bail!( + "Refusing to read {}: it is not a regular file", + escape_path(path) + ); + } + Ok(()) +} + /// Read-modify-write with lock protection. /// /// 1. Acquires the lock at `lock_path` @@ -152,6 +202,30 @@ mod tests { assert!(crate::lock::acquire(&lock_path, std::time::Duration::ZERO).is_ok()); } + #[cfg(unix)] + #[test] + fn test_store_files_are_private() { + use std::os::unix::fs::PermissionsExt; + + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("store.json"); + write_atomic(&path, &TestStore::default()).unwrap(); + let mode = std::fs::metadata(&path).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600); + + // A store others could have written is not trusted + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o664)).unwrap(); + let err = read::(&path).unwrap_err().to_string(); + assert!(err.contains("Refusing to read"), "{err}"); + + // Nor is a symlink to someone else's file + let other = tmp.path().join("other.json"); + std::fs::write(&other, "{}").unwrap(); + std::fs::remove_file(&path).unwrap(); + std::os::unix::fs::symlink(&other, &path).unwrap(); + assert!(read::(&path).is_err()); + } + #[test] fn test_read_empty_file() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/win_acl.rs b/src/win_acl.rs index 6cf31cc..62cbf20 100644 --- a/src/win_acl.rs +++ b/src/win_acl.rs @@ -22,6 +22,7 @@ const ACCESS_ALLOWED_ACE_TYPE: u8 = 0; const ACCESS_ALLOWED_CALLBACK_ACE_TYPE: u8 = 9; const INHERIT_ONLY_ACE: u8 = 0x08; +const FILE_READ_DATA: u32 = 0x1; const FILE_ADD_FILE: u32 = 0x2; const FILE_ADD_SUBDIRECTORY: u32 = 0x4; const FILE_DELETE_CHILD: u32 = 0x40; @@ -30,6 +31,7 @@ const WRITE_DAC: u32 = 0x4_0000; const WRITE_OWNER: u32 = 0x8_0000; const GENERIC_ALL: u32 = 0x1000_0000; const GENERIC_WRITE: u32 = 0x4000_0000; +const GENERIC_READ: u32 = 0x8000_0000; /// Rights on the data directory itself that would let an account change /// what it holds, or who may. @@ -46,6 +48,10 @@ pub const DIR_RIGHTS: u32 = FILE_ADD_FILE /// replace what it holds, or change who may. pub const ANCESTOR_RIGHTS: u32 = FILE_DELETE_CHILD | DELETE | WRITE_DAC | WRITE_OWNER | GENERIC_ALL; +/// Rights that let an account open the files in a directory (their access +/// lists inherit from it), and so hold a lock on one. +pub const READ_RIGHTS: u32 = FILE_READ_DATA | GENERIC_READ | GENERIC_ALL; + /// SYSTEM, Administrators and TrustedInstaller, which can change anything anyway. const SYSTEM_SIDS: [&str; 3] = [ "S-1-5-18", @@ -80,10 +86,10 @@ pub fn current_user_sid() -> Result { } } -/// Why an account other than `user` and the system's own could change +/// Why an account other than `user` and the system's own could `verb` /// `dir`, if one could: it owns `dir`, there is no access list, or an entry /// that applies to `dir` grants it any of `rights`. -pub fn untrusted_access(dir: &Path, user: &str, rights: u32) -> Result> { +pub fn untrusted_access(dir: &Path, user: &str, rights: u32, verb: &str) -> Result> { let wide: Vec = dir.as_os_str().encode_wide().chain(Some(0)).collect(); let trusted = |sid: &str| sid == user || SYSTEM_SIDS.contains(&sid); // SAFETY: GetNamedSecurityInfoW fills `owner` and `dacl` with pointers @@ -145,7 +151,7 @@ pub fn untrusted_access(dir: &Path, user: &str, rights: u32) -> Result Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 13/29] fix: check store and lock files themselves; trusted plugin files; reserved dirs through symlinks Store files are refused when a macOS ACL or a Windows access list (own or inherited, including inherit-only grants) lets another account change them; the lock file is refused when others can open it. check_trusted_file covers files meta runs (plugins): the file and the directory it really lives in. A project path that reaches .git or .worktrees through a symlink is refused. Implements [[tasks/harmony-2749]] --- src/config.rs | 43 ++++++++++++++++++++- src/data_dir.rs | 99 ++++++++++++++++++++++++++++++++++++++++++++++++- src/lock.rs | 34 ++++++++++------- src/store.rs | 30 +++++++++++++-- 4 files changed, 185 insertions(+), 21 deletions(-) diff --git a/src/config.rs b/src/config.rs index d60e811..d2da4a9 100644 --- a/src/config.rs +++ b/src/config.rs @@ -308,7 +308,28 @@ fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result .git`) + let base = base_dir + .canonicalize() + .map_err(|e| format!("cannot resolve {}: {e}", escape_path(base_dir)))?; + if let Ok(inside) = location.strip_prefix(&base) { + let parts: Vec = inside + .components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect(); + if parts.iter().any(|p| p.eq_ignore_ascii_case(".git")) + || parts + .first() + .is_some_and(|p| p.eq_ignore_ascii_case(".worktrees")) + { + return Err(format!( + "path '{}' leads into .git or .worktrees through a symlink", + info.path + )); + } + } + Ok(location) } /// Refuse two projects at one location, or one inside another's directory: @@ -1294,6 +1315,13 @@ mod tests { assert!(err.contains("vendor"), "{err}"); } + fn parse_err_in(dir: &Path, json: &str) -> String { + std::fs::write(dir.join(".meta"), json).unwrap(); + parse_meta_config(&dir.join(".meta")) + .unwrap_err() + .to_string() + } + fn parse_err(json: &str) -> String { let dir = tempfile::tempdir().unwrap(); std::fs::write(dir.path().join(".meta"), json).unwrap(); @@ -1390,6 +1418,19 @@ mod tests { ); } + #[cfg(unix)] + #[test] + fn test_parse_rejects_reserved_dirs_through_a_symlink() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join(".git")).unwrap(); + std::os::unix::fs::symlink(dir.path().join(".git"), dir.path().join("alias")).unwrap(); + let err = parse_err_in( + dir.path(), + r#"{"projects": {"p": {"repo": "u", "path": "alias/hooks"}}}"#, + ); + assert!(err.contains("leads into .git or .worktrees"), "{err}"); + } + #[cfg(unix)] #[test] fn test_parse_allows_symlink_alias_of_the_workspace_itself() { diff --git a/src/data_dir.rs b/src/data_dir.rs index 807ea62..47fe226 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -62,6 +62,43 @@ pub(crate) fn create_private_dir(dir: &Path) -> Result<()> { check_private_dir(dir) } +/// Refuse a file that meta will run, such as a plugin, if another user could +/// change or replace it: the directory it really lives in (after symlinks) +/// must pass [`check_private_dir`], and the file itself must belong to you +/// or root and be writable by no one else. +pub fn check_trusted_file(path: &Path) -> Result<()> { + let shown = crate::display::escape_path(path); + let real = path + .canonicalize() + .with_context(|| format!("Failed to resolve {shown}"))?; + if let Some(parent) = real.parent() { + check_private_dir(parent)?; + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let meta = std::fs::metadata(&real).with_context(|| format!("Failed to stat {shown}"))?; + // SAFETY: geteuid has no preconditions and cannot fail. + let uid = unsafe { libc::geteuid() }; + if !owned_by_you_or_root(&meta, uid) || meta.mode() & 0o022 != 0 || acl_allows_others(&real) + { + anyhow::bail!( + "Refusing to use {shown}: another user owns it or can change it \ + (fix with: chmod go-w '{shown}')" + ); + } + } + #[cfg(windows)] + { + use crate::win_acl::{current_user_sid, untrusted_access, DIR_RIGHTS}; + let user = current_user_sid()?; + if let Some(why) = untrusted_access(&real, &user, DIR_RIGHTS, "change")? { + anyhow::bail!("Refusing to use {shown}: {why}"); + } + } + Ok(()) +} + /// Refuse a directory that another user owns or can write to: they could /// replace the stores, locks or plugins in it. /// @@ -198,7 +235,7 @@ fn only_you_can_write(meta: &std::fs::Metadata, sticky_ok: bool) -> bool { /// an ACL cannot grant more than the group bits allow, so the mode check /// covers it. #[cfg(target_os = "macos")] -fn acl_allows_others(path: &Path) -> bool { +pub(crate) fn acl_allows_others(path: &Path) -> bool { use std::ffi::{c_char, c_int, c_void, CString}; use std::os::unix::ffi::OsStrExt; @@ -240,7 +277,7 @@ fn acl_allows_others(path: &Path) -> bool { } #[cfg(all(unix, not(target_os = "macos")))] -fn acl_allows_others(_path: &Path) -> bool { +pub(crate) fn acl_allows_others(_path: &Path) -> bool { false } @@ -437,6 +474,25 @@ mod tests { .unwrap() .to_string(); assert!(err.contains("could hold the lock"), "{err}"); + + // A grant that applies only to files in a private-looking directory + // still reaches a store file created there + let files_only = tmp.path().join("files-only"); + std::fs::create_dir(&files_only).unwrap(); + check_private_dir(&files_only).unwrap(); + let granted = std::process::Command::new("icacls") + .arg(&files_only) + .args(["/grant", "*S-1-1-0:(OI)(IO)M"]) + .status() + .unwrap(); + assert!(granted.success()); + let store = files_only.join("store.json"); + crate::store::write_atomic(&store, &std::collections::HashMap::::new()) + .unwrap(); + let err = crate::store::read::>(&store) + .unwrap_err() + .to_string(); + assert!(err.contains("S-1-1-0 may change it"), "{err}"); } #[cfg(target_os = "macos")] @@ -456,6 +512,45 @@ mod tests { assert!(err.contains("access control list"), "{err}"); } + #[cfg(target_os = "macos")] + #[test] + fn test_macos_refuses_a_store_file_acl_that_allows_others() { + let tmp = tempfile::tempdir().unwrap(); + let store = tmp.path().join("store.json"); + crate::store::write_atomic(&store, &std::collections::HashMap::::new()) + .unwrap(); + let added = std::process::Command::new("chmod") + .args(["+a", "everyone allow write"]) + .arg(&store) + .status() + .unwrap(); + assert!(added.success()); + assert!(crate::store::read::>(&store).is_err()); + } + + #[cfg(unix)] + #[test] + fn test_trusted_file_refuses_a_plugin_others_can_change() { + use std::os::unix::fs::PermissionsExt; + + let tmp = tempfile::tempdir().unwrap(); + let plugin = tmp.path().join("meta-x"); + std::fs::write(&plugin, "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&plugin, std::fs::Permissions::from_mode(0o755)).unwrap(); + check_trusted_file(&plugin).unwrap(); + std::fs::set_permissions(&plugin, std::fs::Permissions::from_mode(0o757)).unwrap(); + assert!(check_trusted_file(&plugin).is_err()); + + // A symlink to a plugin in a directory others can write is refused too + let shared = tmp.path().join("shared"); + std::fs::create_dir(&shared).unwrap(); + std::fs::set_permissions(&plugin, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::rename(&plugin, shared.join("meta-x")).unwrap(); + std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o777)).unwrap(); + std::os::unix::fs::symlink(shared.join("meta-x"), &plugin).unwrap(); + assert!(check_trusted_file(&plugin).is_err()); + } + #[cfg(unix)] #[test] fn test_refuses_dir_others_can_write() { diff --git a/src/lock.rs b/src/lock.rs index 57065ec..0f5da84 100644 --- a/src/lock.rs +++ b/src/lock.rs @@ -39,20 +39,6 @@ impl LockGuard { pub fn acquire(lock_path: &Path, timeout: Duration) -> Result { if let Some(parent) = lock_path.parent() { crate::data_dir::create_private_dir(parent)?; - // Anyone who can open the lock file can hold the lock; on Unix the - // file is made 0600 below, on Windows it inherits the directory's - // access list - #[cfg(windows)] - { - use crate::win_acl::{current_user_sid, untrusted_access, READ_RIGHTS}; - let user = current_user_sid()?; - if let Some(why) = untrusted_access(parent, &user, READ_RIGHTS, "open files in")? { - anyhow::bail!( - "Refusing to lock in {}: {why}, so another account could hold the lock", - escape_path(parent) - ); - } - } } let mut options = OpenOptions::new(); options.read(true).write(true).create(true).truncate(false); @@ -77,6 +63,26 @@ pub fn acquire(lock_path: &Path, timeout: Duration) -> Result { .with_context(|| format!("Failed to restrict {}", escape_path(lock_path)))?; } } + // An access list can still let others open it: refuse, rather than + // wait on a lock someone else may hold forever + #[cfg(target_os = "macos")] + if crate::data_dir::acl_allows_others(lock_path) { + anyhow::bail!( + "Refusing to lock {}: its access control list lets others open it \ + (remove with: chmod -N)", + escape_path(lock_path) + ); + } + #[cfg(windows)] + { + use crate::win_acl::{current_user_sid, untrusted_access, READ_RIGHTS}; + if let Some(why) = untrusted_access(lock_path, ¤t_user_sid()?, READ_RIGHTS, "open")? { + anyhow::bail!( + "Refusing to lock {}: {why}, so another account could hold the lock", + escape_path(lock_path) + ); + } + } let deadline = Instant::now() + timeout; loop { diff --git a/src/store.rs b/src/store.rs index 9e0ce3a..430a7f4 100644 --- a/src/store.rs +++ b/src/store.rs @@ -80,7 +80,11 @@ pub fn check_private_file(path: &Path) -> Result<()> { .with_context(|| format!("Failed to stat {}", escape_path(path)))?; // SAFETY: geteuid has no preconditions and cannot fail. let uid = unsafe { libc::geteuid() }; - if !meta.is_file() || meta.uid() != uid || meta.mode() & 0o022 != 0 { + if !meta.is_file() + || meta.uid() != uid + || meta.mode() & 0o022 != 0 + || crate::data_dir::acl_allows_others(path) + { anyhow::bail!( "Refusing to read {}: it must be a regular file owned by you that no one else can \ write (fix with: chmod go-w, or remove it)", @@ -90,9 +94,27 @@ pub fn check_private_file(path: &Path) -> Result<()> { Ok(()) } -/// On Windows the directory's access list (checked by `data_dir`) is what -/// the files in it inherit; a symlink is still refused. -#[cfg(not(unix))] +/// On Windows: a regular file that no account but you and the system's own +/// owns or may change (whether by its own entries or inherited ones). +#[cfg(windows)] +pub fn check_private_file(path: &Path) -> Result<()> { + use crate::win_acl::{current_user_sid, untrusted_access, DIR_RIGHTS}; + + let meta = std::fs::symlink_metadata(path) + .with_context(|| format!("Failed to stat {}", escape_path(path)))?; + if !meta.is_file() { + anyhow::bail!( + "Refusing to read {}: it is not a regular file", + escape_path(path) + ); + } + if let Some(why) = untrusted_access(path, ¤t_user_sid()?, DIR_RIGHTS, "change")? { + anyhow::bail!("Refusing to read {}: {why}", escape_path(path)); + } + Ok(()) +} + +#[cfg(not(any(unix, windows)))] pub fn check_private_file(path: &Path) -> Result<()> { let meta = std::fs::symlink_metadata(path) .with_context(|| format!("Failed to stat {}", escape_path(path)))?; From e86835cf5089b8a636ea6118f3db649b013815c1 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:47 -0700 Subject: [PATCH 14/29] fix: allow nested-alias names; follow every link to a trusted file; lock and store hardening A project name may be a plain relative path such as vendor/tree-sitter-markdown (gitkb's config has one), checked by the path rules, since worktrees use it as a destination. check_trusted_file follows the written path link by link. The lock file must be a regular file of yours (no symlink is followed). Store writes use a temp file per writer and check it before it replaces the store. relative_dir validates worktrees_dir. The macOS ACL probe fails closed. Implements [[tasks/harmony-2749]] --- src/config.rs | 108 ++++++++++++++++++++++++++++++++++++--------- src/data_dir.rs | 114 +++++++++++++++++++++++++++++++++--------------- src/lock.rs | 47 ++++++++++++++++---- src/store.rs | 59 +++++++++++++++++-------- 4 files changed, 245 insertions(+), 83 deletions(-) diff --git a/src/config.rs b/src/config.rs index d2da4a9..ec9ed1e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -254,7 +254,9 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, /// join `path` onto the directory of the `.meta` file without checking again: /// - No value (name, path, repo, tags, provides, depends_on) is empty or holds /// a control or bidirectional-control character ([`is_unsafe_char`]). -/// - `name` is one path component: not `.` or `..`, no `/` or `\`. +/// - `name` is a relative path in normal form (usually one component; a +/// nested alias like `vendor/lib` is a worktree destination too), held to +/// the same rules as `path`. /// - The name and every path component pass [`component_problem`]: ASCII /// letters, digits, space and `._-+@` only, no trailing dot or space, no /// Windows device name, not `.git`. The first component is not `.worktrees`. @@ -291,11 +293,15 @@ fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result/`. So it follows + // the path rules, and must already be in their normal form. + let normal = normalize_project_path(&info.name).map_err(|why| format!("name: {why}"))?; + if normal != info.name { + return Err(format!( + "name must be a plain relative path such as 'api' or 'vendor/lib', not '{}'", + info.name + )); } if info.repo.as_deref().is_some_and(|r| r.starts_with('-')) { return Err("repo must not start with '-'".into()); @@ -308,6 +314,17 @@ fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result .git`) let base = base_dir @@ -332,6 +349,35 @@ fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result Result { + // An absolute path is fine when it lies inside base_dir + let raw_path = Path::new(raw); + let relative = if raw_path.is_absolute() { + let real = |p: &Path| { + p.canonicalize() + .ok() + .or_else(|| Some(p.parent()?.canonicalize().ok()?.join(p.file_name()?))) + }; + real(base_dir) + .zip(real(raw_path)) + .and_then(|(base, path)| { + path.strip_prefix(base) + .ok() + .map(|rest| rest.to_string_lossy().into_owned()) + }) + .ok_or_else(|| format!("'{raw}' is outside {}", escape_path(base_dir)))? + } else { + raw.to_string() + }; + let normal = normalize_project_path(&relative)?; + resolve_inside(base_dir, &normal)?; + Ok(normal) +} + /// Refuse two projects at one location, or one inside another's directory: /// a clone of the outer repo could check out a symlink that the inner path /// then follows out of the workspace. Locations are compared as resolved @@ -431,14 +477,6 @@ fn normalize_project_path(raw: &str) -> Result { "path '{raw}' must name a directory below the .meta file" )); } - if parts - .first() - .is_some_and(|first| first.eq_ignore_ascii_case(".worktrees")) - { - return Err(format!( - "path '{raw}' is inside .worktrees, where worktrees live" - )); - } Ok(parts.join("/")) } @@ -450,6 +488,9 @@ pub fn resolve_inside(base_dir: &Path, rel: &str) -> Result { let base = base_dir .canonicalize() .map_err(|e| format!("cannot resolve {}: {e}", escape_path(base_dir)))?; + if rel.starts_with('/') || rel.split('/').any(|part| matches!(part, "" | "." | "..")) { + return Err(format!("path '{rel}' must be a plain relative path")); + } let mut current = base.clone(); let mut exists = true; for part in rel.split('/') { @@ -1324,10 +1365,7 @@ mod tests { fn parse_err(json: &str) -> String { let dir = tempfile::tempdir().unwrap(); - std::fs::write(dir.path().join(".meta"), json).unwrap(); - parse_meta_config(&dir.path().join(".meta")) - .unwrap_err() - .to_string() + parse_err_in(dir.path(), json) } #[test] @@ -1355,12 +1393,16 @@ mod tests { for (json, what) in [ ( r#"{"projects": {"../../../../escaped-wt": {"repo": "u", "path": "a"}}}"#, - "single path component", + "name: path '../../../../escaped-wt' must not contain '..'", ), - (r#"{"projects": {"a/b": "u"}}"#, "single path component"), + ( + r#"{"projects": {"/abs": "u"}}"#, + "name: path '/abs' must be relative", + ), + (r#"{"projects": {"a//b": "u"}}"#, "plain relative path"), ( r#"{"projects": {"..": {"repo": "u", "path": "a"}}}"#, - "single path component", + "must not contain '..'", ), ( r#"{"projects": {"x\u001b]0;T\u0007": "u"}}"#, @@ -1594,6 +1636,30 @@ mod tests { assert!(parse_meta_config(&dir.path().join(".meta")).is_ok()); } + #[test] + fn test_parse_accepts_nested_alias_names() { + // as gitkb's .meta.yaml lists `vendor/tree-sitter-markdown` + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join(".meta.yaml"), + "projects:\n core: u\n vendor/tree-sitter-markdown: u\n", + ) + .unwrap(); + let (projects, _) = parse_meta_config(&dir.path().join(".meta.yaml")).unwrap(); + assert_eq!(projects[1].name, "vendor/tree-sitter-markdown"); + assert_eq!(projects[1].path, "vendor/tree-sitter-markdown"); + } + + #[test] + fn test_relative_dir_stays_inside() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!(relative_dir(dir.path(), "wt").unwrap(), "wt"); + let inside = dir.path().join("custom").to_string_lossy().into_owned(); + assert_eq!(relative_dir(dir.path(), &inside).unwrap(), "custom"); + assert!(relative_dir(dir.path(), "../out").is_err()); + assert!(relative_dir(dir.path(), "/").is_err()); + } + #[test] fn test_parse_normalizes_paths() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/data_dir.rs b/src/data_dir.rs index 47fe226..3d7ac9c 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -62,41 +62,72 @@ pub(crate) fn create_private_dir(dir: &Path) -> Result<()> { check_private_dir(dir) } -/// Refuse a file that meta will run, such as a plugin, if another user could -/// change or replace it: the directory it really lives in (after symlinks) -/// must pass [`check_private_dir`], and the file itself must belong to you -/// or root and be writable by no one else. +/// Refuse a file that meta will run or trust, such as a plugin, if another +/// user could change or replace it. The path is followed one link at a time, +/// as the system will follow it later: the directory holding each link and +/// the final file must pass [`check_private_dir`], each link must belong to +/// you or root, and the file itself must belong to you or root and be +/// writable by no one else. pub fn check_trusted_file(path: &Path) -> Result<()> { let shown = crate::display::escape_path(path); - let real = path - .canonicalize() - .with_context(|| format!("Failed to resolve {shown}"))?; - if let Some(parent) = real.parent() { - check_private_dir(parent)?; - } - #[cfg(unix)] - { - use std::os::unix::fs::MetadataExt; - let meta = std::fs::metadata(&real).with_context(|| format!("Failed to stat {shown}"))?; - // SAFETY: geteuid has no preconditions and cannot fail. - let uid = unsafe { libc::geteuid() }; - if !owned_by_you_or_root(&meta, uid) || meta.mode() & 0o022 != 0 || acl_allows_others(&real) + let mut current = + std::path::absolute(path).with_context(|| format!("Failed to resolve {shown}"))?; + for _ in 0..40 { + let parent = current + .parent() + .ok_or_else(|| anyhow::anyhow!("Refusing to use {shown}: it has no parent directory"))? + .to_path_buf(); + check_private_dir(&parent)?; + let meta = std::fs::symlink_metadata(¤t) + .with_context(|| format!("Failed to stat {shown}"))?; + if meta.file_type().is_symlink() { + #[cfg(unix)] + { + // SAFETY: geteuid has no preconditions and cannot fail. + let uid = unsafe { libc::geteuid() }; + if !owned_by_you_or_root(&meta, uid) { + anyhow::bail!( + "Refusing to use {shown}: the symlink {} belongs to another user", + crate::display::escape_path(¤t) + ); + } + } + let target = std::fs::read_link(¤t) + .with_context(|| format!("Failed to read the symlink {shown}"))?; + current = parent.join(target); + continue; + } + #[cfg(unix)] { - anyhow::bail!( - "Refusing to use {shown}: another user owns it or can change it \ - (fix with: chmod go-w '{shown}')" - ); + use std::os::unix::fs::MetadataExt; + // SAFETY: geteuid has no preconditions and cannot fail. + let uid = unsafe { libc::geteuid() }; + if !meta.is_file() + || !owned_by_you_or_root(&meta, uid) + || meta.mode() & 0o022 != 0 + || acl_allows_others(¤t) + { + anyhow::bail!( + "Refusing to use {shown}: another user owns it or can change it \ + (fix with: chmod go-w '{shown}')" + ); + } } - } - #[cfg(windows)] - { - use crate::win_acl::{current_user_sid, untrusted_access, DIR_RIGHTS}; - let user = current_user_sid()?; - if let Some(why) = untrusted_access(&real, &user, DIR_RIGHTS, "change")? { - anyhow::bail!("Refusing to use {shown}: {why}"); + #[cfg(windows)] + { + use crate::win_acl::{current_user_sid, untrusted_access, DIR_RIGHTS}; + if !meta.is_file() { + anyhow::bail!("Refusing to use {shown}: it is not a regular file"); + } + if let Some(why) = + untrusted_access(¤t, ¤t_user_sid()?, DIR_RIGHTS, "change")? + { + anyhow::bail!("Refusing to use {shown}: {why}"); + } } + return Ok(()); } - Ok(()) + anyhow::bail!("Refusing to use {shown}: too many symlinks") } /// Refuse a directory that another user owns or can write to: they could @@ -258,7 +289,9 @@ pub(crate) fn acl_allows_others(path: &Path) -> bool { unsafe { let acl = acl_get_link_np(c_path.as_ptr(), ACL_TYPE_EXTENDED); if acl.is_null() { - return false; // no ACL + // ENOENT means there is no ACL; anything else is not knowing, + // which is treated as an ACL that may let others in + return std::io::Error::last_os_error().raw_os_error() != Some(libc::ENOENT); } let mut allows = false; let mut entry: *mut c_void = std::ptr::null_mut(); @@ -487,12 +520,12 @@ mod tests { .unwrap(); assert!(granted.success()); let store = files_only.join("store.json"); - crate::store::write_atomic(&store, &std::collections::HashMap::::new()) - .unwrap(); - let err = crate::store::read::>(&store) - .unwrap_err() - .to_string(); + let err = + crate::store::write_atomic(&store, &std::collections::HashMap::::new()) + .unwrap_err() + .to_string(); assert!(err.contains("S-1-1-0 may change it"), "{err}"); + assert!(!store.exists()); } #[cfg(target_os = "macos")] @@ -549,6 +582,17 @@ mod tests { std::fs::set_permissions(&shared, std::fs::Permissions::from_mode(0o777)).unwrap(); std::os::unix::fs::symlink(shared.join("meta-x"), &plugin).unwrap(); assert!(check_trusted_file(&plugin).is_err()); + + // So is one that passes through a link in such a directory, even + // when the link ends at a safe file: the link can be switched + let safe = tmp.path().join("safe"); + std::fs::create_dir(&safe).unwrap(); + std::fs::write(safe.join("meta-y"), "#!/bin/sh\n").unwrap(); + std::os::unix::fs::symlink(safe.join("meta-y"), shared.join("forward")).unwrap(); + let indirect = tmp.path().join("meta-y"); + std::os::unix::fs::symlink(shared.join("forward"), &indirect).unwrap(); + check_trusted_file(&safe.join("meta-y")).unwrap(); + assert!(check_trusted_file(&indirect).is_err()); } #[cfg(unix)] diff --git a/src/lock.rs b/src/lock.rs index 0f5da84..c7805cd 100644 --- a/src/lock.rs +++ b/src/lock.rs @@ -40,24 +40,40 @@ pub fn acquire(lock_path: &Path, timeout: Duration) -> Result { if let Some(parent) = lock_path.parent() { crate::data_dir::create_private_dir(parent)?; } + // A symlink here could lead every meta process to a different file + if std::fs::symlink_metadata(lock_path).is_ok_and(|meta| !meta.is_file()) { + anyhow::bail!( + "Refusing to lock {}: it is not a regular file (such as a symlink)", + escape_path(lock_path) + ); + } let mut options = OpenOptions::new(); options.read(true).write(true).create(true).truncate(false); // Readable by no one else: anyone who can open the file can hold the // lock and block every store write #[cfg(unix)] - std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600).custom_flags(libc::O_NOFOLLOW); + } let file = options .open(lock_path) .with_context(|| format!("Failed to open lock file: {}", escape_path(lock_path)))?; #[cfg(unix)] { - use std::os::unix::fs::PermissionsExt; - // a lock file left by an older meta may still be 0644 - let mode = file + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let meta = file .metadata() - .with_context(|| format!("Failed to stat {}", escape_path(lock_path)))? - .permissions() - .mode(); + .with_context(|| format!("Failed to stat {}", escape_path(lock_path)))?; + // SAFETY: geteuid has no preconditions and cannot fail. + if !meta.is_file() || meta.uid() != unsafe { libc::geteuid() } { + anyhow::bail!( + "Refusing to lock {}: it is not a regular file of yours", + escape_path(lock_path) + ); + } + // a lock file left by an older meta may still be 0644 + let mode = meta.permissions().mode(); if mode & 0o077 != 0 { file.set_permissions(std::fs::Permissions::from_mode(0o600)) .with_context(|| format!("Failed to restrict {}", escape_path(lock_path)))?; @@ -75,8 +91,9 @@ pub fn acquire(lock_path: &Path, timeout: Duration) -> Result { } #[cfg(windows)] { - use crate::win_acl::{current_user_sid, untrusted_access, READ_RIGHTS}; - if let Some(why) = untrusted_access(lock_path, ¤t_user_sid()?, READ_RIGHTS, "open")? { + use crate::win_acl::{current_user_sid, untrusted_access, DIR_RIGHTS, READ_RIGHTS}; + let rights = READ_RIGHTS | DIR_RIGHTS; + if let Some(why) = untrusted_access(lock_path, ¤t_user_sid()?, rights, "open")? { anyhow::bail!( "Refusing to lock {}: {why}, so another account could hold the lock", escape_path(lock_path) @@ -152,6 +169,18 @@ mod tests { } } + #[cfg(unix)] + #[test] + fn test_lock_refuses_a_symlink() { + let tmp = tempfile::tempdir().unwrap(); + let elsewhere = tmp.path().join("elsewhere"); + fs::write(&elsewhere, "").unwrap(); + let lock_path = tmp.path().join("x.lock"); + std::os::unix::fs::symlink(&elsewhere, &lock_path).unwrap(); + let err = acquire(&lock_path, WAIT).err().unwrap().to_string(); + assert!(err.contains("not a regular file"), "{err}"); + } + #[cfg(unix)] #[test] fn test_lock_file_is_private() { diff --git a/src/store.rs b/src/store.rs index 430a7f4..0722141 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1,7 +1,7 @@ //! Atomic JSON store read/write with lock-protected updates. //! //! Provides generic utilities for reading, writing, and updating JSON files -//! with atomic write semantics (write to `.tmp`, then rename) and optional +//! with atomic write semantics (write to a temporary file, then rename) and optional //! lock protection for concurrent access. use crate::display::escape_path; @@ -33,7 +33,7 @@ pub fn read(path: &Path) -> Result { /// Write data to a JSON file atomically. /// -/// Writes to a temporary file (`.tmp` suffix) then renames to the target path. +/// Writes to a temporary file beside it, then renames it to the target path. /// This ensures readers never see a partially-written file. pub fn write_atomic(path: &Path, data: &T) -> Result<()> { // Ensure parent directory exists @@ -43,13 +43,18 @@ pub fn write_atomic(path: &Path, data: &T) -> Result<()> { } } - let tmp_path = path.with_extension("tmp"); + // One temp file per writer (a fixed name lets two writers interleave), + // created fresh, readable and writable by you alone + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let tmp_path = path.with_extension(format!( + "tmp.{}.{}", + std::process::id(), + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); let json = serde_json::to_string_pretty(data).with_context(|| "Failed to serialize store data")?; - // A fresh file readable and writable by you alone (a leftover one from a - // crash is replaced, whatever its mode) let _ = std::fs::remove_file(&tmp_path); let mut options = std::fs::OpenOptions::new(); options.write(true).create_new(true); @@ -62,10 +67,18 @@ pub fn write_atomic(path: &Path, data: &T) -> Result<()> { .with_context(|| format!("Failed to write temp file: {}", escape_path(&tmp_path)))?; drop(file); - std::fs::rename(&tmp_path, path) - .with_context(|| format!("Failed to rename temp file to: {}", escape_path(path)))?; - - Ok(()) + // What it inherited (an access list on Windows, a macOS ACL) must not + // let others change it, or the next read would refuse it + if let Err(e) = check_private_file(&tmp_path) { + let _ = std::fs::remove_file(&tmp_path); + return Err(e); + } + let renamed = std::fs::rename(&tmp_path, path) + .with_context(|| format!("Failed to rename temp file to: {}", escape_path(path))); + if renamed.is_err() { + let _ = std::fs::remove_file(&tmp_path); + } + renamed } /// Refuse to read a store file another user could have written: anything but @@ -80,15 +93,25 @@ pub fn check_private_file(path: &Path) -> Result<()> { .with_context(|| format!("Failed to stat {}", escape_path(path)))?; // SAFETY: geteuid has no preconditions and cannot fail. let uid = unsafe { libc::geteuid() }; - if !meta.is_file() - || meta.uid() != uid - || meta.mode() & 0o022 != 0 - || crate::data_dir::acl_allows_others(path) - { + let shown = escape_path(path); + if !meta.is_file() { + anyhow::bail!("Refusing to read {shown}: it is not a regular file (such as a symlink)"); + } + if meta.uid() != uid { anyhow::bail!( - "Refusing to read {}: it must be a regular file owned by you that no one else can \ - write (fix with: chmod go-w, or remove it)", - escape_path(path) + "Refusing to read {shown}: it belongs to uid {}, not to you (uid {uid})", + meta.uid() + ); + } + if meta.mode() & 0o022 != 0 { + anyhow::bail!( + "Refusing to read {shown}: other users can write to it (fix with: chmod go-w '{shown}')" + ); + } + if crate::data_dir::acl_allows_others(path) { + anyhow::bail!( + "Refusing to read {shown}: its access control list lets others in \ + (remove with: chmod -N '{shown}')" ); } Ok(()) @@ -184,7 +207,7 @@ mod tests { assert_eq!(loaded.items.get("key").unwrap(), "value"); // Ensure tmp file was cleaned up - assert!(!path.with_extension("tmp").exists()); + assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 1); } #[test] From 798417b9ba65a3c63e30aedc84629e9758c4f0f2 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:48 -0700 Subject: [PATCH 15/29] fix: accept an absolute worktrees_dir inside the workspace with several missing parts Implements [[tasks/harmony-2749]] --- src/config.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/config.rs b/src/config.rs index ec9ed1e..5c1a09a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -357,10 +357,11 @@ pub fn relative_dir(base_dir: &Path, raw: &str) -> Result { // An absolute path is fine when it lies inside base_dir let raw_path = Path::new(raw); let relative = if raw_path.is_absolute() { + // the real path of the nearest part that exists, then the rest let real = |p: &Path| { - p.canonicalize() - .ok() - .or_else(|| Some(p.parent()?.canonicalize().ok()?.join(p.file_name()?))) + let existing = p.ancestors().find(|a| a.exists())?; + let rest = p.strip_prefix(existing).ok()?; + Some(existing.canonicalize().ok()?.join(rest)) }; real(base_dir) .zip(real(raw_path)) @@ -1656,6 +1657,15 @@ mod tests { assert_eq!(relative_dir(dir.path(), "wt").unwrap(), "wt"); let inside = dir.path().join("custom").to_string_lossy().into_owned(); assert_eq!(relative_dir(dir.path(), &inside).unwrap(), "custom"); + let deeper = dir + .path() + .join("build/worktrees") + .to_string_lossy() + .into_owned(); + assert_eq!( + relative_dir(dir.path(), &deeper).unwrap(), + "build/worktrees" + ); assert!(relative_dir(dir.path(), "../out").is_err()); assert!(relative_dir(dir.path(), "/").is_err()); } From 0f213d0fd947e2926b2a2e98e947d649028418e9 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:48 -0700 Subject: [PATCH 16/29] fix: escape config values in path-rule errors Implements [[tasks/harmony-2749]] --- src/config.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/config.rs b/src/config.rs index 5c1a09a..14152df 100644 --- a/src/config.rs +++ b/src/config.rs @@ -370,7 +370,7 @@ pub fn relative_dir(base_dir: &Path, raw: &str) -> Result { .ok() .map(|rest| rest.to_string_lossy().into_owned()) }) - .ok_or_else(|| format!("'{raw}' is outside {}", escape_path(base_dir)))? + .ok_or_else(|| format!("'{}' is outside {}", escape(raw), escape_path(base_dir)))? } else { raw.to_string() }; @@ -460,22 +460,25 @@ fn component_problem(part: &str) -> Option<&'static str> { fn normalize_project_path(raw: &str) -> Result { let unified = raw.replace('\\', "/"); if unified.starts_with('/') { - return Err(format!("path '{raw}' must be relative")); + return Err(format!("path '{}' must be relative", escape(raw))); } let mut parts = Vec::new(); for part in unified.split('/') { match part { "" | "." => {} - ".." => return Err(format!("path '{raw}' must not contain '..'")), + ".." => return Err(format!("path '{}' must not contain '..'", escape(raw))), part => match component_problem(part) { - Some(why) => return Err(format!("path '{raw}' has a component with {why}")), + Some(why) => { + return Err(format!("path '{}' has a component with {why}", escape(raw))) + } None => parts.push(part), }, } } if parts.is_empty() { return Err(format!( - "path '{raw}' must name a directory below the .meta file" + "path '{}' must name a directory below the .meta file", + escape(raw) )); } Ok(parts.join("/")) @@ -1667,6 +1670,9 @@ mod tests { "build/worktrees" ); assert!(relative_dir(dir.path(), "../out").is_err()); + // a value from the config is escaped in the message + let err = relative_dir(dir.path(), "../bad\nFORGED").unwrap_err(); + assert!(!err.contains('\n') && err.contains("bad\\nFORGED"), "{err}"); assert!(relative_dir(dir.path(), "/").is_err()); } From be9a715167e13908cdf2c49daca027c6c9372a6e Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:48 -0700 Subject: [PATCH 17/29] fix: reserve the configured worktrees_dir; read Windows object entries as unsafe; steady lock tests Lock tests no longer wait zero seconds for a lock just released: a process forked by a parallel test can share it for a moment. Implements [[tasks/harmony-2749]] --- src/config.rs | 38 ++++++++++++++++++++++++-------------- src/data_dir.rs | 6 +++++- src/lock.rs | 6 +++--- src/store.rs | 2 +- src/win_acl.rs | 24 ++++++++++++++++-------- 5 files changed, 49 insertions(+), 27 deletions(-) diff --git a/src/config.rs b/src/config.rs index 14152df..81e6b3e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -198,6 +198,12 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, .parent() .filter(|p| !p.as_os_str().is_empty()) .unwrap_or(Path::new(".")); + // Where worktrees live; no project may go there + let worktrees = config + .worktrees_dir + .as_deref() + .and_then(|dir| relative_dir(base_dir, dir).ok()) + .unwrap_or_else(|| ".worktrees".to_string()); let mut entries: Vec<_> = config.projects.into_iter().collect(); entries.sort_by(|a, b| a.0.cmp(&b.0)); let checked: Vec<(ProjectInfo, PathBuf)> = entries @@ -231,7 +237,7 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, depends_on, meta, }; - let location = validate_project(base_dir, &mut info).map_err(|reason| { + let location = validate_project(base_dir, &worktrees, &mut info).map_err(|reason| { anyhow::anyhow!( "Invalid project '{}' in {}: {reason}", escape(&info.name), @@ -268,7 +274,11 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, /// - Tags hold no whitespace and no `,`, which the `--tag` filter splits on. /// /// Returns where the project lives on disk (see [`resolve_inside`]). -fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result { +fn validate_project( + base_dir: &Path, + worktrees: &str, + info: &mut ProjectInfo, +) -> Result { let lists = [ ("tag", &info.tags), ("provides entry", &info.provides), @@ -314,14 +324,14 @@ fn validate_project(base_dir: &Path, info: &mut ProjectInfo) -> Result Result Resu ); } let header = &*ace.cast::(); - // Entries for children only, and deny or audit entries, - // grant nothing on this directory. - if header.AceFlags & INHERIT_ONLY_ACE != 0 - || !matches!( - header.AceType, - ACCESS_ALLOWED_ACE_TYPE | ACCESS_ALLOWED_CALLBACK_ACE_TYPE - ) - { + // Entries for children only grant nothing on this directory; + // nor do deny or audit entries + if header.AceFlags & INHERIT_ONLY_ACE != 0 { continue; } + match header.AceType { + ACCESS_ALLOWED_ACE_TYPE | ACCESS_ALLOWED_CALLBACK_ACE_TYPE => {} + // Object entries carry their SID at another offset; not + // reading them, assume they may let someone in + ACCESS_ALLOWED_OBJECT_ACE_TYPE | ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE => { + return Ok(Some( + "it has an object access entry this check cannot read".into(), + )); + } + _ => continue, + } let allowed = &*ace.cast::(); if allowed.Mask & rights == 0 { continue; From 3d2c152f321a226a5d177245e835d68144945b2a Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:48 -0700 Subject: [PATCH 18/29] fix: reserve where the worktree root resolves; names may not nest; strict store reads A project is refused inside the worktree root as resolved through symlinks, not only as written; an invalid worktrees_dir is a parse error. Project names, which are worktree destinations, may not nest or collide by case. A store file that cannot be checked (other than missing) is an error, so an update cannot replace its entries. Implements [[tasks/harmony-2749]] --- src/config.rs | 126 +++++++++++++++++++++++++++++++++++++------------- src/store.rs | 11 ++++- 2 files changed, 104 insertions(+), 33 deletions(-) diff --git a/src/config.rs b/src/config.rs index 81e6b3e..aab318c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -198,12 +198,17 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, .parent() .filter(|p| !p.as_os_str().is_empty()) .unwrap_or(Path::new(".")); - // Where worktrees live; no project may go there - let worktrees = config - .worktrees_dir - .as_deref() - .and_then(|dir| relative_dir(base_dir, dir).ok()) - .unwrap_or_else(|| ".worktrees".to_string()); + // Where worktrees live (as written, and where that really is); no + // project may go there. A bad worktrees_dir is an error like a bad entry. + let worktrees = match config.worktrees_dir.as_deref() { + Some(dir) => relative_dir(base_dir, dir).map_err(|why| { + anyhow::anyhow!("Invalid worktrees_dir in {}: {why}", escape_path(meta_path)) + })?, + None => ".worktrees".to_string(), + }; + let worktrees_at = resolve_inside(base_dir, &worktrees) + .ok() + .map(|at| PathBuf::from(at.to_string_lossy().to_lowercase())); let mut entries: Vec<_> = config.projects.into_iter().collect(); entries.sort_by(|a, b| a.0.cmp(&b.0)); let checked: Vec<(ProjectInfo, PathBuf)> = entries @@ -237,13 +242,15 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, depends_on, meta, }; - let location = validate_project(base_dir, &worktrees, &mut info).map_err(|reason| { - anyhow::anyhow!( - "Invalid project '{}' in {}: {reason}", - escape(&info.name), - escape_path(meta_path) - ) - })?; + let location = + validate_project(base_dir, &worktrees, worktrees_at.as_deref(), &mut info) + .map_err(|reason| { + anyhow::anyhow!( + "Invalid project '{}' in {}: {reason}", + escape(&info.name), + escape_path(meta_path) + ) + })?; Ok((info, location)) }) .collect::>()?; @@ -277,6 +284,7 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, fn validate_project( base_dir: &Path, worktrees: &str, + worktrees_at: Option<&Path>, info: &mut ProjectInfo, ) -> Result { let lists = [ @@ -345,7 +353,11 @@ fn validate_project( .components() .map(|c| c.as_os_str().to_string_lossy().into_owned()) .collect(); - if parts.iter().any(|p| p.eq_ignore_ascii_case(".git")) || in_worktrees(&parts.join("/")) { + let lowered = PathBuf::from(location.to_string_lossy().to_lowercase()); + if parts.iter().any(|p| p.eq_ignore_ascii_case(".git")) + || in_worktrees(&parts.join("/")) + || worktrees_at.is_some_and(|at| lowered.starts_with(at)) + { return Err(format!( "path '{}' leads into .git or {worktrees} through a symlink", info.path @@ -391,7 +403,9 @@ pub fn relative_dir(base_dir: &Path, raw: &str) -> Result { /// through existing symlinks, and without case, which some filesystems /// ignore. A repo inside another belongs in a nested `.meta` (`meta: true`). fn check_no_overlap(projects: &[(ProjectInfo, PathBuf)]) -> Result<(), String> { - let keyed: Vec<_> = projects + // Paths, by where they resolve; and names, which worktrees use as + // destinations (`/`) + let by_location: Vec<_> = projects .iter() .map(|(info, location)| { ( @@ -400,26 +414,44 @@ fn check_no_overlap(projects: &[(ProjectInfo, PathBuf)]) -> Result<(), String> { ) }) .collect(); + if let Some((outer, inner)) = nested(&by_location) { + return Err(format!( + "project '{}' (path '{}') is at or inside project '{}' (path '{}'); \ + list it in a nested .meta instead", + escape(&inner.name), + escape(&inner.path), + escape(&outer.name), + escape(&outer.path) + )); + } + let by_name: Vec<_> = projects + .iter() + .map(|(info, _)| (PathBuf::from(info.name.to_ascii_lowercase()), info)) + .collect(); + if let Some((outer, inner)) = nested(&by_name) { + return Err(format!( + "project name '{}' is the same as or inside '{}', and names are worktree \ + destinations", + escape(&inner.name), + escape(&outer.name) + )); + } + Ok(()) +} + +/// The first pair whose keys are equal or nested, outer first. +fn nested<'a>(keyed: &[(PathBuf, &'a ProjectInfo)]) -> Option<(&'a ProjectInfo, &'a ProjectInfo)> { for (i, (outer_key, outer)) in keyed.iter().enumerate() { for (inner_key, inner) in keyed.iter().skip(i + 1) { - let (outer, inner) = if inner_key.starts_with(outer_key) { - (outer, inner) - } else if outer_key.starts_with(inner_key) { - (inner, outer) - } else { - continue; - }; - return Err(format!( - "project '{}' (path '{}') is at or inside project '{}' (path '{}'); \ - list it in a nested .meta instead", - escape(&inner.name), - escape(&inner.path), - escape(&outer.name), - escape(&outer.path) - )); + if inner_key.starts_with(outer_key) { + return Some((outer, inner)); + } + if outer_key.starts_with(inner_key) { + return Some((inner, outer)); + } } } - Ok(()) + None } /// What is wrong with a name or path component, if anything. The same @@ -1686,6 +1718,38 @@ mod tests { assert!(relative_dir(dir.path(), "/").is_err()); } + #[test] + fn test_parse_rejects_nesting_or_colliding_names() { + let err = parse_err( + r#"{"projects": {"a": {"repo": "u", "path": "x"}, "a/b": {"repo": "u", "path": "y"}}}"#, + ); + assert!( + err.contains("project name 'a/b' is the same as or inside 'a'"), + "{err}" + ); + let err = parse_err( + r#"{"projects": {"API": {"repo": "u", "path": "x"}, "api": {"repo": "u", "path": "y"}}}"#, + ); + assert!(err.contains("is the same as or inside"), "{err}"); + let err = parse_err(r#"{"projects": {}, "worktrees_dir": "../out"}"#); + assert!(err.contains("Invalid worktrees_dir"), "{err}"); + } + + #[cfg(unix)] + #[test] + fn test_parse_rejects_projects_where_the_worktree_root_resolves() { + // .worktrees is a symlink to storage/, so storage/review is in it + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("storage")).unwrap(); + std::os::unix::fs::symlink(dir.path().join("storage"), dir.path().join(".worktrees")) + .unwrap(); + let err = parse_err_in( + dir.path(), + r#"{"projects": {"app": {"repo": "u", "path": "storage/review"}}}"#, + ); + assert!(err.contains("through a symlink"), "{err}"); + } + #[test] fn test_parse_normalizes_paths() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/store.rs b/src/store.rs index e28467d..179e3e8 100644 --- a/src/store.rs +++ b/src/store.rs @@ -15,8 +15,15 @@ use std::path::Path; /// Returns an error if the file exists but can't be parsed, or if another /// user could have written it (see [`check_private_file`]). pub fn read(path: &Path) -> Result { - if std::fs::symlink_metadata(path).is_err() { - return Ok(T::default()); + // Only a missing file means an empty store: any other failure to look + // at it must not let an update replace every entry + match std::fs::symlink_metadata(path) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(T::default()), + Err(e) => { + return Err(e) + .with_context(|| format!("Failed to stat store file: {}", escape_path(path))) + } + Ok(_) => {} } check_private_file(path)?; From 3e64df85bb46b0d630909a891d0e5a60a3fb30d1 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:48 -0700 Subject: [PATCH 19/29] fix: refuse a link on the way to a trusted file on Windows Implements [[tasks/harmony-2749]] --- src/data_dir.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/data_dir.rs b/src/data_dir.rs index 3b12844..fc941be 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -68,6 +68,8 @@ pub(crate) fn create_private_dir(dir: &Path) -> Result<()> { /// the final file must pass [`check_private_dir`], each link must belong to /// you or root, and the file itself must belong to you or root and be /// writable by no one else. +// Off Unix links are refused, so the walk below never follows one +#[cfg_attr(not(unix), allow(unused_mut, clippy::never_loop))] pub fn check_trusted_file(path: &Path) -> Result<()> { let shown = crate::display::escape_path(path); let mut current = @@ -81,6 +83,13 @@ pub fn check_trusted_file(path: &Path) -> Result<()> { let meta = std::fs::symlink_metadata(¤t) .with_context(|| format!("Failed to stat {shown}"))?; if meta.file_type().is_symlink() { + // On Windows the link's own access list is not checked here, so + // a link is refused, as in check_private_dir + #[cfg(not(unix))] + anyhow::bail!( + "Refusing to use {shown}: {} is a link; use the real file", + crate::display::escape_path(¤t) + ); #[cfg(unix)] { // SAFETY: geteuid has no preconditions and cannot fail. @@ -91,11 +100,11 @@ pub fn check_trusted_file(path: &Path) -> Result<()> { crate::display::escape_path(¤t) ); } + let target = std::fs::read_link(¤t) + .with_context(|| format!("Failed to read the symlink {shown}"))?; + current = parent.join(target); + continue; } - let target = std::fs::read_link(¤t) - .with_context(|| format!("Failed to read the symlink {shown}"))?; - current = parent.join(target); - continue; } #[cfg(unix)] { From fc5941a82473ec4f84e78f866bcd54b744dc495a Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:48 -0700 Subject: [PATCH 20/29] fix: refuse a worktrees_dir inside a project's checkout Implements [[tasks/harmony-2749]] --- src/config.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/config.rs b/src/config.rs index aab318c..15af31d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -256,6 +256,19 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, .collect::>()?; check_no_overlap(&checked) .map_err(|e| anyhow::anyhow!("Invalid projects in {}: {e}", escape_path(meta_path)))?; + // Nor may the worktree directory sit inside a project's checkout + if let Some(at) = &worktrees_at { + for (info, location) in &checked { + if at.starts_with(PathBuf::from(location.to_string_lossy().to_lowercase())) { + anyhow::bail!( + "Invalid worktrees_dir in {}: '{}' is inside project '{}'", + escape_path(meta_path), + escape(&worktrees), + escape(&info.name) + ); + } + } + } let projects = checked.into_iter().map(|(info, _)| info).collect(); Ok((projects, config.ignore)) @@ -1731,6 +1744,10 @@ mod tests { r#"{"projects": {"API": {"repo": "u", "path": "x"}, "api": {"repo": "u", "path": "y"}}}"#, ); assert!(err.contains("is the same as or inside"), "{err}"); + let err = parse_err( + r#"{"projects": {"app": {"repo": "u", "path": "app"}}, "worktrees_dir": "app/wt"}"#, + ); + assert!(err.contains("is inside project 'app'"), "{err}"); let err = parse_err(r#"{"projects": {}, "worktrees_dir": "../out"}"#); assert!(err.contains("Invalid worktrees_dir"), "{err}"); } From d4f1ea5aad6ac9572af3b3f85de6a3540de403c0 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:48 -0700 Subject: [PATCH 21/29] fix: always reserve .worktrees, also with a custom worktrees_dir Implements [[tasks/harmony-2749]] --- src/config.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/config.rs b/src/config.rs index 15af31d..a53f158 100644 --- a/src/config.rs +++ b/src/config.rs @@ -345,9 +345,12 @@ fn validate_project( return Err(format!("tag '{tag}' contains whitespace or ','")); } info.path = normalize_project_path(&info.path)?; + // The configured worktree directory, and the default one always let in_worktrees = |value: &str| { - let (value, worktrees) = (value.to_ascii_lowercase(), worktrees.to_ascii_lowercase()); - value == worktrees || value.starts_with(&format!("{worktrees}/")) + let value = value.to_ascii_lowercase(); + [worktrees.to_ascii_lowercase(), ".worktrees".to_string()] + .iter() + .any(|dir| value == *dir || value.starts_with(&format!("{dir}/"))) }; for value in [&info.name, &info.path] { if in_worktrees(value) { @@ -1642,6 +1645,10 @@ mod tests { r#"{"projects": {"p": {"repo": "u", "path": "sets/x"}}, "worktrees_dir": "sets"}"#, "inside sets", ), + ( + r#"{"projects": {".worktrees/b": {"repo": "u", "path": "b"}}, "worktrees_dir": "sets"}"#, + "inside sets", + ), (r#"{"projects": {"x|y": "u"}}"#, "ASCII letters"), ( r#"{"projects": {"a.": {"repo": "u", "path": "b"}}}"#, From 84f97a30e83b003cc2a7e942da212610c3af4a9c Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:48 -0700 Subject: [PATCH 22/29] fix: a worktree directory may not resolve into .git Implements [[tasks/harmony-2749]] --- src/config.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/config.rs b/src/config.rs index a53f158..0385dfd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -409,7 +409,18 @@ pub fn relative_dir(base_dir: &Path, raw: &str) -> Result { raw.to_string() }; let normal = normalize_project_path(&relative)?; - resolve_inside(base_dir, &normal)?; + let location = resolve_inside(base_dir, &normal)?; + // Nor may it lead into git's own data + let base = base_dir + .canonicalize() + .map_err(|e| format!("cannot resolve {}: {e}", escape_path(base_dir)))?; + if location.strip_prefix(&base).is_ok_and(|inside| { + inside + .components() + .any(|c| c.as_os_str().eq_ignore_ascii_case(".git")) + }) { + return Err(format!("'{}' leads into .git", escape(raw))); + } Ok(normal) } @@ -1732,6 +1743,15 @@ mod tests { "build/worktrees" ); assert!(relative_dir(dir.path(), "../out").is_err()); + #[cfg(unix)] + { + std::fs::create_dir(dir.path().join(".git")).unwrap(); + std::os::unix::fs::symlink(dir.path().join(".git"), dir.path().join("storage")) + .unwrap(); + assert!(relative_dir(dir.path(), "storage") + .unwrap_err() + .contains("leads into .git")); + } // a value from the config is escaped in the message let err = relative_dir(dir.path(), "../bad\nFORGED").unwrap_err(); assert!(!err.contains('\n') && err.contains("bad\\nFORGED"), "{err}"); From a56f6907e244a9da5dc568695d3ae04fedaca506 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:48 -0700 Subject: [PATCH 23/29] fix(store): say how to recover from a lock or store file another user owns A lock or store file left by meta run with sudo blocked every store write with no hint of the fix. Implements [[tasks/harmony-2749]] --- src/lock.rs | 5 ++++- src/store.rs | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/lock.rs b/src/lock.rs index cee688d..dd354e0 100644 --- a/src/lock.rs +++ b/src/lock.rs @@ -68,7 +68,10 @@ pub fn acquire(lock_path: &Path, timeout: Duration) -> Result { // SAFETY: geteuid has no preconditions and cannot fail. if !meta.is_file() || meta.uid() != unsafe { libc::geteuid() } { anyhow::bail!( - "Refusing to lock {}: it is not a regular file of yours", + "Refusing to lock {}: it is not a regular file of yours \ + (if it was left by meta run as another user, such as with sudo, \ + remove it: rm '{}')", + escape_path(lock_path), escape_path(lock_path) ); } diff --git a/src/store.rs b/src/store.rs index 179e3e8..ffff944 100644 --- a/src/store.rs +++ b/src/store.rs @@ -106,7 +106,9 @@ pub fn check_private_file(path: &Path) -> Result<()> { } if meta.uid() != uid { anyhow::bail!( - "Refusing to read {shown}: it belongs to uid {}, not to you (uid {uid})", + "Refusing to read {shown}: it belongs to uid {}, not to you (uid {uid}); \ + if meta ran as that user (such as with sudo), take it back with: \ + sudo chown {uid} '{shown}'", meta.uid() ); } From 2e7972fc20060290ed21314a123f0f08d0ebdb4c Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:48 -0700 Subject: [PATCH 24/29] fix(data-dir): a filesystem without ACLs (ENOTSUP) is not an ACL that lets others in Implements [[tasks/harmony-2749]] --- src/data_dir.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/data_dir.rs b/src/data_dir.rs index fc941be..f2eead6 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -298,9 +298,11 @@ pub(crate) fn acl_allows_others(path: &Path) -> bool { unsafe { let acl = acl_get_link_np(c_path.as_ptr(), ACL_TYPE_EXTENDED); if acl.is_null() { - // ENOENT means there is no ACL; anything else is not knowing, - // which is treated as an ACL that may let others in - return std::io::Error::last_os_error().raw_os_error() != Some(libc::ENOENT); + // ENOENT means there is no ACL, and ENOTSUP a filesystem without + // ACLs; anything else is not knowing, which is treated as an ACL + // that may let others in + let errno = std::io::Error::last_os_error().raw_os_error(); + return errno != Some(libc::ENOENT) && errno != Some(libc::ENOTSUP); } let mut allows = false; let mut entry: *mut c_void = std::ptr::null_mut(); From c47c631b2d68f9c6352349d75d279d3ea7f942eb Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:27:48 -0700 Subject: [PATCH 25/29] fix: walk_projects walks a chosen config's tree and fails on a refused nested config Implements [[tasks/harmony-2749]] --- src/config.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/config.rs b/src/config.rs index 0385dfd..47b948c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -650,12 +650,22 @@ pub fn walk_meta_tree( let (projects, _ignore) = parse_meta_config(&config_path)?; let meta_dir = config_path.parent().unwrap_or(Path::new(".")); + walk_projects(meta_dir, &projects, max_depth) +} +/// The meta tree whose top level is `projects`, the parsed config in +/// `meta_dir` (such as one chosen with `--config`), walked like +/// [`walk_meta_tree`]. A nested config that fails to parse is an error. +pub fn walk_projects( + meta_dir: &Path, + projects: &[ProjectInfo], + max_depth: Option, +) -> anyhow::Result> { let mut visited = std::collections::HashSet::new(); visited.insert(meta_dir.canonicalize().unwrap_or(meta_dir.to_path_buf())); let depth = max_depth.unwrap_or(usize::MAX); - walk_inner(meta_dir, &projects, depth, 0, &mut visited) + walk_inner(meta_dir, projects, depth, 0, &mut visited) } /// Flatten a meta tree into fully-qualified path strings. From 8a2f9421b20ad8e62320bccc30881c635e2c67e3 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:48:00 -0700 Subject: [PATCH 26/29] fix: a path part that cannot be examined is refused; escape more invisible characters; derive the ACE SID pointer from the raw entry resolve_inside took any lstat error as 'does not exist yet', so a directory without permission could hide a symlink out of the workspace. Only NotFound now means missing. Implements [[tasks/harmony-2749]] --- src/config.rs | 10 +++++++++- src/display.rs | 26 +++++++++++++++++++++++--- src/win_acl.rs | 8 +++++--- 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/src/config.rs b/src/config.rs index 47b948c..72538d9 100644 --- a/src/config.rs +++ b/src/config.rs @@ -568,7 +568,15 @@ pub fn resolve_inside(base_dir: &Path, rel: &str) -> Result { continue; } match current.symlink_metadata() { - Err(_) => exists = false, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => exists = false, + // What can't be examined (no permission, say) may hold a + // symlink out, so it is refused rather than taken as missing + Err(e) => { + return Err(format!( + "path '{rel}' cannot be checked at '{}': {e}", + escape_path(¤t) + )) + } Ok(meta) if meta.file_type().is_symlink() => match current.canonicalize() { Ok(target) if target.starts_with(&base) => current = target, Ok(_) => { diff --git a/src/display.rs b/src/display.rs index feac442..ca750be 100644 --- a/src/display.rs +++ b/src/display.rs @@ -14,19 +14,29 @@ use std::fmt::Write; /// controls and DEL; the Unicode bidirectional controls, which reorder how a /// line is displayed (U+061C, U+200E-F, U+202A-E, U+2066-9); the line and /// paragraph separators (U+2028-9), which many renderers treat as line -/// breaks; and invisible format characters that hide text from a reader -/// (soft hyphen, zero-width characters, word joiners, BOM, tag characters). +/// breaks; and invisible characters that hide text from a reader or make one +/// value look like another (soft hyphen, combining grapheme joiner, Hangul +/// fillers, Mongolian vowel separator, zero-width characters, word joiners +/// and deprecated format controls, BOM, interlinear +/// annotation controls, tag characters). pub fn is_unsafe_char(c: char) -> bool { c.is_control() || matches!( c, '\u{AD}' + | '\u{034F}' | '\u{061C}' + | '\u{115F}'..='\u{1160}' + | '\u{180E}' | '\u{200B}'..='\u{200F}' | '\u{2028}'..='\u{202E}' - | '\u{2060}'..='\u{2069}' + | '\u{2060}'..='\u{206F}' + | '\u{3164}' | '\u{FEFF}' + | '\u{FFA0}' + | '\u{FFF9}'..='\u{FFFB}' | '\u{E0000}'..='\u{E007F}' + ) } @@ -91,6 +101,16 @@ mod tests { ); } + #[test] + fn invisible_fillers_are_made_visible() { + assert_eq!( + escape("a\u{34f}b\u{3164}c\u{180e}d\u{206a}e\u{fff9}f"), + "a\\u{34f}b\\u{3164}c\\u{180e}d\\u{206a}e\\u{fff9}f" + ); + // Emoji keep their variation selector + assert!(matches!(escape("ok \u{2714}\u{fe0f}"), Cow::Borrowed(_))); + } + #[test] fn escape_lines_keeps_newlines_only() { assert!(matches!(escape_lines("a\nb"), Cow::Borrowed(_))); diff --git a/src/win_acl.rs b/src/win_acl.rs index 6ce4e95..c1347b0 100644 --- a/src/win_acl.rs +++ b/src/win_acl.rs @@ -153,11 +153,13 @@ pub fn untrusted_access(dir: &Path, user: &str, rights: u32, verb: &str) -> Resu } _ => continue, } - let allowed = &*ace.cast::(); - if allowed.Mask & rights == 0 { + // The SID runs past the struct, so its pointer comes from the + // raw entry pointer, not from a reference to the struct + let allowed = ace.cast::(); + if (*allowed).Mask & rights == 0 { continue; } - let sid = sid_string(std::ptr::addr_of!(allowed.SidStart).cast_mut().cast())?; + let sid = sid_string(std::ptr::addr_of_mut!((*allowed).SidStart).cast())?; if !trusted(&sid) { return Ok(Some(format!("{sid} may {verb} it"))); } From 07d22ced93401506c4070ca6a1b2974e41817670 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 18:30:23 -0700 Subject: [PATCH 27/29] fix: the meta tree walk fails on a nested config it cannot examine walk_inner found a project's config with find_meta_config, whose exists()/is_file() turn a stat error into 'no config', so a .meta link into a directory that can't be entered silently dropped that subtree. nested_config_in now treats only NotFound as absent. Also keeps the zero-width joiner, which emoji sequences use, out of the escaped set. Implements [[tasks/harmony-2749]] --- src/config.rs | 110 ++++++++++++++++++++++++++++++++++++++++++++++--- src/display.rs | 9 +++- 2 files changed, 111 insertions(+), 8 deletions(-) diff --git a/src/config.rs b/src/config.rs index 72538d9..0697102 100644 --- a/src/config.rs +++ b/src/config.rs @@ -123,6 +123,41 @@ pub fn find_meta_config_in(dir: &Path) -> Option<(PathBuf, ConfigFormat)> { None } +/// The config file directly in project directory `dir`, for walking the +/// meta tree. Only a missing directory or file means there is none: one +/// that cannot be examined (no permission, a link whose target is out of +/// reach) is an error, since skipping it would silently drop its repos. +/// A `.meta` directory (the plugins folder) is not a config. +fn nested_config_in(dir: &Path) -> anyhow::Result> { + let unreadable = + |path: &Path, e: std::io::Error| anyhow::anyhow!("Cannot read {}: {e}", escape_path(path)); + match std::fs::metadata(dir) { + Ok(meta) if meta.is_dir() => {} + Ok(_) => return Ok(None), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(unreadable(dir, e)), + } + for (name, format) in &[ + (".meta", ConfigFormat::Json), + (".meta.json", ConfigFormat::Json), + (".meta.yaml", ConfigFormat::Yaml), + (".meta.yml", ConfigFormat::Yaml), + ] { + let candidate = dir.join(name); + match std::fs::symlink_metadata(&candidate) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, + Err(e) => return Err(unreadable(&candidate, e)), + Ok(_) => {} + } + match std::fs::metadata(&candidate) { + Ok(meta) if meta.is_file() => return Ok(Some((candidate, format.clone()))), + Ok(_) => continue, + Err(e) => return Err(unreadable(&candidate, e)), + } + } + Ok(None) +} + /// Find the meta config file, checking for .meta, .meta.yaml, and .meta.yml /// /// Walks up from `start_dir` to the filesystem root, looking for config files. @@ -823,12 +858,7 @@ fn walk_inner( let project_dir = base_dir.join(&project.path); // Check if this project has its own .meta file directly in its directory - let nested_config = if project_dir.is_dir() { - find_meta_config(&project_dir, None) - .filter(|(path, _)| path.parent() == Some(project_dir.as_path())) - } else { - None - }; + let nested_config = nested_config_in(&project_dir)?; let has_meta = nested_config.is_some(); // Recurse into children if within depth limit and this is a meta repo. @@ -1523,6 +1553,74 @@ mod tests { } } + /// Whether a directory with mode 000 still can't be entered here (as + /// root it can, and permission tests have nothing to check). + #[cfg(unix)] + fn locked_dir(path: &Path) -> bool { + use std::os::unix::fs::PermissionsExt; + std::fs::create_dir_all(path).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o000)).unwrap(); + std::fs::read_dir(path).is_err() + } + + #[cfg(unix)] + fn unlock_dir(path: &Path) { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).unwrap(); + } + + #[cfg(unix)] + #[test] + fn test_parse_rejects_a_path_through_a_directory_it_cannot_examine() { + // `locked` may hold a symlink out; not being able to look is no + // proof that the rest of the path does not exist yet + let dir = tempfile::tempdir().unwrap(); + let locked = dir.path().join("locked"); + if !locked_dir(&locked) { + return; + } + let err = parse_err_in( + dir.path(), + r#"{"projects": {"p": {"repo": "u", "path": "locked/x"}}}"#, + ); + unlock_dir(&locked); + assert!(err.contains("cannot be checked at"), "{err}"); + } + + #[cfg(unix)] + #[test] + fn test_walk_fails_on_a_nested_config_it_cannot_read() { + // group/.meta links into a directory that can't be entered: the walk + // must fail rather than leave group's repos out + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(dir.path().join("group/core")).unwrap(); + std::fs::write( + dir.path().join(".meta"), + r#"{"projects": {"group": {"repo": "u", "meta": true}}}"#, + ) + .unwrap(); + let private = dir.path().join("private"); + std::fs::create_dir(&private).unwrap(); + std::fs::write( + private.join("config.json"), + r#"{"projects": {"core": "u"}}"#, + ) + .unwrap(); + std::os::unix::fs::symlink("../private/config.json", dir.path().join("group/.meta")) + .unwrap(); + assert!(walk_meta_tree(dir.path(), None).is_ok()); + if !locked_dir(&private) { + return; + } + let result = walk_meta_tree(dir.path(), None); + unlock_dir(&private); + let err = result.unwrap_err().to_string(); + assert!( + err.contains("Cannot read") && err.contains(".meta"), + "{err}" + ); + } + #[cfg(unix)] #[test] fn test_parse_rejects_overlap_through_symlink_alias() { diff --git a/src/display.rs b/src/display.rs index ca750be..b957f58 100644 --- a/src/display.rs +++ b/src/display.rs @@ -16,7 +16,7 @@ use std::fmt::Write; /// paragraph separators (U+2028-9), which many renderers treat as line /// breaks; and invisible characters that hide text from a reader or make one /// value look like another (soft hyphen, combining grapheme joiner, Hangul -/// fillers, Mongolian vowel separator, zero-width characters, word joiners +/// fillers, Mongolian vowel separator, zero-width characters (not the joiner, which emoji sequences use), word joiners /// and deprecated format controls, BOM, interlinear /// annotation controls, tag characters). pub fn is_unsafe_char(c: char) -> bool { @@ -28,7 +28,8 @@ pub fn is_unsafe_char(c: char) -> bool { | '\u{061C}' | '\u{115F}'..='\u{1160}' | '\u{180E}' - | '\u{200B}'..='\u{200F}' + | '\u{200B}'..='\u{200C}' + | '\u{200E}'..='\u{200F}' | '\u{2028}'..='\u{202E}' | '\u{2060}'..='\u{206F}' | '\u{3164}' @@ -109,6 +110,10 @@ mod tests { ); // Emoji keep their variation selector assert!(matches!(escape("ok \u{2714}\u{fe0f}"), Cow::Borrowed(_))); + assert!(matches!( + escape("\u{1f468}\u{200d}\u{1f467}"), + Cow::Borrowed(_) + )); } #[test] From f5e4c359d54f5128735c6bac3fcfbd535acfa776 Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 18:56:38 -0700 Subject: [PATCH 28/29] fix: one config lookup that fails on a config it cannot examine find_meta_config_in returns an error for a config that exists but cannot be read (no permission, a link out of reach) instead of 'none', and is the lookup the tree walk uses. find_meta_config returns such a candidate, so reading it fails, rather than walking on to another workspace's config. Implements [[tasks/harmony-2749]] --- src/config.rs | 47 ++++++++++++++++++++--------------------------- 1 file changed, 20 insertions(+), 27 deletions(-) diff --git a/src/config.rs b/src/config.rs index 0697102..a65652a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -104,31 +104,13 @@ pub enum ConfigFormat { Yaml, } -/// Check if a directory has a meta config file (.meta, .meta.yaml, or .meta.yml). -/// -/// Unlike `find_meta_config`, this does NOT walk up the directory tree. -/// Returns the path and format if found. -pub fn find_meta_config_in(dir: &Path) -> Option<(PathBuf, ConfigFormat)> { - for (name, format) in &[ - (".meta", ConfigFormat::Json), - (".meta.json", ConfigFormat::Json), - (".meta.yaml", ConfigFormat::Yaml), - (".meta.yml", ConfigFormat::Yaml), - ] { - let candidate = dir.join(name); - if candidate.exists() && candidate.is_file() { - return Some((candidate, format.clone())); - } - } - None -} - -/// The config file directly in project directory `dir`, for walking the -/// meta tree. Only a missing directory or file means there is none: one +/// The config file directly in directory `dir` (`.meta`, `.meta.json`, +/// `.meta.yaml`, `.meta.yml`, in that order). Only a missing directory or +/// file means there is none: one /// that cannot be examined (no permission, a link whose target is out of /// reach) is an error, since skipping it would silently drop its repos. /// A `.meta` directory (the plugins folder) is not a config. -fn nested_config_in(dir: &Path) -> anyhow::Result> { +pub fn find_meta_config_in(dir: &Path) -> anyhow::Result> { let unreadable = |path: &Path, e: std::io::Error| anyhow::anyhow!("Cannot read {}: {e}", escape_path(path)); match std::fs::metadata(dir) { @@ -188,7 +170,15 @@ pub fn find_meta_config( loop { for (name, format) in &candidates { let candidate = current_dir.join(name); - if candidate.exists() && candidate.is_file() { + // A candidate that exists but can't be examined is returned, so + // reading it fails loudly, rather than skipped for a config + // further up (another workspace's) + let found = match std::fs::symlink_metadata(&candidate) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, + Err(_) => true, + Ok(_) => !matches!(std::fs::metadata(&candidate), Ok(meta) if !meta.is_file()), + }; + if found { return Some((candidate, format.clone())); } } @@ -644,7 +634,7 @@ pub fn resolve_inside(base_dir: &Path, rel: &str) -> Result { /// Load defaults from a meta config file. /// Returns MetaDefaults::default() if no config found or on parse error. pub fn load_meta_defaults(start_dir: &Path) -> MetaDefaults { - let Some((config_path, _format)) = find_meta_config_in(start_dir) else { + let Ok(Some((config_path, _format))) = find_meta_config_in(start_dir) else { return MetaDefaults::default(); }; @@ -858,7 +848,7 @@ fn walk_inner( let project_dir = base_dir.join(&project.path); // Check if this project has its own .meta file directly in its directory - let nested_config = nested_config_in(&project_dir)?; + let nested_config = find_meta_config_in(&project_dir)?; let has_meta = nested_config.is_some(); // Recurse into children if within depth limit and this is a meta repo. @@ -2071,11 +2061,14 @@ mod tests { fn test_meta_directory_is_not_config() { let dir = tempfile::tempdir().unwrap(); std::fs::create_dir_all(dir.path().join(".meta/skills")).unwrap(); - assert!(find_meta_config_in(dir.path()).is_none()); + assert!(find_meta_config_in(dir.path()).unwrap().is_none()); std::fs::write(dir.path().join(".meta.yaml"), "projects: {}\n").unwrap(); let expected = dir.path().join(".meta.yaml"); - assert_eq!(find_meta_config_in(dir.path()).unwrap().0, expected); + assert_eq!( + find_meta_config_in(dir.path()).unwrap().unwrap().0, + expected + ); assert_eq!(find_meta_config(dir.path(), None).unwrap().0, expected); } From 40f6ee2017ae3567e6d707ad78415cc70aab889f Mon Sep 17 00:00:00 2001 From: gold-silver-copper <157451540+gold-silver-copper@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:29:10 -0700 Subject: [PATCH 29/29] fix: a walk stopped by its depth limit does not fail on a config it would not read; create_private_dir is public Implements [[tasks/harmony-2749]] --- src/config.rs | 8 +++++++- src/data_dir.rs | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/config.rs b/src/config.rs index a65652a..2c4c044 100644 --- a/src/config.rs +++ b/src/config.rs @@ -848,7 +848,13 @@ fn walk_inner( let project_dir = base_dir.join(&project.path); // Check if this project has its own .meta file directly in its directory - let nested_config = find_meta_config_in(&project_dir)?; + // Past the depth limit it is never read, so a config that can't be + // examined only stops a walk that would recurse into it + let nested_config = if current_depth < max_depth { + find_meta_config_in(&project_dir)? + } else { + find_meta_config_in(&project_dir).ok().flatten() + }; let has_meta = nested_config.is_some(); // Recurse into children if within depth limit and this is a meta repo. diff --git a/src/data_dir.rs b/src/data_dir.rs index f2eead6..3d0660d 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -48,7 +48,7 @@ pub fn data_subdir(namespace: &str) -> Result { } /// Create `dir` (mode 0700 on Unix) if missing, then check it is private. -pub(crate) fn create_private_dir(dir: &Path) -> Result<()> { +pub fn create_private_dir(dir: &Path) -> Result<()> { let mut builder = std::fs::DirBuilder::new(); builder.recursive(true); #[cfg(unix)]