diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 7a1e8a8..c3510ec 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,15 +6,19 @@ on: pull_request: branches: ["master"] + permissions: read-all jobs: ci: + permissions: + contents: read + id-token: write # Reusable CI lives in 1set/meta — the single source of truth for every # Star* module's pipeline. Pinned to a commit SHA for supply-chain safety; # bump the pin when meta's workflow changes (Dependabot github-actions can # automate this). - uses: 1set/meta/.github/workflows/go-ci.yml@5d86667e7264f012655dab2644dfa44e09597445 + uses: 1set/meta/.github/workflows/go-ci.yml@496f38088eff1a37bae1b43d158146a8a9d83a37 with: go-floor: "1.19" doc-coverage: true diff --git a/CLAUDE.md b/CLAUDE.md index 5fcfc67..de5688e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -99,7 +99,11 @@ back. Every script-visible thing is a Go struct exposed through a thin `fs.ValidPath` (the barrier that confines traversal, also satisfies CodeQL's path-injection query) + dotfile/`@eaDir` rejection (`.well-known` carve-out) + an `EvalSymlinks` real-path check (`openWithin`) that blocks symlink escape. - Mount registry is copy-on-write so the serve path reads it lock-free. Tests in + Mount roots must exist and be beneath the server's captured working directory + unless the host enables `allow_unsafe_file_paths`. Registration resolves and + copies each root; later cwd changes or symlink retargeting cannot select a + different root. Mount registry is copy-on-write so the serve path reads it + lock-free. Tests in `static_test.go` (source-shaped). - **`errors.go`** — `ErrorResponse`, `ErrorHandlerRegistry` (status code → Starlark handler), invoked from `applyResponse`/`NoRoute`/`NoMethod`. @@ -109,7 +113,8 @@ back. Every script-visible thing is a Go struct exposed through a thin ## Invariants / hardening (preserve when editing) -The iron rule is **opt-in / default-off so old scripts run identically**. +Preserve documented defaults; security boundary corrections must explicitly +document their behavior changes. 1. **Default-deny public bind.** `create_server` defaults `host` to `localhost`; `Start()`/`Run()` call `checkBindAllowed`, which refuses any non-loopback @@ -133,8 +138,10 @@ The iron rule is **opt-in / default-off so old scripts run identically**. into `bodyData` so `body()`/`json()`/`form()`/middleware can all read it; `form()` re-wraps the cached bytes. Don't re-read `c.Request.Body` directly. 6. **Backward compatibility.** `NewModule()` keeps every historical default - (localhost bind allowed, public bind denied, 32 MiB body cap). Any new safety - lever must default to the historical behavior. + (localhost bind allowed, public bind denied, 32 MiB body cap). File responses + and static mounts share a fixed host root captured at server + creation. Outside static roots now require the existing host-only + `allow_unsafe_file_paths` opt-out; missing roots must be created before mounting. ## Test organization diff --git a/README.md b/README.md index 9dc11a3..6894b10 100644 --- a/README.md +++ b/README.md @@ -87,10 +87,10 @@ Module builtins (`load("web", …)`): - `json_response(data, status?, headers?)` — JSON response. - `html_response(content, status?, headers?)` — HTML response. - `text_response(text, status?)` — plain-text response. -- `file_response(filepath, content_type?, filename?)` — serve a file (optionally as a download). Confined to the working directory by default; set `allow_unsafe_file_paths` to serve outside it. +- `file_response(filepath, content_type?, filename?)` — serve a file (optionally as a download). Confined to the working directory captured when the server is created; set `allow_unsafe_file_paths` to serve outside it. - `send_file(filepath, content_type?)` — serve a file (same working-directory confinement as `file_response`). - `send_data(data, filename, content_type?)` — send in-memory data as a download. -- `static_dir(root, index?, spa?, cache_control?)` — read-only static-file root for `srv.static` (safe by default: no traversal/dotfiles/listing). +- `static_dir(root, index?, spa?, cache_control?)` — read-only static-file root for `srv.static`; mounts require an existing directory under the server's captured working directory by default (no traversal/dotfiles/listing). - `redirect(location, status?)` — redirect response. - `error_response(status, message?)` — error response. - `api_key_auth(keys?, header?, query_param?)` — API-key authenticator. @@ -130,7 +130,10 @@ The module's options (`host`, `port`, `read_timeout`, `write_timeout`, per-option `get_` / `set_` accessor builtins, and serve as defaults for the servers the module creates. Two opt-in levers default to off: `allow_public_bind` lets the host expose a server beyond loopback, and `allow_unsafe_file_paths` lets -`file_response`/`send_file` serve files outside the working directory. Both +file responses and static mounts use paths outside the server's captured working +directory. Relative file responses remain anchored there even if the process +changes directory later. Static mounts bind to a resolved directory at mount +time; changing its original symlink alias cannot redirect the mount. Both `allow_unsafe_file_paths` and `max_body_size` are **host-only** (no `set_` builtin) — an untrusted script cannot weaken these safety guards; set them via Go config or `WEB_*`. See the diff --git a/codecov.yml b/codecov.yml new file mode 100644 index 0000000..2f7efae --- /dev/null +++ b/codecov.yml @@ -0,0 +1,14 @@ +coverage: + status: + project: + default: + target: auto + threshold: 0% + patch: + default: + target: 100% + threshold: 0% +comment: + layout: "diff, flags, files" + require_changes: false + hide_project_coverage: false diff --git a/docs/API.md b/docs/API.md index 92867aa..106a413 100644 --- a/docs/API.md +++ b/docs/API.md @@ -240,7 +240,10 @@ and `Content-Type` by extension all work without the script handling them; an **Parameters:** -- `root` (string): The directory to serve. Must not be empty. +- `root` (string): The directory to serve. Must not be empty. At mount time it + must exist and resolve to a directory under the working directory captured + when the server was created. The host-only `allow_unsafe_file_paths` option + permits an outside root; it does not disable confinement within that mount. - `index` (string or list of strings, optional): Directory default pages, tried in order (default: `["index.html", "index.htm"]`). An empty list disables index pages (directories then 404). @@ -252,7 +255,10 @@ and `Content-Type` by extension all work without the script handling them; an **Returns:** A `web.StaticDir` handle (pass it to `srv.static`). -**Safety (always on, no opt-out):** +The mount is bound to the resolved physical root at registration. Later cwd +changes or retargeting of the supplied symlink alias do not select a new root. + +**Safety within an accepted mount (always on, no opt-out):** - **No path traversal.** The request path is cleaned and anchored under `root`; `..` can never escape, and the resolved path is re-checked against the @@ -644,7 +650,8 @@ explicit route registered on the server takes precedence. A request under - `prefix` (string): URL prefix to mount under (`/` serves the whole site). - `dir` (`web.StaticDir`): the handle returned by `static_dir(...)`. -- **Returns:** `None`. +- **Returns:** `None`. A missing, non-directory or unauthorized root raises an + error without registering the mount. Create the directory before mounting. ```python srv.static("/assets", static_dir("./public/assets", cache_control="max-age=3600")) @@ -898,6 +905,11 @@ lives in the sandbox runtime layer; this is the module-local guardrail. ## Configuration +The server captures the physical working directory at creation. Confined +`file_response`, `send_file`, direct `file_path` assignments and custom error +responses resolve relative paths against that fixed root. Changing cwd later +does not widen this boundary. + Each module configuration option is exposed to scripts as a pair of generated accessor builtins (loaded from the `web` module alongside the functions above): @@ -932,7 +944,7 @@ them from Go configuration or the corresponding `WEB_*` environment variable. | `debug_mode` | `get_debug_mode` | `set_debug_mode` | bool | `WEB_DEBUG_MODE` | `false` | Enable Gin debug logging | | `server_header` | `get_server_header` | `set_server_header` | string | `WEB_SERVER_HEADER` | `Starlark-Web/1.0` | Custom `Server` header value | | `allow_public_bind` | `get_allow_public_bind` | `set_allow_public_bind` | bool | `WEB_ALLOW_PUBLIC_BIND` | `false` | Allow binding to a non-loopback (public) address | -| `allow_unsafe_file_paths` | `get_allow_unsafe_file_paths` | _(host-only)_ | bool | `WEB_ALLOW_UNSAFE_FILE_PATHS` | `false` | Allow `file_response`/`send_file` to serve paths outside the working directory | +| `allow_unsafe_file_paths` | `get_allow_unsafe_file_paths` | _(host-only)_ | bool | `WEB_ALLOW_UNSAFE_FILE_PATHS` | `false` | Allow file responses and static mounts outside the server's captured working directory | **Example:** diff --git a/server.go b/server.go index ce39667..e2118e7 100644 --- a/server.go +++ b/server.go @@ -54,7 +54,8 @@ type Server struct { maxBodySize int64 serverHeader string allowPublicBind bool // When false, refuse to bind to a non-loopback address - allowUnsafeFilePaths bool // When false, confine file_response/send_file to the working directory + allowUnsafeFilePaths bool // Host opt-out from the fileRoot boundary + fileRoot string // Physical working directory captured at server creation; empty denies file access middleware []*Middleware // All middleware with path patterns errorHandlers *ErrorHandlerRegistry ginMiddlewareAdded bool // Flag to prevent multiple Gin middleware additions @@ -78,6 +79,7 @@ func newServer(module *Module, host string, port int) *Server { serverHeader := module.ext.GetString(configKeyServerHeader) allowPublicBind := module.ext.GetBool(configKeyAllowPublicBind) allowUnsafeFilePaths := module.ext.GetBool(configKeyAllowUnsafeFilePaths) + fileRoot, _ := workingDirReal() // Set gin mode - ensure release mode by default to avoid debug output if debugMode { @@ -114,6 +116,7 @@ func newServer(module *Module, host string, port int) *Server { serverHeader: serverHeader, allowPublicBind: allowPublicBind, allowUnsafeFilePaths: allowUnsafeFilePaths, + fileRoot: fileRoot, middleware: make([]*Middleware, 0), errorHandlers: NewErrorHandlerRegistry(), ginMiddlewareAdded: false, @@ -498,14 +501,11 @@ func (s *Server) applyResponse(c *gin.Context, response *Response) { // serveConfinedFile serves a path a script asked to return (via file_response / // send_file / a directly-set Response.file_path). Unless allow_unsafe_file_paths -// is set, it opens the file first and then validates the open descriptor: it -// must be a regular file — never a directory, which http.ServeFile would turn -// into an index page or listing, nor a FIFO/device that could block — whose real -// path stays under the process working directory. It is then served from that -// same descriptor, which narrows the check-to-serve TOCTOU window and stops an -// untrusted script from reading arbitrary host files or echoing a request -// parameter straight into a file read. (Static mounts have their own confinement -// in static.go.) Returns true when it wrote a response. +// is set, it resolves and checks the path before opening: only regular files +// under the physical working directory captured at server creation are allowed. +// Directories and special files are rejected, and the opened descriptor is used +// for serving. Static mounts use the same host root in static.go. Returns true +// when it wrote a response. func (s *Server) serveConfinedFile(c *gin.Context, p string) bool { if s.allowUnsafeFilePaths { c.File(p) // opt-out: unrestricted serving (historical behavior) @@ -531,24 +531,22 @@ func (s *Server) serveConfinedFile(c *gin.Context, p string) bool { } // resolveConfinedFile resolves p to a symlink-free physical path, confirms it is -// a regular file under the working directory, and returns it. Resolving and -// checking BEFORE any open means an outside target is never opened — so a +// a regular file under the server's captured working directory, and returns it. +// Resolving and checking BEFORE any open means an outside target is never opened — so a // FIFO/device outside the root cannot block os.Open — and a directory (which // http.ServeFile would list) is rejected. func (s *Server) resolveConfinedFile(p string) (string, bool) { - if strings.TrimSpace(p) == "" { + if strings.TrimSpace(p) == "" || s.fileRoot == "" { return "", false } - abs, err := filepath.Abs(p) - if err != nil { - return "", false + if !filepath.IsAbs(p) { + p = filepath.Join(s.fileRoot, p) } - real, err := filepath.EvalSymlinks(abs) + real, err := filepath.EvalSymlinks(p) if err != nil { return "", false } - realRoot, ok := workingDirReal() - if !ok || !withinRoot(realRoot, real) { + if !withinRoot(s.fileRoot, real) { return "", false } // real is symlink-free, so Lstat == Stat: reject a directory or FIFO/device. @@ -559,15 +557,12 @@ func (s *Server) resolveConfinedFile(p string) (string, bool) { } // workingDirReal returns the symlink-resolved process working directory. -func workingDirReal() (string, bool) { +func workingDirReal() (string, error) { root, err := os.Getwd() if err != nil { - return "", false - } - if rr, err := filepath.EvalSymlinks(root); err == nil { - return rr, true + return "", err } - return root, true + return filepath.EvalSymlinks(root) } // Server lifecycle methods diff --git a/server_test.go b/server_test.go index fabca98..e2e1691 100644 --- a/server_test.go +++ b/server_test.go @@ -10,6 +10,7 @@ package web // - server builtin arg validation: route / error_handler / use_for / group errors // - lifecycle errors: stop()/double-start guards // - wrapHandler + applyResponse: request->handler->response bridge via httptest +// - file responses: complete entrypoint contract and fixed host root import ( "net" @@ -658,3 +659,100 @@ def handler(req): t.Errorf("body = %q, want the custom error handler body", rec.Body.String()) } } + +// TestServerFileRootSnapshot exercises the complete response path after cwd +// changes, including a file returned by a custom error handler. +func TestServerFileRootSnapshot(t *testing.T) { + root, outside := t.TempDir(), t.TempDir() + for dir, content := range map[string]string{root: "inside", outside: "outside"} { + if err := os.WriteFile(filepath.Join(dir, "probe.txt"), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + useWorkingDir(t, root) + t.Setenv("WEB_ALLOW_UNSAFE_FILE_PATHS", "false") + m := NewModule() + srv := newServer(m, "localhost", 0) + if err := os.Chdir(outside); err != nil { + t.Fatal(err) + } + if err := srv.RegisterStatic("/", staticDirFor(outside, false)); err == nil { + t.Error("cwd change widened static root authorization") + } + paths := []string{"probe.txt", filepath.Join(root, "probe.txt"), filepath.Join(outside, "probe.txt")} + if volume := filepath.VolumeName(root); volume != "" { + paths = append(paths, volume+"probe.txt") + } + for _, entry := range []string{"file_response", "send_file", "file_path", "error_handler"} { + for _, path := range paths { + t.Run(entry+"/"+path, func(t *testing.T) { + response := &Response{StatusCode: 200, FilePath: path} + if entry == "file_response" || entry == "send_file" { + fn := m.fileResponse + if entry == "send_file" { + fn = m.sendFile + } + v, err := starlark.Call(&starlark.Thread{}, starlark.NewBuiltin(entry, fn), starlark.Tuple{starlark.String(path)}, nil) + if err != nil { + t.Fatal(err) + } + response = v.(*ResponseWrapper).response + } + if entry == "error_handler" { + globals, err := starlark.ExecFile(&starlark.Thread{}, "error.star", "def handler(req):\n return response\n", starlark.StringDict{"response": NewResponseWrapper(response)}) + if err != nil { + t.Fatal(err) + } + srv.errorHandlers.RegisterHandler([]int{404}, globals["handler"].(starlark.Callable)) + response = &Response{StatusCode: 404} + } + c, rec := newGinContextForTest(http.MethodGet, "/probe") + srv.applyResponse(c, response) + if path == filepath.Join(outside, "probe.txt") || (filepath.VolumeName(path) != "" && !filepath.IsAbs(path)) { + if rec.Code != http.StatusNotFound || strings.Contains(rec.Body.String(), "outside") { + t.Errorf("outside file served: %d %q", rec.Code, rec.Body.String()) + } + } else if rec.Code != 200 || rec.Body.String() != "inside" { + t.Errorf("fixed root response: %d %q", rec.Code, rec.Body.String()) + } + }) + } + } +} + +func TestServerMissingFileRootDeniesAccess(t *testing.T) { + srv := newServer(NewModule(), "localhost", 0) + srv.fileRoot = "" // cwd resolution failed at construction + if _, ok := srv.resolveConfinedFile("go.mod"); ok { + t.Error("missing host root must deny file responses") + } + if err := srv.RegisterStatic("/", staticDirFor(".", false)); err == nil { + t.Error("missing host root must deny static mounts") + } +} + +func TestServerUnavailableWorkingDirectory(t *testing.T) { + root := t.TempDir() + useWorkingDir(t, root) + if err := os.Remove(root); err != nil { + t.Skipf("platform cannot remove current directory: %v", err) + } + srv := newServer(NewModule(), "localhost", 0) + if srv.fileRoot != "" { + t.Errorf("unavailable cwd yielded a file grant: %q", srv.fileRoot) + } +} + +func BenchmarkConfinedFileResponse(b *testing.B) { + srv := newServer(NewModule(), "localhost", 0) + response := &Response{StatusCode: 200, FilePath: "go.mod"} + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + c, rec := newGinContextForTest(http.MethodGet, "/f") + srv.applyResponse(c, response) + if rec.Code != 200 { + b.Fatalf("status = %d", rec.Code) + } + } +} diff --git a/static.go b/static.go index dce6e22..322afa7 100644 --- a/static.go +++ b/static.go @@ -148,12 +148,35 @@ func (mt *staticMount) matchPrefix(urlPath string) (string, bool) { } // RegisterStatic mounts a StaticDir at prefix. Most-specific (longest) prefix -// wins when several mounts overlap. +// wins when several mounts overlap. The root must be an existing directory +// beneath the physical working directory captured at server creation, unless +// the host enabled allow_unsafe_file_paths. Its resolved path is fixed at mount +// time, so a later cwd change or retargeting of the original alias cannot grant +// access to a different directory. func (s *Server) RegisterStatic(prefix string, sd *StaticDir) error { if sd == nil { return fmt.Errorf("static: dir must not be nil") } - mt := &staticMount{prefix: normalizeStaticPrefix(prefix), sd: sd} + if sd.rootAbs == "" { + return fmt.Errorf("static: root must not be empty") + } + real, err := filepath.EvalSymlinks(sd.rootAbs) + if err != nil { + return fmt.Errorf("static: cannot resolve root: %w", err) + } + if !s.allowUnsafeFilePaths && (s.fileRoot == "" || !withinRoot(s.fileRoot, real)) { + return fmt.Errorf("static: root is outside the server's working directory") + } + if info, err := os.Stat(real); err != nil || !info.IsDir() { + return fmt.Errorf("static: root must be an existing directory") + } + // Bind an immutable mount copy to the checked physical directory, not to + // the caller's handle or its possibly mutable symlink alias. + bound := *sd + bound.rootAbs, bound.realRoot = real, real + bound.fsys = os.DirFS(real) + bound.index = append([]string(nil), sd.index...) + mt := &staticMount{prefix: normalizeStaticPrefix(prefix), sd: &bound} s.mu.Lock() // Copy-on-write: build a fresh slice rather than appending/sorting in place, // so the lock-free iteration in tryServeStatic (which copies only the slice diff --git a/static_test.go b/static_test.go index d8afaeb..e485aa0 100644 --- a/static_test.go +++ b/static_test.go @@ -7,6 +7,7 @@ package web // - conditional GET (304) and Range (206) via http.ServeContent // - SPA fallback (opt-in) and prefix-mount + explicit-route precedence // - static_dir() / static() argument validation +// - host root authorization and root/symlink lifecycle import ( "fmt" @@ -53,7 +54,11 @@ func setupSite(t *testing.T) string { func newStaticServer(t *testing.T) *Server { t.Helper() - return newServer(NewModule(), "localhost", 8080) + srv := newServer(NewModule(), "localhost", 8080) + // Serving-mechanics fixtures live outside cwd. Root authorization itself is + // covered below using newServer with the default confined policy. + srv.allowUnsafeFilePaths = true + return srv } func staticDirFor(root string, spa bool) *StaticDir { @@ -376,3 +381,137 @@ func TestStaticDirBuiltinValidation(t *testing.T) { t.Error("static() with a non-StaticDir should error") } } + +// --- Host root authorization and lifecycle ----------------------------------- + +// useWorkingDir is intentionally serial: changing cwd is process-wide. +func useWorkingDir(t *testing.T, dir string) { + t.Helper() + old, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + if err := os.Chdir(dir); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := os.Chdir(old); err != nil { + t.Error(err) + } + }) +} + +func TestStaticMountRootPolicy(t *testing.T) { + base := t.TempDir() + root := filepath.Join(base, "app") + outside := filepath.Join(base, "app-sibling") + for _, dir := range []string{root, outside} { + if err := os.MkdirAll(filepath.Join(dir, "assets"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "file.txt"), []byte("fixture"), 0o600); err != nil { + t.Fatal(err) + } + } + useWorkingDir(t, root) + t.Setenv("WEB_ALLOW_UNSAFE_FILE_PATHS", "false") + for _, unsafe := range []bool{false, true} { + for _, tc := range []struct { + name, path string + inside, exists bool + }{ + {"relative_root", ".", true, true}, + {"relative_child", "assets", true, true}, + {"absolute_root", root, true, true}, + {"absolute_child", filepath.Join(root, "assets"), true, true}, + {"parent", "..", false, true}, + {"sibling_prefix", outside, false, true}, + {"relative_sibling", filepath.Join("..", "app-sibling"), false, true}, + {"missing", "missing", true, false}, + {"file_not_directory", "file.txt", true, false}, + } { + t.Run(fmt.Sprintf("unsafe=%v/%s", unsafe, tc.name), func(t *testing.T) { + m := NewModule() + srv := newServer(m, "localhost", 0) + srv.allowUnsafeFilePaths = unsafe // explicit host opt-out + bi := starlark.NewBuiltin("web.static_dir", m.staticDir) + value, err := starlark.Call(&starlark.Thread{}, bi, starlark.Tuple{starlark.String(tc.path)}, nil) + if err != nil { + t.Fatal(err) + } + mount, err := NewServerWrapper(srv).Attr("static") + if err != nil { + t.Fatal(err) + } + _, err = starlark.Call(&starlark.Thread{}, mount, starlark.Tuple{starlark.String("/"), value}, nil) + wantAllowed := tc.exists && (unsafe || tc.inside) + if (err == nil) != wantAllowed { + t.Errorf("mount %q: err=%v, allowed=%v", tc.path, err, wantAllowed) + } + if !wantAllowed && len(srv.staticMounts) != 0 { + t.Error("rejected root must not enter the mount registry") + } + }) + } + } + for _, sd := range []*StaticDir{nil, {}} { + if err := newServer(NewModule(), "localhost", 0).RegisterStatic("/", sd); err == nil { + t.Error("an invalid handle must not authorize a root") + } + } +} + +func TestStaticMountSymlinkLifecycle(t *testing.T) { + root := t.TempDir() + outside := setupSite(t) + inside := filepath.Join(root, "site") + if err := os.Mkdir(inside, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(inside, "index.html"), []byte("inside"), 0o600); err != nil { + t.Fatal(err) + } + useWorkingDir(t, root) + t.Setenv("WEB_ALLOW_UNSAFE_FILE_PATHS", "false") + link := filepath.Join(root, "alias") + if err := os.Symlink(inside, link); err != nil { + t.Skipf("symlinks unsupported: %v", err) + } + srv := newServer(NewModule(), "localhost", 0) + handle := staticDirFor(link, false) + if err := srv.RegisterStatic("/", handle); err != nil { + t.Fatal(err) + } + if err := os.Remove(link); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, link); err != nil { + t.Fatal(err) + } + // The accepted root is frozen, so retargeting its alias does not switch it. + if r := do(srv, "GET", "/", nil); r.Code != 200 || r.Body.String() != "inside" { + t.Errorf("frozen mount: code=%d body=%q", r.Code, r.Body.String()) + } + // A handle built before the alias changed must be checked again on mount. + other := newServer(NewModule(), "localhost", 0) + if err := other.RegisterStatic("/", handle); err == nil { + t.Error("retargeted outside root accepted") + } + if err := other.RegisterStatic("/", staticDirFor(link, false)); err == nil { + t.Error("outside symlink root accepted") + } + other.allowUnsafeFilePaths = true + if err := other.RegisterStatic("/", staticDirFor(link, false)); err != nil { + t.Errorf("host opt-out rejected outside root: %v", err) + } + // Replacing the physical root itself must not grant the replacement target. + if err := os.Rename(inside, inside+"-saved"); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, inside); err != nil { + t.Fatal(err) + } + if r := do(srv, "GET", "/about.html", nil); r.Code != http.StatusNotFound { + t.Errorf("replaced physical root served: %d %q", r.Code, r.Body.String()) + } +} diff --git a/web.go b/web.go index 6b621bb..bbbcd4b 100644 --- a/web.go +++ b/web.go @@ -32,7 +32,7 @@ const ( configKeyAllowPublicBind = "allow_public_bind" // configKeyAllowUnsafeFilePaths gates serving a file whose path escapes the // working directory (an absolute host path or a traversal). It defaults to - // false so file_response/send_file confine reads to the app directory unless + // false so file responses and static mounts stay under the app directory unless // the host explicitly opts in. configKeyAllowUnsafeFilePaths = "allow_unsafe_file_paths" ) @@ -63,7 +63,7 @@ func NewModule() *Module { genConfigOption(configKeyServerHeader, "Custom server header", "Starlark-Web/1.0"), genConfigOption(configKeyAllowPublicBind, "Allow binding to a non-loopback (public) address", false), // Host-only: a script must not be able to lift its own file-path confinement. - genConfigOption(configKeyAllowUnsafeFilePaths, "Allow file_response/send_file to serve paths outside the working directory", false).SetHostOnly(true), + genConfigOption(configKeyAllowUnsafeFilePaths, "Allow file responses and static mounts outside the server working directory", false).SetHostOnly(true), ) }