Crate proc_canonicalize

Crate proc_canonicalize 

Source
Expand description

§proc-canonicalize

A patch for std::fs::canonicalize that preserves Linux /proc/PID/root and /proc/PID/cwd namespace boundaries.

§The Problem

On Linux, /proc/PID/root is a “magic symlink” that crosses into a process’s mount namespace. However, std::fs::canonicalize resolves it to /, losing the namespace context:

// The kernel resolves /proc/self/root to "/" - losing the namespace boundary!
let resolved = std::fs::canonicalize("/proc/self/root")?;
assert_eq!(resolved, std::path::PathBuf::from("/"));

This breaks security tools that use /proc/PID/root as a boundary for container filesystem access, because the boundary resolves to the host root!

§The Fix

This crate detects /proc/PID/root and /proc/PID/cwd prefixes and preserves them:

use std::path::PathBuf;

// The namespace boundary is preserved!
let resolved = proc_canonicalize::canonicalize("/proc/self/root")?;
assert_eq!(resolved, PathBuf::from("/proc/self/root"));

// Paths through the boundary also preserve the prefix
let resolved = proc_canonicalize::canonicalize("/proc/self/root/etc")?;
assert!(resolved.starts_with("/proc/self/root"));

For all other paths, behavior is identical to std::fs::canonicalize:

// Normal paths behave exactly like std::fs::canonicalize
let std_result = std::fs::canonicalize(".")?;
let our_result = proc_canonicalize::canonicalize(".")?;
// Note: On Windows with the `dunce` feature, our result may differ
// (simplified path without \\?\ prefix). See unit tests for full coverage.
#[cfg(not(windows))]
assert_eq!(std_result, our_result);
#[cfg(windows)]
let _ = (std_result, our_result); // Use variables to avoid warnings

§Platform Support

  • Linux: Full functionality - preserves /proc/PID/root and /proc/PID/cwd
  • Other platforms: Falls back to std::fs::canonicalize (no-op)

§Zero Dependencies

This crate has no dependencies beyond the Rust standard library.

§Optional Features

  • dunce (Windows only): Simplifies Windows extended-length paths by removing the \\?\ prefix when possible (e.g., \\?\C:\foo becomes C:\foo). Automatically preserves the prefix when needed (e.g., for paths longer than 260 characters). Enable with features = ["dunce"].

Functions§

canonicalize
Canonicalize a path, preserving Linux /proc/PID/root and /proc/PID/cwd boundaries.