diff --git a/Cargo.toml b/Cargo.toml index f01ce21..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] @@ -17,5 +19,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/config.rs b/src/config.rs index 43f4904..2c4c044 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; @@ -103,11 +104,21 @@ 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)> { +/// 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. +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) { + 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), @@ -115,11 +126,18 @@ pub fn find_meta_config_in(dir: &Path) -> Option<(PathBuf, ConfigFormat)> { (".meta.yml", ConfigFormat::Yaml), ] { let candidate = dir.join(name); - if candidate.exists() && candidate.is_file() { - return Some((candidate, format.clone())); + 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)), } } - None + Ok(None) } /// Find the meta config file, checking for .meta, .meta.yaml, and .meta.yml @@ -152,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())); } } @@ -161,23 +187,56 @@ 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()))?; + 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 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() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + // 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 .into_iter() .map(|(name, entry)| { let (repo, path, tags, provides, depends_on, meta) = match entry { @@ -199,8 +258,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,20 +266,375 @@ pub fn parse_meta_config(meta_path: &Path) -> anyhow::Result<(Vec, provides, depends_on, meta, + }; + 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::>()?; + 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)) +} + +/// 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 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`. +/// - `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 +/// 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. +/// +/// Returns where the project lives on disk (see [`resolve_inside`]). +fn validate_project( + base_dir: &Path, + worktrees: &str, + worktrees_at: Option<&Path>, + info: &mut ProjectInfo, +) -> Result { + 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) + )); + } + } + // A name may be a relative path, such as `vendor/lib` for a nested + // repo: worktrees put the project at `/`. 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()); + } + 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)?; + // The configured worktree directory, and the default one always + let in_worktrees = |value: &str| { + 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) { + return Err(format!( + "'{value}' is inside {worktrees}, where worktrees live" + )); + } + } + let location = resolve_inside(base_dir, &info.path)?; + // Where it really goes must not be reserved either (`alias -> .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(); + 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 + )); + } + } + Ok(location) +} + +/// Check a directory a config names relative to its own directory, such as +/// `worktrees_dir`, by the rules for project paths, and return its normal +/// form. (An absolute or outside location is the user's to choose, through +/// an environment variable such as `META_WORKTREES`, not the config's.) +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| { + 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)) + .and_then(|(base, path)| { + path.strip_prefix(base) + .ok() + .map(|rest| rest.to_string_lossy().into_owned()) + }) + .ok_or_else(|| format!("'{}' is outside {}", escape(raw), escape_path(base_dir)))? + } else { + raw.to_string() + }; + let normal = normalize_project_path(&relative)?; + 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) +} + +/// 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> { + // Paths, by where they resolve; and names, which worktrees use as + // destinations (`/`) + let by_location: Vec<_> = projects + .iter() + .map(|(info, location)| { + ( + PathBuf::from(location.to_string_lossy().to_lowercase()), + info, + ) }) .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(()) +} - // Sort projects alphabetically by name for deterministic order - projects.sort_by(|a, b| a.name.cmp(&b.name)); +/// 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) { + if inner_key.starts_with(outer_key) { + return Some((outer, inner)); + } + if outer_key.starts_with(inner_key) { + return Some((inner, outer)); + } + } + } + None +} - Ok((projects, config.ignore)) +/// 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 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"); + } + if part.eq_ignore_ascii_case(".git") { + return Some("the name .git"); + } + None +} + +/// 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('\\', "/"); + if unified.starts_with('/') { + 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 '{}' must not contain '..'", escape(raw))), + part => match component_problem(part) { + 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 '{}' must name a directory below the .meta file", + escape(raw) + )); + } + Ok(parts.join("/")) +} + +/// Resolve `rel` below `base_dir` through the symlinks that exist now, and +/// 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. +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('/') { + current.push(part); + if !exists { + continue; + } + match current.symlink_metadata() { + 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(_) => { + 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(_) => {} + } + } + if current == base { + return Err(format!( + "path '{rel}' leads to the directory of the .meta file itself" + )); + } + Ok(current) } /// 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(); }; @@ -266,16 +679,26 @@ 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(".")); + 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); - 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 +841,40 @@ 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); + // 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 - 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 +884,7 @@ fn walk_inner( } nodes.sort_by(|a, b| a.info.name.cmp(&b.info.name)); - nodes + Ok(nodes) } #[cfg(test)] @@ -558,16 +978,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 root #[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( dir.path().join(".meta"), @@ -580,14 +998,14 @@ 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("leads to the directory of the .meta file itself"), + "{err}" + ); + } } #[test] @@ -1030,32 +1448,504 @@ 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_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(); + parse_err_in(dir.path(), json) + } + + #[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"}}}"#, + "name: path '../../../../escaped-wt' must not contain '..'", + ), + ( + r#"{"projects": {"/abs": "u"}}"#, + "name: path '/abs' must be relative", + ), + (r#"{"projects": {"a//b": "u"}}"#, "plain relative path"), + ( + r#"{"projects": {"..": {"repo": "u", "path": "a"}}}"#, + "must not contain '..'", + ), + ( + 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}"); + } + } + + /// 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() { + // `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}" + ); + } + + #[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() { + // `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}" + ); + } + + #[cfg(unix)] // Windows refuses control characters in file names + #[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 [ + 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("ASCII letters"), "{json}: {err}"); + } + } + + #[test] + fn test_parse_rejects_names_and_paths_that_alias_or_mislead() { + 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": "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": "C:x"}}}"#, + "ASCII letters", + ), + ( + r#"{"projects": {"p": {"repo": "u", "path": "ab:c"}}}"#, + "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": {"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"}}}"#, + "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+z@w": "u", ".github": "u"}}"#, + ) + .unwrap(); + assert!(parse_meta_config(&dir.path().join(".meta")).is_ok()); + } + + #[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 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("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(); + 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_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"); + 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()); + #[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}"); + 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": {"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}"); + } + + #[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(); + 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] @@ -1177,11 +2067,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); } diff --git a/src/data_dir.rs b/src/data_dir.rs index 49900a1..3d0660d 100644 --- a/src/data_dir.rs +++ b/src/data_dir.rs @@ -4,19 +4,29 @@ //! 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) +} + +/// 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) } @@ -25,30 +35,369 @@ 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(private_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. +pub 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 {}", + crate::display::escape_path(dir) + ) + })?; + check_private_dir(dir) +} + +/// 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. +// 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 = + 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() { + // 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. + 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)] + { + 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}; + 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(()); + } + anyhow::bail!("Refusing to use {shown}: too many symlinks") +} + +/// 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 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), and every symlink +/// followed must belong to you or root. +#[cfg(unix)] +pub fn check_private_dir(dir: &Path) -> Result<()> { + use std::ffi::OsString; + use std::path::Component; + + let shown = crate::display::escape_path(dir); + // SAFETY: geteuid has no preconditions and cannot fail. + let uid = unsafe { libc::geteuid() }; + 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 = 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() { + 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() { + // 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)?; + 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){}", + crate::display::escape_path(¤t), + outside_namespace_note(&holder) + ); + } + if name == ".." { + current.pop(); + continue; + } + let next = current.join(&name); + let entry = stat(&next)?; + if entry.file_type().is_symlink() { + // In a sticky directory the link's owner can still replace it + 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), + outside_namespace_note(&entry) + ); + } + 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() || !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 !only_you_can_write(&meta, false) { + anyhow::bail!( + "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(()) +} + +#[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 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, sticky_ok: bool) -> bool { + use std::os::unix::fs::MetadataExt; + 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")] +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; + + 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() { + // 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(); + 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")))] +pub(crate) 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)] +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. 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 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, "change")? { + 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, "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(()) +} + +/// No ownership model to check on other platforms. +#[cfg(not(any(unix, windows)))] +pub fn check_private_dir(_dir: &Path) -> Result<()> { + Ok(()) +} + #[cfg(test)] mod tests { use super::*; #[test] fn test_data_file_path() { - std::env::set_var("META_DATA_DIR", "/tmp/test-meta"); - let path = data_file("worktree"); - assert_eq!(path, PathBuf::from("/tmp/test-meta/worktree.json")); + let tmp = tempfile::tempdir().unwrap(); + std::env::set_var("META_DATA_DIR", tmp.path()); + let path = data_file("worktree").unwrap(); + assert_eq!(path, tmp.path().join("worktree.json")); std::env::remove_var("META_DATA_DIR"); } @@ -58,6 +407,219 @@ 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_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 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}"); + + // `..` 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(); + } + + #[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}"); + + // 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}"); + + // 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::from_millis(500), + ) + .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}"); + + // 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"); + 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")] + #[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(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()); + + // 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)] + #[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..b957f58 --- /dev/null +++ b/src/display.rs @@ -0,0 +1,124 @@ +//! 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 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 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 (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 { + c.is_control() + || matches!( + c, + '\u{AD}' + | '\u{034F}' + | '\u{061C}' + | '\u{115F}'..='\u{1160}' + | '\u{180E}' + | '\u{200B}'..='\u{200C}' + | '\u{200E}'..='\u{200F}' + | '\u{2028}'..='\u{202E}' + | '\u{2060}'..='\u{206F}' + | '\u{3164}' + | '\u{FEFF}' + | '\u{FFA0}' + | '\u{FFF9}'..='\u{FFFB}' + | '\u{E0000}'..='\u{E007F}' + + ) +} + +/// 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 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() +} + +#[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"); + 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}" + ); + } + + #[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(_))); + assert!(matches!( + escape("\u{1f468}\u{200d}\u{1f467}"), + Cow::Borrowed(_) + )); + } + + #[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"); + } +} diff --git a/src/lib.rs b/src/lib.rs index 7dd3d65..407b1f8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,15 +2,19 @@ //! //! 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; +#[cfg(windows)] +mod win_acl; /// Default meta data directory name. const META_DIR_NAME: &str = ".meta"; @@ -20,13 +24,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..dd354e0 100644 --- a/src/lock.rs +++ b/src/lock.rs @@ -1,27 +1,30 @@ -//! 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. 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}; -use std::fs::{self, OpenOptions}; -use std::io::Write; +use std::fs::{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 +32,120 @@ impl LockGuard { } } -/// Acquire an exclusive lock at the given path. +/// Acquire an exclusive lock on `lock_path`, creating the file and its +/// directory if needed. /// -/// 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 -/// -/// 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()) - })?; - } + crate::data_dir::create_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 - ) - }); - } - } + // 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) + ); } - - 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() - .write(true) - .create_new(true) // O_CREAT | O_EXCL + 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)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600).custom_flags(libc::O_NOFOLLOW); + } + let file = options .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) + .with_context(|| format!("Failed to open lock file: {}", escape_path(lock_path)))?; + #[cfg(unix)] + { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let meta = file + .metadata() + .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 \ + (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) + ); + } + // 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)))?; + } } -} - -/// 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; + // 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) + ); } - - unsafe { - let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid); - if handle.is_null() { - false - } else { - CloseHandle(handle); - true + #[cfg(windows)] + { + 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) + ); } } -} -#[cfg(not(any(unix, windows)))] -fn is_process_alive(_pid: u32) -> bool { - // On other platforms, conservatively assume the process is alive - true + 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, + escape_path(lock_path) + ), + Err(TryLockError::Error(e)) => { + return Err(e).with_context(|| format!("Failed to lock {}", escape_path(lock_path))) + } + } + } } #[cfg(test)] mod tests { use super::*; + use std::fs; + + 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 + acquire(&lock_path, WAIT).unwrap(); } #[test] @@ -197,39 +153,61 @@ 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)); + // 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, WAIT).unwrap(); + } + } - // Write our own PID — should not be stale - fs::write(&lock_path, format!("{}\n", std::process::id())).unwrap(); - assert!(!is_stale(&lock_path)); + #[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_acquire_recovers_stale_lock() { + fn test_lock_file_is_private() { + use std::os::unix::fs::PermissionsExt; + let tmp = tempfile::tempdir().unwrap(); - let lock_path = tmp.path().join("stale.lock"); + 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); + } - // Create a stale lock (non-existent PID) - fs::write(&lock_path, "999999999\n").unwrap(); + #[test] + 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("x.lock"); + let _guard = acquire(&lock_path, WAIT).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..ffff944 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1,9 +1,10 @@ //! 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; use anyhow::{Context, Result}; use serde::de::DeserializeOwned; use serde::Serialize; @@ -11,47 +12,150 @@ 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() { - 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)?; 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. /// -/// 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 if let Some(parent) = path.parent() { if !parent.exists() { - std::fs::create_dir_all(parent) - .with_context(|| format!("Failed to create directory: {}", parent.display()))?; + crate::data_dir::create_private_dir(parent)?; } } - 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")?; - std::fs::write(&tmp_path, &json) - .with_context(|| format!("Failed to write temp file: {}", tmp_path.display()))?; + 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); + + // 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 +/// 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() }; + 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 {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() + ); + } + 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(()) +} - std::fs::rename(&tmp_path, path) - .with_context(|| format!("Failed to rename temp file to: {}", path.display()))?; +/// 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)))?; + if !meta.is_file() { + anyhow::bail!( + "Refusing to read {}: it is not a regular file", + escape_path(path) + ); + } Ok(()) } @@ -69,7 +173,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); @@ -112,7 +216,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] @@ -149,7 +253,31 @@ 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::from_millis(500)).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] diff --git a/src/win_acl.rs b/src/win_acl.rs new file mode 100644 index 0000000..c1347b0 --- /dev/null +++ b/src/win_acl.rs @@ -0,0 +1,187 @@ +//! 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_OBJECT_ACE_TYPE: u8 = 5; +const ACCESS_ALLOWED_CALLBACK_ACE_TYPE: u8 = 9; +const ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE: u8 = 11; +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; +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; +const GENERIC_READ: u32 = 0x8000_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; + +/// 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", + "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 `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, 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 + // 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 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, + } + // 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_mut!((*allowed).SidStart).cast())?; + if !trusted(&sid) { + return Ok(Some(format!("{sid} may {verb} 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) +}