FS Sub Mounts Subtree Root

Mount one directory of an fs.FS as its own root with fs.Sub, read files through the narrowed view, and confirm parent paths are refused.

GoSecurity Boundaries

Code

gosnippet
40 lines
package main

import (
	"fmt"
	"io/fs"
	"testing/fstest"
)

func main() {
	files := fstest.MapFS{
		"config/app.yaml":  &fstest.MapFile{Data: []byte("name: demo\n")},
		"config/ports.txt": &fstest.MapFile{Data: []byte("8080\n")},
		"README.md":        &fstest.MapFile{Data: []byte("# demo\n")},
	}

	// fs.Sub exposes config as the subtree root of the view
	sub, err := fs.Sub(files, "config")
	if err != nil {
		fmt.Println("sub failed:", err)
		return
	}
	data, err := fs.ReadFile(sub, "app.yaml")
	if err != nil {
		fmt.Println("read failed:", err)
		return
	}
	fmt.Print("app.yaml: ", string(data))

	entries, err := fs.ReadDir(sub, ".")
	if err != nil {
		fmt.Println("read dir failed:", err)
		return
	}
	for _, entry := range entries {
		fmt.Println("entry:", entry.Name())
	}

	_, err = fs.ReadFile(sub, "../README.md")
	fmt.Println("escape blocked:", err != nil)
}

The code, statement by statement

FS Sub Mounts Subtree Root comes down to the function main.

A single loop drives the file — for _, entry := range entries. Error handling is inline: 3 places test err != nil and branch immediately.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: func main()

Running the file prints labeled results such as sub failed:, read failed:, app.yaml: — each operation’s effect is visible in the output.

Key statements

for _, entry := range entries {
fmt.Println("entry:", entry.Name())
}
if err != nil {
fmt.Println("sub failed:", err)
return
}
if err != nil {
fmt.Println("read failed:", err)
return
}

Interactive Tools for This Topic

FAQ

What does FS Sub Mounts Subtree Root print when run?
The script runs standalone; its 6 labeled outputs include `sub failed:`, `read failed:`, `app.yaml:`.