| Crates.io | soft-canonicalize |
| lib.rs | soft-canonicalize |
| version | 0.5.4 |
| created_at | 2025-07-18 12:43:29.631991+00 |
| updated_at | 2026-01-19 08:45:29.670442+00 |
| description | Path canonicalization that works with non-existing paths. |
| homepage | https://github.com/DK26/soft-canonicalize-rs |
| repository | https://github.com/DK26/soft-canonicalize-rs |
| max_upload_size | |
| id | 1758927 |
| size | 1,157,452 |
Path canonicalization that works with non-existing paths.
Rust implementation inspired by Python 3.6+ pathlib.Path.resolve(strict=False), providing the same functionality as std::fs::canonicalize (Rust's equivalent to Unix realpath()) but extended to handle non-existing paths, with optional features for simplified Windows output (dunce) and virtual filesystem semantics (anchored).
🚀 Works with non-existing paths - Plan file locations before creating them
⚡ Fast - Mixed workload median performance: Windows ~1.8x (13,840 paths/s), Linux ~3.0x (379,119 paths/s) faster than Python's pathlib (see benchmark methodology for 5-run protocol and environment details)
✅ Compatible - 100% behavioral match with std::fs::canonicalize for existing paths, with optional UNC simplification via dunce feature (Windows)
🎯 Virtual filesystem support - Optional anchored feature for bounded canonicalization within directory boundaries
🔒 Robust - 500+ comprehensive tests including symlink cycle protection, malicious stream validation, and edge case handling
🛡️ Safe traversal - Proper .. and symlink resolution with cycle detection
🌍 Cross-platform - Windows, macOS, Linux with comprehensive UNC/symlink handling
🔧 Zero dependencies - Optional features may add minimal dependencies
Path resolution libraries fall into two categories:
Lexical Resolution (no I/O):
std::path::absolute, normpath::normalizeFilesystem-Based Resolution (performs I/O):
std::fs::canonicalize, soft_canonicalize, dunce::canonicalizeRule of thumb: If you cannot guarantee symlinks won't be introduced, or if correctness is critical, use filesystem-based resolution.
[dependencies]
soft-canonicalize = "0.5"
use soft_canonicalize::soft_canonicalize;
let non_existing_path = r"C:\Users\user\documents\..\non\existing\config.json";
// Using Rust's own std canonicalize function:
let result = std::fs::canonicalize(non_existing_path);
assert!(result.is_err());
// Using our crate's function:
let result = soft_canonicalize(non_existing_path);
assert!(result.is_ok());
// Shows the UNC path conversion and path normalization
assert_eq!(
result.unwrap().to_string_lossy(),
r"\\?\C:\Users\user\non\existing\config.json"
);
// With `dunce` feature enabled, paths are simplified when safe
// assert_eq!(
// result.unwrap().to_string_lossy(),
// r"C:\Users\user\non\existing\config.json"
// );
anchored - Virtual filesystem/bounded canonicalization (cross-platform)dunce - Simplified Windows path output (Windows-only target-conditional dependency)anchored feature)For correct symlink resolution within virtual/constrained directory spaces, use anchored_canonicalize. This function implements true virtual filesystem semantics by clamping ALL paths (including absolute symlink targets) to the anchor directory:
[dependencies]
soft-canonicalize = { version = "0.5", features = ["anchored"] }
use soft_canonicalize::anchored_canonicalize;
use std::fs;
// Set up an anchor/root directory (no need to pre-canonicalize)
let anchor = std::env::temp_dir().join("workspace_root");
fs::create_dir_all(&anchor)?;
// Canonicalize paths relative to the anchor (anchor is soft-canonicalized internally)
let resolved_path = anchored_canonicalize(&anchor, "../../../etc/passwd")?;
// Result: /tmp/workspace_root/etc/passwd (lexical .. clamped to anchor)
// Absolute symlinks are also clamped to the anchor
// If there's a symlink: workspace_root/config -> /etc/config
// It resolves to: workspace_root/etc/config (clamped to anchor)
let symlink_path = anchored_canonicalize(&anchor, "config")?;
// Safe: always stays within workspace_root, even if symlink points to /etc/config
Key features of anchored_canonicalize:
For a complete multi-tenant security example, see:
cargo run --example virtual_filesystem_demo --features anchored
dunce feature, Windows-only)By default on Windows, soft_canonicalize returns paths in extended-length UNC format (\\?\C:\foo) for maximum robustness and compatibility with long paths, reserved names, and other Windows filesystem edge cases.
If you need simplified paths (C:\foo) for compatibility with legacy Windows applications or user-facing output, enable the dunce feature:
[dependencies]
soft-canonicalize = { version = "0.5", features = ["dunce"] }
Example:
use soft_canonicalize::soft_canonicalize;
let path = soft_canonicalize(r"C:\Users\user\documents\..\config.json")?;
// Without dunce feature (default):
// Returns: \\?\C:\Users\user\config.json (extended-length UNC)
// With dunce feature enabled:
// Returns: C:\Users\user\config.json (simplified when safe)
When to use:
How it works:
The dunce crate intelligently simplifies Windows UNC paths (\\?\C:\foo → C:\foo) only when safe:
.. (literal interpretation)proc-canonicalizeSince v0.5.0, soft_canonicalize uses proc-canonicalize by default for existing-path canonicalization instead of std::fs::canonicalize. This fixes a critical issue with Linux namespace boundaries.
std::fs::canonicalizeOn Linux, std::fs::canonicalize resolves "magic symlinks" like /proc/PID/root to their targets:
// std::fs::canonicalize follows magic symlinks incorrectly
let path = std::fs::canonicalize("/proc/1/root")?; // Returns "/" (wrong!)
// This loses the namespace boundary - dangerous for container tooling
proc-canonicalize preserves namespace boundaries:
use proc_canonicalize::canonicalize;
let path = canonicalize("/proc/1/root")?; // Returns "/proc/1/root" (correct!)
// Namespace boundary is preserved
| Use Case | Function | Reason |
|---|---|---|
| Paths that may not exist | soft_canonicalize |
Handles non-existing paths |
| Existing paths (general) | proc_canonicalize::canonicalize |
Correct namespace handling |
| Existing paths (std behavior) | std::fs::canonicalize |
Legacy compatibility only |
Recommendation: If you need to canonicalize paths that must exist (and would previously use std::fs::canonicalize), use proc_canonicalize::canonicalize for correct Linux namespace handling:
[dependencies]
proc-canonicalize = "0.0"
| Feature | soft_canonicalize |
proc_canonicalize |
std::fs::canonicalize |
std::path::absolute |
dunce::canonicalize |
|---|---|---|---|---|---|
| Resolution type | Filesystem-based | Filesystem-based | Filesystem-based | Lexical | Filesystem-based |
| Works with non-existing paths | ✅ | ❌ | ❌ | ✅ | ❌ |
| Resolves symlinks | ✅ | ✅ | ✅ | ❌ | ✅ |
| Preserves Linux namespaces | ✅ (default) | ✅ | ❌ | N/A | ❌ |
| Simplified Windows paths | ✅ (opt-in dunce feature) |
✅ (opt-in) | ❌ (UNC) | ❌ (varies) | ✅ |
| Virtual/bounded canonicalization | ✅ (opt-in anchored feature) |
❌ | ❌ | ❌ | ❌ |
| Zero dependencies | ✅ (default) | ✅ | ✅ | ✅ | ✅ |
Choose soft_canonicalize when:
std::fs::canonicalize behavior for paths that don't exist yetanchored feature)dunce feature)Choose alternatives when:
proc_canonicalize::canonicalize - All paths exist and you need correct Linux namespace handling (recommended over std::fs::canonicalize)std::fs::canonicalize - All paths exist; only when you specifically need the legacy behavior that resolves /proc/PID/root to /std::path::absolute - You only need absolute paths without symlink resolution (lexical, fast)dunce::canonicalize - Windows-only, all paths exist, just need UNC simplificationnormpath::normalize - Lexical normalization only, no filesystem I/O (fast but doesn't resolve symlinks)path_absolutize - Absolute path resolution without symlink following, with CWD caching optimizationssoft-canonicalize internally for path validation and boundary enforcement.Security does not depend on enabling features. The core API is secure-by-default; the optional anchored feature is a convenience for virtual roots. We test all modes (no features; --features anchored; --features anchored,dunce).
Built-in protections include:
See docs/SECURITY.md for detailed analysis, attack scenarios, and test references.
On Windows, the filesystem may generate short filenames (8.3 format) for long directory names. For non-existing paths, this library cannot determine if a short filename form (e.g., PROGRA~1) and its corresponding long form (e.g., Program Files) refer to the same future location:
use soft_canonicalize::soft_canonicalize;
// These non-existing paths are treated as different (correctly)
let short_form = soft_canonicalize("C:/PROGRA~1/MyApp/config.json")?;
let long_form = soft_canonicalize("C:/Program Files/MyApp/config.json")?;
// They will NOT be equal because we cannot determine equivalence
// without filesystem existence
assert_ne!(short_form, long_form);
This is a fundamental limitation shared by Python's pathlib.Path.resolve(strict=False) and other path canonicalization libraries across languages. Short filename mapping only exists when files/directories are actually created by the filesystem.
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
Licensed under either of:
See CHANGELOG.md for a detailed history of changes.