pub fn safe_join(base: &Path, path: &str) -> Result<PathBuf>Expand description
Safely joins a base path with a relative path, preventing directory traversal.
This function securely combines a base directory with a relative path while preventing directory traversal attacks. It validates the input path and ensures the result stays within the base directory.
§Arguments
base- The base directory that should contain the resultpath- The relative path to join (validated for safety)
§Returns
The joined path with proper platform-specific handling, or an error if:
- The path contains invalid characters
- The path would escape the base directory
- Platform-specific validation fails
§Examples
use agpm_cli::utils::platform::safe_join;
use std::path::Path;
let base = Path::new("/home/user/project");
// Safe joins
let file_path = safe_join(base, "src/main.rs")?;
let nested_path = safe_join(base, "docs/guide/intro.md")?;
// These would fail (directory traversal)
// safe_join(base, "../../../etc/passwd").unwrap_err();
// safe_join(base, "/absolute/path").unwrap_err();§Security Features
- Path traversal prevention: Detects and blocks
../escape attempts - Character validation: Ensures valid characters for the platform
- Normalization: Resolves
.and..components before validation - Platform handling: Applies Windows long path support when needed
§Validation Performed
- Character validation: Checks for platform-invalid characters
- Traversal detection: Identifies attempts to escape base directory
- Path normalization: Resolves relative components
- Boundary checking: Ensures result stays within base
§Error Cases
- Path contains invalid characters (platform-specific)
- Path traversal attempt detected (
../../../etc/passwd) - Path would resolve outside the base directory
- Windows reserved names used in path components
§Use Cases
- Processing user-provided relative paths
- Extracting archive files safely
- Configuration file path resolution
- API endpoints that accept file paths
§Platform Behavior
- Windows: Handles long paths, validates reserved names
- Unix-like: Allows most characters, prevents null bytes
- All platforms: Prevents directory traversal attacks
§See Also
validate_path_charsfor character validation detailswindows_long_pathfor Windows path handlingis_safe_pathfor path safety checking