fs ValidPath Validates FS Paths

Validate path shape with fs.ValidPath before any fs.FS read, rejecting absolute paths, dot segments, and empty elements at the gate.

GoSecurity Boundaries

Code

snippet
package main

import (
	"fmt"
	"io/fs"
	"os"
)

func readUnder(root fs.FS, name string) (string, error) {
	// fs.FS 只接受 ValidPath 形状:非绝对、不含 . 与 ..、无空段
	if !fs.ValidPath(name) {
		return "", fmt.Errorf("invalid fs path: %q", name)
	}
	return fs.ReadFile(root, name)
}

func main() {
	root := os.DirFS(".")

	for _, name := range []string{"go.mod", "/etc/passwd", "../secrets.txt"} {
		data, err := readUnder(root, name)
		if err != nil {
			fmt.Println(name, "-> rejected:", err)
			continue
		}
		fmt.Println(name, "->", len(data), "bytes")
	}
}

How this snippet works

All of the logic lives in the functions readUnder and main.

Iteration happens inside for _, name := range []string{"go.mod", "/etc/passwd", "../secrets.txt"} — everything outside it runs once. Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly.

Caveats

  • No installation is involved: the snippet works within the standard library.
  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Applying it

The main signature reads func readUnder(root fs.FS, name string) (string, error)

Running the file executes main, which drives readUnder in order.

Statements that matter

return "", fmt.Errorf("invalid fs path: %q", name)
for _, name := range []string{"go.mod", "/etc/passwd", "../secrets.txt"} {
	data, err := readUnder(root, name)
	if err != nil {
		fmt.Println(name, "-> rejected:", err)
		continue
	}
	fmt.Println(name, "->", len(data), "bytes")
}
return fs.ReadFile(root, name)

Interactive Tools for This Topic

FAQ

How are errors reported?
The Go way: `err` comes back from each call, and 1 checkpoint here test it before proceeding.
How do you run fs ValidPath Validates FS Paths?
It runs as-is — treat the file as the whole program and execute it.