Validate paths and safe traversal
Validate paths and safe traversal
Validate untrusted logical names before mapping them to native paths. fs.ValidPath rejects empty names, rooted names and dot or dot-dot components (except the root name .). filepath.Localize (Go 1.23) converts valid logical names to representable local paths. These are lexical checks, not a sandbox. Use the examples only on a private, trusted temporary tree.
package main
import ( "fmt" "io/fs" "path/filepath")
func main() { for _, name := range []string{"docs/a.txt", "../a.txt", "/a.txt", ".", "a//b"} { p, e := filepath.Localize(name) fmt.Println(name, fs.ValidPath(name), e == nil && filepath.IsLocal(p)) }}ValidPath alone does not reject backslashes or colons; native representability depends on the OS. Localize checks that conversion. A file-only policy should also reject the root name . and apply application-specific name restrictions. IsLocal and Clean do not account for symlinks. Even a check with EvalSymlinks can race with subsequent use. For hostile writable trees use a separately reviewed OS-backed containment mechanism; Go 1.23 examples here do not implement one.
Expected output:
docs/a.txt true true../a.txt false false/a.txt false false. true truea//b false falseWalk a trusted tree
package main
import ( "fmt" "io/fs" "os" "path/filepath")
func check(err error) { if err != nil { panic(err) }}func lab() (string, func()) { d, err := os.MkdirTemp("", "bytemind-") check(err) return d, func() { check(os.RemoveAll(d)) }}
func main() { d, cleanup := lab() defer cleanup() check(os.Mkdir(filepath.Join(d, "sub"), 0700)) check(os.WriteFile(filepath.Join(d, "sub", "a.txt"), nil, 0600)) e := fs.WalkDir(os.DirFS(d), ".", func(name string, entry fs.DirEntry, err error) error { if err != nil { return err } if !entry.IsDir() && entry.Type().IsRegular() { fmt.Println(name) } return nil }) check(e)}WalkDir visits entries in lexical order and does not follow symlinks encountered during traversal. The callback receives errors; handle them before accessing the entry. Here it lists regular entries, not their contents. A tree can change between traversal and opening; do not turn this listing into an authorization check.
Expected output:
sub/a.txtTry it locally
For the names "a.txt", "../a", "." print whether they pass a lexical file-name policy: valid fs path, not root and successfully localized.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Files and paths 07: Validate paths and safe traversal
Check the lesson objective before moving on.
Which operation alone guarantees confinement against hostile symlinks?
When should a WalkDir callback inspect its entry?