fix(web): log file errors of the asset server and answer server errors with 500

Assisted-by: Claude Code:claude-opus-5-5
This commit is contained in:
Sara Ahmadi committed 2026-11-25 18:24:51 +01:00
1 parent 63f17a94d0
commit ac365de8db
3 files changed
+234 -42

No files matched your search

+65 -16
View File
@@ -2,36 +2,55 @@ package assets
import (
"bytes"
"errors"
"io"
"io/fs"
"mime"
"net/http"
"path"
"path/filepath"
"syscall"
"golang.org/x/net/html"
"github.com/opencloud-eu/opencloud/pkg/log"
)
type fileServer struct {
fsys http.FileSystem
fsys http.FileSystem
logger log.Logger
}
// FileServer defines the http handler for the embedded files
func FileServer(fsys fs.FS) http.Handler {
return &fileServer{http.FS(fsys)}
func FileServer(logger log.Logger, fsys fs.FS) http.Handler {
return &fileServer{fsys: http.FS(fsys), logger: logger}
}
// errNoFile reports that a path can't be served as a file: it doesn't exist,
// it is a directory, or the filesystem can't have a file with this name.
var errNoFile = errors.New("no file")
func (f *fileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
file, info, ok := f.open(path.Clean(path.Join("/", r.URL.Path)))
if !ok {
name := path.Clean(path.Join("/", r.URL.Path))
served := name
file, info, err := f.open(served)
if errors.Is(err, errNoFile) {
// paths that aren't files are routes of the web app, which index.html handles.
// not every fs contains an index.html: without one, the path is not found.
file, info, ok = f.open("/index.html")
if !ok {
served = "/index.html"
file, info, err = f.open(served)
if errors.Is(err, errNoFile) {
logger := f.logger.SubloggerWithRequestID(r.Context())
logger.Debug().Str("path", name).Msg("neither the path nor /index.html is a file")
http.NotFound(w, r)
return
}
}
if err != nil {
f.serverError(w, r, name, served, err, "could not open the file")
return
}
defer file.Close()
buf := new(bytes.Buffer)
@@ -41,12 +60,12 @@ func (f *fileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Del("Expires")
w.Header().Set("Cache-Control", "no-cache")
if err := withBase(buf, file, "/"); err != nil {
http.NotFound(w, r)
f.serverError(w, r, name, served, err, "could not read the file")
return
}
default:
if _, err := buf.ReadFrom(file); err != nil {
http.NotFound(w, r)
f.serverError(w, r, name, served, err, "could not read the file")
return
}
}
@@ -55,20 +74,50 @@ func (f *fileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(buf.Bytes())
}
// open returns the file with the given name if it exists and isn't a directory.
func (f *fileServer) open(name string) (http.File, fs.FileInfo, bool) {
// open returns the file with the given name. It returns errNoFile if there is
// no file with this name, and any other error if the file couldn't be opened.
func (f *fileServer) open(name string) (http.File, fs.FileInfo, error) {
file, err := f.fsys.Open(name)
if err != nil {
return nil, nil, false
switch {
case isNoFile(err):
return nil, nil, errNoFile
case err != nil:
return nil, nil, err
}
info, err := file.Stat()
if err != nil || info.IsDir() {
switch {
case err != nil:
_ = file.Close()
return nil, nil, false
return nil, nil, err
case info.IsDir():
_ = file.Close()
return nil, nil, errNoFile
}
return file, info, true
return file, info, nil
}
// isNoFile reports whether err means that there is no file with the requested
// name, either because it doesn't exist or because the filesystem can't have
// such a name, e.g. one that is too long or contains a NUL byte.
func isNoFile(err error) bool {
return errors.Is(err, fs.ErrNotExist) ||
errors.Is(err, fs.ErrInvalid) ||
errors.Is(err, syscall.ENAMETOOLONG) ||
errors.Is(err, syscall.EINVAL) // e.g. a NUL byte in the name
}
// serverError logs err with the requested path and the file that failed, which
// is /index.html for a web app route, and answers with a 500 that must not be
// cached, so that a passing error doesn't stick in browsers and proxies.
func (f *fileServer) serverError(w http.ResponseWriter, r *http.Request, name, filename string, err error, msg string) {
logger := f.logger.SubloggerWithRequestID(r.Context())
logger.Error().Err(err).Str("path", name).Str("filename", filename).Msg(msg)
w.Header().Del("Expires")
w.Header().Set("Cache-Control", "no-store")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
func withBase(w io.Writer, r io.Reader, base string) error {
+168 -25
View File
@@ -1,6 +1,9 @@
package assets
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/fs"
@@ -9,11 +12,16 @@ import (
"net/url"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"testing/fstest"
chimiddleware "github.com/go-chi/chi/v5/middleware"
"github.com/onsi/gomega"
"github.com/rs/zerolog"
"github.com/opencloud-eu/opencloud/pkg/log"
"github.com/opencloud-eu/opencloud/pkg/x/io/fsx"
)
@@ -24,7 +32,7 @@ func TestFileServer(t *testing.T) {
}
{
s := FileServer(fstest.MapFS{})
s := FileServer(log.NopLogger(), fstest.MapFS{})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/foo", nil)
//defer req.Body.Close()
@@ -110,7 +118,7 @@ func TestFileServer(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", tt.url, nil)
FileServer(tt.fs).ServeHTTP(w, req)
FileServer(log.NopLogger(), tt.fs).ServeHTTP(w, req)
res := w.Result()
defer res.Body.Close()
@@ -152,7 +160,7 @@ func TestFileServerIndexIsDirectory(t *testing.T) {
}
w := httptest.NewRecorder()
(&fileServer{fsys: fsys}).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/missing", nil))
(&fileServer{fsys: fsys, logger: log.NopLogger()}).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/missing", nil))
g.Expect(w.Code).To(gomega.Equal(http.StatusNotFound))
g.Expect(fsys.opens).To(gomega.BeNumerically("<=", 3), "the index fallback must not call itself again")
@@ -161,6 +169,7 @@ func TestFileServerIndexIsDirectory(t *testing.T) {
// faultyFS returns files whose Stat or Read fail, for the names given.
type faultyFS struct {
http.FileSystem
openErr map[string]error
statErr map[string]bool
readErr map[string]bool
}
@@ -173,7 +182,7 @@ type faultyFile struct {
func (f faultyFile) Stat() (fs.FileInfo, error) {
if f.statErr {
return nil, fs.ErrInvalid
return nil, syscall.EIO
}
return f.File.Stat()
}
@@ -190,6 +199,9 @@ func (f faultyFile) Read(p []byte) (int, error) {
}
func (f faultyFS) Open(name string) (http.File, error) {
if err := f.openErr[name]; err != nil {
return nil, err
}
file, err := f.FileSystem.Open(name)
if err != nil {
return nil, err
@@ -197,61 +209,165 @@ func (f faultyFS) Open(name string) (http.File, error) {
return faultyFile{File: file, statErr: f.statErr[name], readErr: f.readErr[name]}, nil
}
type logEntry struct {
level string
path string
filename string
}
// logEntries returns the level and the path of each log entry, and checks
// that each one carries the request id.
func logEntries(g *gomega.WithT, buf *bytes.Buffer, requestID string) []logEntry {
var entries []logEntry
for line := range strings.SplitSeq(strings.TrimSpace(buf.String()), "\n") {
if line == "" {
continue
}
var e map[string]any
g.Expect(json.Unmarshal([]byte(line), &e)).To(gomega.Succeed())
g.Expect(e).To(gomega.HaveKeyWithValue(log.RequestIDString, requestID), line)
entry := logEntry{level: fmt.Sprint(e["level"])}
if p, ok := e["path"]; ok {
entry.path = fmt.Sprint(p)
}
if f, ok := e["filename"]; ok {
entry.filename = fmt.Sprint(f)
}
entries = append(entries, entry)
}
return entries
}
func TestFileServerFaultyFiles(t *testing.T) {
// Match log.NewLogger's global level, the loggers of the test cases filter on their own.
previousLevel := zerolog.GlobalLevel()
zerolog.SetGlobalLevel(zerolog.TraceLevel)
t.Cleanup(func() { zerolog.SetGlobalLevel(previousLevel) })
mapFS := fstest.MapFS{
"index.html": &fstest.MapFile{Data: []byte("index file content")},
"app.js": &fstest.MapFile{Data: []byte("console.log('complete file')")},
}
index := `<html><head><base href="/"/></head><body>index file content</body></html>`
for _, tt := range []struct {
name string
url string
openErr map[string]error
statErr []string
readErr []string
expectedCode int
expectedBody string
// the cache headers after the request, when Static has set them before
expectedCacheControl string
expectedLogs []logEntry
}{
{
name: "stat error falls back to the index",
url: "/app.js",
statErr: []string{"/app.js"},
expectedCode: http.StatusOK,
expectedBody: `<html><head><base href="/"/></head><body>index file content</body></html>`,
name: "missing file falls back to the index without a log entry",
url: "/missing",
expectedCode: http.StatusOK,
expectedBody: index,
expectedCacheControl: "no-cache",
},
{
name: "stat error on the index",
name: "name too long falls back to the index without a log entry",
url: "/long",
openErr: map[string]error{"/long": &fs.PathError{Op: "open", Path: "long", Err: syscall.ENAMETOOLONG}},
expectedCode: http.StatusOK,
expectedBody: index,
expectedCacheControl: "no-cache",
},
{
name: "invalid name falls back to the index without a log entry",
url: "/invalid",
openErr: map[string]error{"/invalid": &fs.PathError{Op: "open", Path: "invalid", Err: syscall.EINVAL}},
expectedCode: http.StatusOK,
expectedBody: index,
expectedCacheControl: "no-cache",
},
{
name: "invalid fs path falls back to the index without a log entry",
url: "/invalid",
openErr: map[string]error{"/invalid": &fs.PathError{Op: "open", Path: "invalid", Err: fs.ErrInvalid}},
expectedCode: http.StatusOK,
expectedBody: index,
expectedCacheControl: "no-cache",
},
{
name: "missing index",
url: "/missing",
statErr: []string{"/index.html"},
openErr: map[string]error{"/index.html": &fs.PathError{Op: "open", Path: "index.html", Err: fs.ErrNotExist}},
expectedCode: http.StatusNotFound,
expectedLogs: []logEntry{{level: "debug", path: "/missing"}},
},
{
name: "open error on an asset",
url: "/app.js",
openErr: map[string]error{"/app.js": &fs.PathError{Op: "open", Path: "app.js", Err: fs.ErrPermission}},
expectedCode: http.StatusInternalServerError,
expectedBody: "Internal Server Error\n",
expectedCacheControl: "no-store",
expectedLogs: []logEntry{{level: "error", path: "/app.js", filename: "/app.js"}},
},
{
name: "open error on the index fallback",
url: "/missing",
openErr: map[string]error{"/index.html": &fs.PathError{Op: "open", Path: "index.html", Err: fs.ErrPermission}},
expectedCode: http.StatusInternalServerError,
expectedBody: "Internal Server Error\n",
expectedCacheControl: "no-store",
expectedLogs: []logEntry{{level: "error", path: "/missing", filename: "/index.html"}},
},
{
name: "stat error on an asset",
url: "/app.js",
statErr: []string{"/app.js"},
expectedCode: http.StatusInternalServerError,
expectedBody: "Internal Server Error\n",
expectedCacheControl: "no-store",
expectedLogs: []logEntry{{level: "error", path: "/app.js", filename: "/app.js"}},
},
{
name: "stat error on the index fallback",
url: "/missing",
statErr: []string{"/index.html"},
expectedCode: http.StatusInternalServerError,
expectedBody: "Internal Server Error\n",
expectedCacheControl: "no-store",
expectedLogs: []logEntry{{level: "error", path: "/missing", filename: "/index.html"}},
},
{
name: "read error on an asset",
url: "/app.js",
readErr: []string{"/app.js"},
expectedCode: http.StatusNotFound,
expectedCacheControl: "max-age=60",
expectedCode: http.StatusInternalServerError,
expectedBody: "Internal Server Error\n",
expectedCacheControl: "no-store",
expectedLogs: []logEntry{{level: "error", path: "/app.js", filename: "/app.js"}},
},
{
name: "read error on the index",
url: "/index.html",
readErr: []string{"/index.html"},
expectedCode: http.StatusNotFound,
expectedCacheControl: "no-cache",
expectedCode: http.StatusInternalServerError,
expectedBody: "Internal Server Error\n",
expectedCacheControl: "no-store",
expectedLogs: []logEntry{{level: "error", path: "/index.html", filename: "/index.html"}},
},
{
name: "read error on the index fallback",
url: "/missing",
readErr: []string{"/index.html"},
expectedCode: http.StatusNotFound,
expectedCacheControl: "no-cache",
expectedCode: http.StatusInternalServerError,
expectedBody: "Internal Server Error\n",
expectedCacheControl: "no-store",
expectedLogs: []logEntry{{level: "error", path: "/missing", filename: "/index.html"}},
},
} {
t.Run(tt.name, func(t *testing.T) {
g := gomega.NewWithT(t)
fsys := faultyFS{FileSystem: http.FS(mapFS), statErr: map[string]bool{}, readErr: map[string]bool{}}
fsys := faultyFS{FileSystem: http.FS(mapFS), openErr: tt.openErr, statErr: map[string]bool{}, readErr: map[string]bool{}}
for _, n := range tt.statErr {
fsys.statErr[n] = true
}
@@ -259,12 +375,16 @@ func TestFileServerFaultyFiles(t *testing.T) {
fsys.readErr[n] = true
}
buf := &bytes.Buffer{}
server := &fileServer{fsys: fsys, logger: log.Logger{Logger: zerolog.New(buf).Level(zerolog.DebugLevel)}}
req := httptest.NewRequest(http.MethodGet, tt.url, nil)
req = req.WithContext(context.WithValue(req.Context(), chimiddleware.RequestIDKey, "test-request-id"))
w := httptest.NewRecorder()
w.Header().Set("Cache-Control", "max-age=60")
w.Header().Set("Expires", "Thu, 01 Jan 2099 00:00:00 GMT")
g.Expect(func() {
(&fileServer{fsys: fsys}).ServeHTTP(w, httptest.NewRequest(http.MethodGet, tt.url, nil))
}).ToNot(gomega.Panic())
g.Expect(func() { server.ServeHTTP(w, req) }).ToNot(gomega.Panic())
g.Expect(w.Code).To(gomega.Equal(tt.expectedCode))
if tt.expectedBody != "" {
@@ -272,10 +392,9 @@ func TestFileServerFaultyFiles(t *testing.T) {
}
if tt.expectedCacheControl != "" {
g.Expect(w.Header().Get("Cache-Control")).To(gomega.Equal(tt.expectedCacheControl))
if tt.expectedCacheControl == "no-cache" {
g.Expect(w.Header().Get("Expires")).To(gomega.BeEmpty())
}
g.Expect(w.Header().Get("Expires")).To(gomega.BeEmpty())
}
g.Expect(logEntries(g, buf, "test-request-id")).To(gomega.Equal(tt.expectedLogs))
})
}
}
@@ -290,7 +409,7 @@ func TestFileServerOnDisk(t *testing.T) {
g.Expect(os.WriteFile(filepath.Join(root, "js", "app.js"), []byte("app content"), 0o644)).To(gomega.Succeed())
// the same layering as the web service: a directory on disk with the embedded assets as fallback
server := FileServer(fsx.NewFallbackFS(
server := FileServer(log.NopLogger(), fsx.NewFallbackFS(
fsx.NewBasePathFs(fsx.NewOsFs(), root),
fsx.NewMemMapFs(),
).IOFS())
@@ -307,6 +426,8 @@ func TestFileServerOnDisk(t *testing.T) {
{name: "parent directory", url: "/../outside.txt", expectedBody: index},
{name: "encoded parent directory", url: "/%2e%2e/outside.txt", expectedBody: index},
{name: "relative path", url: "js/app.js", expectedBody: "app content"},
{name: "name too long", url: "/files/spaces/personal/admin/" + strings.Repeat("文", 100), expectedBody: index},
{name: "nul byte", url: "/files/a%00b", expectedBody: index},
} {
t.Run(tt.name, func(t *testing.T) {
g := gomega.NewWithT(t)
@@ -324,3 +445,25 @@ func TestFileServerOnDisk(t *testing.T) {
})
}
}
func TestFileServerOnDiskUnreadable(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("root can read files without read permission")
}
g := gomega.NewWithT(t)
root := t.TempDir()
g.Expect(os.WriteFile(filepath.Join(root, "index.html"), []byte("index file content"), 0o644)).To(gomega.Succeed())
g.Expect(os.WriteFile(filepath.Join(root, "app.js"), []byte("app content"), 0o000)).To(gomega.Succeed())
server := FileServer(log.NopLogger(), fsx.NewFallbackFS(
fsx.NewBasePathFs(fsx.NewOsFs(), root),
fsx.NewMemMapFs(),
).IOFS())
w := httptest.NewRecorder()
server.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/app.js", nil))
g.Expect(w.Code).To(gomega.Equal(http.StatusInternalServerError))
g.Expect(w.Body.String()).ToNot(gomega.ContainSubstring("index file content"))
}
+1 -1
View File
@@ -211,7 +211,7 @@ func (p Web) Static(f fs.FS, root string, ttl int) http.HandlerFunc {
static := http.StripPrefix(
rootWithSlash,
assets.FileServer(f),
assets.FileServer(p.logger, f),
)
lastModified := time.Now().UTC().Format(http.TimeFormat)