mirror of
https://github.com/opencloud-eu/opencloud.git
synced 2026-11-26 18:16:47 -05:00
fix: serve the web index fallback without recursion and handle file errors
Assisted-by: Claude Code:claude-opus-5-5
This commit is contained in:
1 parent
9ebb6a75a6
commit
63f17a94d0
2 files changed
+242
-32
No files matched your search
@@ -22,55 +22,60 @@ func FileServer(fsys fs.FS) http.Handler {
|
||||
}
|
||||
|
||||
func (f *fileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
uPath := path.Clean(path.Join("/", r.URL.Path))
|
||||
r.URL.Path = uPath
|
||||
|
||||
tryIndex := func() {
|
||||
r.URL.Path = "/index.html"
|
||||
|
||||
// not every fs contains a file named index.html,
|
||||
// therefore, we need to check if the file exists and stop the recursion if it doesn't
|
||||
file, err := f.fsys.Open(r.URL.Path)
|
||||
if err != nil {
|
||||
file, info, ok := f.open(path.Clean(path.Join("/", r.URL.Path)))
|
||||
if !ok {
|
||||
// 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 {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
f.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
asset, err := f.fsys.Open(uPath)
|
||||
if err != nil {
|
||||
tryIndex()
|
||||
return
|
||||
}
|
||||
defer asset.Close()
|
||||
|
||||
s, _ := asset.Stat()
|
||||
if s.IsDir() {
|
||||
tryIndex()
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", mime.TypeByExtension(filepath.Ext(s.Name())))
|
||||
defer file.Close()
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
|
||||
switch s.Name() {
|
||||
switch info.Name() {
|
||||
case "index.html", "oidc-callback.html", "oidc-silent-redirect.html":
|
||||
w.Header().Del("Expires")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
_ = withBase(buf, asset, "/")
|
||||
if err := withBase(buf, file, "/"); err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
default:
|
||||
_, _ = buf.ReadFrom(asset)
|
||||
if _, err := buf.ReadFrom(file); err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", mime.TypeByExtension(filepath.Ext(info.Name())))
|
||||
_, _ = 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) {
|
||||
file, err := f.fsys.Open(name)
|
||||
if err != nil {
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
info, err := file.Stat()
|
||||
if err != nil || info.IsDir() {
|
||||
_ = file.Close()
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
return file, info, true
|
||||
}
|
||||
|
||||
func withBase(w io.Writer, r io.Reader, base string) error {
|
||||
doc, _ := html.Parse(r)
|
||||
doc, err := html.Parse(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var parse func(*html.Node)
|
||||
parse = func(n *html.Node) {
|
||||
if n.Type == html.ElementNode && n.Data == "head" {
|
||||
|
||||
@@ -6,10 +6,15 @@ import (
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/onsi/gomega"
|
||||
|
||||
"github.com/opencloud-eu/opencloud/pkg/x/io/fsx"
|
||||
)
|
||||
|
||||
func TestFileServer(t *testing.T) {
|
||||
@@ -119,3 +124,203 @@ func TestFileServer(t *testing.T) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// limitedFS refuses to open more than max files, like a process that has
|
||||
// run out of file descriptors, and counts how often Open was called.
|
||||
type limitedFS struct {
|
||||
http.FileSystem
|
||||
max int
|
||||
opens int
|
||||
}
|
||||
|
||||
func (l *limitedFS) Open(name string) (http.File, error) {
|
||||
l.opens++
|
||||
if l.opens > l.max {
|
||||
return nil, fs.ErrPermission
|
||||
}
|
||||
return l.FileSystem.Open(name)
|
||||
}
|
||||
|
||||
func TestFileServerIndexIsDirectory(t *testing.T) {
|
||||
g := gomega.NewWithT(t)
|
||||
|
||||
fsys := &limitedFS{
|
||||
FileSystem: http.FS(fstest.MapFS{
|
||||
"index.html": &fstest.MapFile{Mode: fs.ModeDir},
|
||||
}),
|
||||
max: 100,
|
||||
}
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
(&fileServer{fsys: fsys}).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")
|
||||
}
|
||||
|
||||
// faultyFS returns files whose Stat or Read fail, for the names given.
|
||||
type faultyFS struct {
|
||||
http.FileSystem
|
||||
statErr map[string]bool
|
||||
readErr map[string]bool
|
||||
}
|
||||
|
||||
type faultyFile struct {
|
||||
http.File
|
||||
statErr bool
|
||||
readErr bool
|
||||
}
|
||||
|
||||
func (f faultyFile) Stat() (fs.FileInfo, error) {
|
||||
if f.statErr {
|
||||
return nil, fs.ErrInvalid
|
||||
}
|
||||
return f.File.Stat()
|
||||
}
|
||||
|
||||
func (f faultyFile) Read(p []byte) (int, error) {
|
||||
if f.readErr {
|
||||
n, _ := f.File.Read(p[:min(len(p), 4)])
|
||||
if n > 0 {
|
||||
return n, nil
|
||||
}
|
||||
return 0, io.ErrUnexpectedEOF
|
||||
}
|
||||
return f.File.Read(p)
|
||||
}
|
||||
|
||||
func (f faultyFS) Open(name string) (http.File, error) {
|
||||
file, err := f.FileSystem.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return faultyFile{File: file, statErr: f.statErr[name], readErr: f.readErr[name]}, nil
|
||||
}
|
||||
|
||||
func TestFileServerFaultyFiles(t *testing.T) {
|
||||
mapFS := fstest.MapFS{
|
||||
"index.html": &fstest.MapFile{Data: []byte("index file content")},
|
||||
"app.js": &fstest.MapFile{Data: []byte("console.log('complete file')")},
|
||||
}
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
url string
|
||||
statErr []string
|
||||
readErr []string
|
||||
expectedCode int
|
||||
expectedBody string
|
||||
// the cache headers after the request, when Static has set them before
|
||||
expectedCacheControl string
|
||||
}{
|
||||
{
|
||||
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: "stat error on the index",
|
||||
url: "/missing",
|
||||
statErr: []string{"/index.html"},
|
||||
expectedCode: http.StatusNotFound,
|
||||
},
|
||||
{
|
||||
name: "read error on an asset",
|
||||
url: "/app.js",
|
||||
readErr: []string{"/app.js"},
|
||||
expectedCode: http.StatusNotFound,
|
||||
expectedCacheControl: "max-age=60",
|
||||
},
|
||||
{
|
||||
name: "read error on the index",
|
||||
url: "/index.html",
|
||||
readErr: []string{"/index.html"},
|
||||
expectedCode: http.StatusNotFound,
|
||||
expectedCacheControl: "no-cache",
|
||||
},
|
||||
{
|
||||
name: "read error on the index fallback",
|
||||
url: "/missing",
|
||||
readErr: []string{"/index.html"},
|
||||
expectedCode: http.StatusNotFound,
|
||||
expectedCacheControl: "no-cache",
|
||||
},
|
||||
} {
|
||||
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{}}
|
||||
for _, n := range tt.statErr {
|
||||
fsys.statErr[n] = true
|
||||
}
|
||||
for _, n := range tt.readErr {
|
||||
fsys.readErr[n] = true
|
||||
}
|
||||
|
||||
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(w.Code).To(gomega.Equal(tt.expectedCode))
|
||||
if tt.expectedBody != "" {
|
||||
g.Expect(w.Body.String()).To(gomega.Equal(tt.expectedBody))
|
||||
}
|
||||
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())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileServerOnDisk(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
root := filepath.Join(base, "core")
|
||||
g := gomega.NewWithT(t)
|
||||
g.Expect(os.MkdirAll(filepath.Join(root, "js"), 0o755)).To(gomega.Succeed())
|
||||
g.Expect(os.WriteFile(filepath.Join(base, "outside.txt"), []byte("outside content"), 0o644)).To(gomega.Succeed())
|
||||
g.Expect(os.WriteFile(filepath.Join(root, "index.html"), []byte("index file content"), 0o644)).To(gomega.Succeed())
|
||||
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(
|
||||
fsx.NewBasePathFs(fsx.NewOsFs(), root),
|
||||
fsx.NewMemMapFs(),
|
||||
).IOFS())
|
||||
|
||||
index := `<html><head><base href="/"/></head><body>index file content</body></html>`
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
url string
|
||||
expectedBody string
|
||||
}{
|
||||
{name: "regular file", url: "/js/app.js", expectedBody: "app content"},
|
||||
{name: "deep link", url: "/files/spaces/personal/admin", expectedBody: index},
|
||||
{name: "directory", url: "/js", expectedBody: index},
|
||||
{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"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
g := gomega.NewWithT(t)
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
// set the path directly: a path without a leading slash is no valid request target
|
||||
u, err := url.Parse(tt.url)
|
||||
g.Expect(err).ToNot(gomega.HaveOccurred())
|
||||
req.URL.Path = u.Path
|
||||
server.ServeHTTP(w, req)
|
||||
|
||||
g.Expect(w.Code).To(gomega.Equal(http.StatusOK))
|
||||
g.Expect(w.Body.String()).To(gomega.Equal(tt.expectedBody))
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user