Confine File Access With os.Root
os.Root scopes every lookup to one directory: paths that climb out with .. are rejected outright while normal reads and writes keep working.
Code
package main
import (
"fmt"
"os"
)
func main() {
dir, err := os.MkdirTemp("", "rootdemo")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir) // LIFO:先 root.Close 再删目录,Windows 上才不会失败
// os.Root(Go 1.24+):之后的每次打开都被限制在这个根目录内
root, err := os.OpenRoot(dir)
if err != nil {
panic(err)
}
defer root.Close()
f, err := root.Create("notes.txt")
if err != nil {
panic(err)
}
if _, err := f.WriteString("confined\n"); err != nil {
panic(err)
}
f.Close()
data, err := root.ReadFile("notes.txt")
if err != nil {
panic(err)
}
fmt.Print("inside root: ", string(data))
// ../ 向上穿越被直接拒绝,不会真正触碰根目录之外的文件
if _, err := root.ReadFile("../outside.txt"); err != nil {
fmt.Println("traversal blocked:", err != nil)
}
}How the snippet works
Confine File Access With os.Root is built around the function main.
Every err != nil branch (6 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.
What to watch for
- Adapting this to library code usually means replacing the
panic(err)calls with error returns the caller can branch on.
Using it
Output lines are prefixed (inside root:, traversal blocked:), so each output line names the operation behind it.
Key statements
if err != nil {
panic(err)
}
defer os.RemoveAll(dir) // LIFO:先 root.Close 再删目录,Windows 上才不会失败
defer root.Close()
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- What is the error handling style?
- The failure path is `panic(err)` — detected problems halt the run rather than being passed back.
- What does Confine File Access With os.Root print when run?
- Run it as a complete program — the output lines carry labels such as `inside root:`, `traversal blocked:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.