Implement multiple validation layers to prevent path traversal attacks. File paths provided by users or external systems must be validated before use in filesystem operations:
Implement multiple validation layers to prevent path traversal attacks. File paths provided by users or external systems must be validated before use in filesystem operations:
// First validate with fs.ValidPath
if !fs.ValidPath(fp) {
return nil, fmt.Errorf("%w: %s", errFilePath, fp)
}
// Then use filepath.Clean to normalize
fp = filepath.Clean(fp)
// Finally validate containment with os.Root
root, err := os.OpenRoot(safeDirectory)
if err != nil {
return nil, err
}
defer root.Close()
// All file operations should go through this root
Enter the URL of a public GitHub repository