Просмотр исходного кода

fix(webui): validate web UI files by content, not modification time

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jamesread 4 дней назад
Родитель
Сommit
0f33ed0593

+ 18 - 11
service/internal/httpservers/webuiServer.go

@@ -4,6 +4,7 @@ import (
 	"net/http"
 	"os"
 	"path"
+	"strings"
 
 	log "github.com/sirupsen/logrus"
 
@@ -38,22 +39,26 @@ func NewWebUIServer(cfg *config.Config) *webUIServer {
 // (webUIDir) do not hash their asset names at all. Without Cache-Control,
 // browsers cache responses that only carry Last-Modified heuristically, and
 // can keep an old UI after an upgrade. no-cache makes them revalidate every
-// time; unchanged files still come back as a cheap 304.
+// time; unchanged files still come back as a cheap 304 (see webui_etag.go).
 const webuiCacheControl = "no-cache"
 
 func (s *webUIServer) handleWebui(w http.ResponseWriter, r *http.Request) {
 	w.Header().Set("Cache-Control", webuiCacheControl)
 
-	// Mangle requests for any path like /logs or /config to load the webui index.html
-	if path.Ext(r.URL.Path) == "" && r.URL.Path != "/" {
-		log.Debugf("Mangling request for %s to /index.html", r.URL.Path)
-		http.ServeFile(w, r, path.Join(s.webuiDir, "index.html"))
-		return
-	}
+	// http.Dir rejects path traversal; do not Join raw URL paths into ServeFile.
+	root := http.Dir(s.webuiDir)
 
 	log.Tracef("Serving webui from %s for %s", s.webuiDir, r.URL.Path)
-	// http.Dir rejects path traversal; do not Join raw URL paths into ServeFile.
-	http.FileServer(http.Dir(s.webuiDir)).ServeHTTP(w, r)
+	serveFileWithContentETag(w, r, root, webuiFileName(r.URL.Path), http.FileServer(root))
+}
+
+// Mangle requests for any path like /logs or /config to load the webui index.html
+func webuiFileName(urlPath string) string {
+	if path.Ext(urlPath) == "" {
+		return "/index.html"
+	}
+
+	return urlPath
 }
 
 func (s *webUIServer) findWebuiDir() string {
@@ -138,10 +143,12 @@ func (s *webUIServer) generateThemeCss(w http.ResponseWriter, r *http.Request) {
 }
 
 func (s *webUIServer) handleCustomWebui() http.Handler {
-	fs := http.StripPrefix("/custom-webui/", http.FileServer(http.Dir(s.findCustomWebuiDir())))
+	root := http.Dir(s.findCustomWebuiDir())
+	fileServer := http.StripPrefix("/custom-webui/", http.FileServer(root))
 
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		w.Header().Set("Cache-Control", webuiCacheControl)
-		fs.ServeHTTP(w, r)
+		name := "/" + strings.TrimPrefix(r.URL.Path, "/custom-webui/")
+		serveFileWithContentETag(w, r, root, name, fileServer)
 	})
 }

+ 95 - 1
service/internal/httpservers/webuiServer_test.go

@@ -6,9 +6,12 @@ import (
 	"os"
 	"path/filepath"
 	"testing"
+	"time"
 
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
+
+	config "github.com/OliveTin/OliveTin/internal/config"
 )
 
 func TestHandleWebuiSetsCacheControl(t *testing.T) {
@@ -26,6 +29,97 @@ func TestHandleWebuiSetsCacheControl(t *testing.T) {
 
 		assert.Equal(t, http.StatusOK, rec.Code, p)
 		assert.Equal(t, "no-cache", rec.Header().Get("Cache-Control"), p)
-		assert.NotEmpty(t, rec.Header().Get("Last-Modified"), p)
+		assert.NotEmpty(t, rec.Header().Get("ETag"), p)
+		assert.Empty(t, rec.Header().Get("Last-Modified"), p)
+	}
+}
+
+func getWithHeader(t *testing.T, handler http.Handler, urlPath string, header string, value string) *httptest.ResponseRecorder {
+	t.Helper()
+
+	req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, urlPath, nil)
+	if header != "" {
+		req.Header.Set(header, value)
 	}
+
+	rec := httptest.NewRecorder()
+	handler.ServeHTTP(rec, req)
+
+	return rec
+}
+
+func writeFileWithModTime(t *testing.T, filename string, content string, modTime time.Time) {
+	t.Helper()
+
+	require.NoError(t, os.WriteFile(filename, []byte(content), 0o600))
+	require.NoError(t, os.Chtimes(filename, modTime, modTime))
+}
+
+func TestHandleWebuiRevalidatesByContent(t *testing.T) {
+	t.Parallel()
+
+	dir := t.TempDir()
+	appFile := filepath.Join(dir, "app.js")
+	modTime := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
+	writeFileWithModTime(t, appFile, "// old app", modTime)
+
+	s := &webUIServer{webuiDir: dir}
+	handler := http.HandlerFunc(s.handleWebui)
+
+	first := getWithHeader(t, handler, "/app.js", "", "")
+	require.Equal(t, http.StatusOK, first.Code)
+	oldETag := first.Header().Get("ETag")
+
+	unchanged := getWithHeader(t, handler, "/app.js", "If-None-Match", oldETag)
+	assert.Equal(t, http.StatusNotModified, unchanged.Code)
+
+	writeFileWithModTime(t, appFile, "// new app", modTime.Add(-time.Hour))
+
+	replaced := getWithHeader(t, handler, "/app.js", "If-None-Match", oldETag)
+	assert.Equal(t, http.StatusOK, replaced.Code)
+	assert.Equal(t, "// new app", replaced.Body.String())
+	assert.NotEqual(t, oldETag, replaced.Header().Get("ETag"))
+
+	legacy := getWithHeader(t, handler, "/app.js", "If-Modified-Since", modTime.Format(http.TimeFormat))
+	assert.Equal(t, http.StatusOK, legacy.Code)
+	assert.Equal(t, "// new app", legacy.Body.String())
+}
+
+func TestHandleWebuiMissingFile(t *testing.T) {
+	t.Parallel()
+
+	s := &webUIServer{webuiDir: t.TempDir()}
+
+	rec := getWithHeader(t, http.HandlerFunc(s.handleWebui), "/missing.js", "", "")
+	assert.Equal(t, http.StatusNotFound, rec.Code)
+}
+
+func TestHandleCustomWebuiRevalidatesByContent(t *testing.T) {
+	t.Parallel()
+
+	configDir := t.TempDir()
+	iconsDir := filepath.Join(configDir, "custom-webui", "icons")
+	require.NoError(t, os.MkdirAll(iconsDir, 0o750))
+
+	iconFile := filepath.Join(iconsDir, "open.svg")
+	modTime := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
+	writeFileWithModTime(t, iconFile, "<svg>old</svg>", modTime)
+
+	cfg := config.DefaultConfig()
+	cfg.SetDir(configDir)
+	handler := (&webUIServer{cfg: cfg}).handleCustomWebui()
+
+	first := getWithHeader(t, handler, "/custom-webui/icons/open.svg", "", "")
+	require.Equal(t, http.StatusOK, first.Code)
+	assert.Equal(t, "no-cache", first.Header().Get("Cache-Control"))
+	assert.Empty(t, first.Header().Get("Last-Modified"))
+
+	writeFileWithModTime(t, iconFile, "<svg>new</svg>", modTime)
+
+	replaced := getWithHeader(t, handler, "/custom-webui/icons/open.svg", "If-None-Match", first.Header().Get("ETag"))
+	assert.Equal(t, http.StatusOK, replaced.Code)
+	assert.Equal(t, "<svg>new</svg>", replaced.Body.String())
+
+	missing := getWithHeader(t, handler, "/custom-webui/icons/closed.svg", "", "")
+	assert.Equal(t, http.StatusNotFound, missing.Code)
 }

+ 81 - 0
service/internal/httpservers/webui_etag.go

@@ -0,0 +1,81 @@
+package httpservers
+
+import (
+	"crypto/sha256"
+	"encoding/hex"
+	"errors"
+	"io"
+	"io/fs"
+	"net/http"
+	"time"
+
+	log "github.com/sirupsen/logrus"
+)
+
+// A replacement web UI file can keep the same, or an older, modification time
+// as the file it replaces (for example when it is copied with its times
+// preserved), so Last-Modified cannot tell a browser that it changed. Files are
+// validated by a hash of their content instead, and no modification time is
+// sent or compared, so a browser still holding a Last-Modified value from an
+// older release always gets the current file.
+
+var errServeIsDirectory = errors.New("path is a directory")
+
+func serveFileWithContentETag(w http.ResponseWriter, r *http.Request, root http.FileSystem, name string, fallback http.Handler) {
+	file, info, err := openServableFile(root, name)
+	if err != nil {
+		fallback.ServeHTTP(w, r)
+		return
+	}
+
+	defer closeServedFile(file, name)
+
+	etag, err := contentETag(file)
+	if err != nil {
+		log.Warnf("Could not hash web UI file %s: %v", name, err)
+		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
+		return
+	}
+
+	w.Header().Set("ETag", etag)
+	http.ServeContent(w, r, info.Name(), time.Time{}, file)
+}
+
+func openServableFile(root http.FileSystem, name string) (http.File, fs.FileInfo, error) {
+	file, err := root.Open(name)
+	if err != nil {
+		return nil, nil, err
+	}
+
+	info, err := file.Stat()
+	if err == nil && info.IsDir() {
+		err = errServeIsDirectory
+	}
+
+	if err != nil {
+		closeServedFile(file, name)
+		return nil, nil, err
+	}
+
+	return file, info, nil
+}
+
+func closeServedFile(file http.File, name string) {
+	if err := file.Close(); err != nil {
+		log.Warnf("Could not close web UI file %s: %v", name, err)
+	}
+}
+
+func contentETag(file http.File) (string, error) {
+	hash := sha256.New()
+
+	if _, err := io.Copy(hash, file); err != nil {
+		return "", err
+	}
+
+	if _, err := file.Seek(0, io.SeekStart); err != nil {
+		return "", err
+	}
+
+	return `"` + hex.EncodeToString(hash.Sum(nil)[:16]) + `"`, nil
+}