Explorar o código

fix: address remaining review comments on the release PR (#1192)

James Read hai 1 día
pai
achega
19b4fe6005

+ 19 - 5
.github/workflows/release-upgrade-notes.yml

@@ -41,14 +41,28 @@ jobs:
           fetch-depth: 0
           fetch-depth: 0
           token: ${{ secrets.CONTAINER_TOKEN }}
           token: ${{ secrets.CONTAINER_TOKEN }}
 
 
+      # Runs are queued in the order they start waiting, not in tag order, so
+      # this run may start before the run for an earlier release. Every
+      # release up to this one is processed oldest first, so a note always
+      # moves under the first release that shipped it. Releases that already
+      # have a section are skipped by the script.
       - name: Move released upgrade notes
       - name: Move released upgrade notes
         run: |
         run: |
           released_notes="${RUNNER_TEMP}/upgrade_notes_released.adoc"
           released_notes="${RUNNER_TEMP}/upgrade_notes_released.adoc"
-          if ! git show "refs/tags/${RELEASE_TAG}:${NOTES_PATH}" > "${released_notes}"; then
-            echo "Tag ${RELEASE_TAG} has no ${NOTES_PATH}; nothing to do."
-            exit 0
+          if ! git rev-parse -q --verify "refs/tags/${RELEASE_TAG}" > /dev/null; then
+            echo "Tag ${RELEASE_TAG} does not exist."
+            exit 1
           fi
           fi
-          python3 -I scripts/release_upgrade_notes.py "${RELEASE_TAG}" "${released_notes}" "${NOTES_PATH}"
+          git tag -l '3*.*.*' | grep -v -e '-' | sort -V | while read -r tag; do
+            if ! git show "refs/tags/${tag}:${NOTES_PATH}" > "${released_notes}" 2>/dev/null; then
+              echo "Tag ${tag} has no ${NOTES_PATH}; skipping."
+            else
+              python3 -I scripts/release_upgrade_notes.py "${tag}" "${released_notes}" "${NOTES_PATH}"
+            fi
+            if [ "${tag}" = "${RELEASE_TAG}" ]; then
+              break
+            fi
+          done
 
 
       - name: Commit and push
       - name: Commit and push
         run: |
         run: |
@@ -59,5 +73,5 @@ jobs:
           git config user.name "github-actions[bot]"
           git config user.name "github-actions[bot]"
           git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
           git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
           git add "${NOTES_PATH}"
           git add "${NOTES_PATH}"
-          git commit -m "docs: label upgrade notes released in ${RELEASE_TAG}"
+          git commit -m "docs: label upgrade notes released up to ${RELEASE_TAG}"
           git push origin HEAD:next
           git push origin HEAD:next

+ 1 - 1
docs/modules/ROOT/examples/solutions/single-button-toggle/config.yaml

@@ -9,7 +9,7 @@ actions:
     shell: |
     shell: |
       set -e
       set -e
       entity_file=/etc/OliveTin/entities/water_valve.yaml
       entity_file=/etc/OliveTin/entities/water_valve.yaml
-      if grep -Eq "^  state: +[\"']?open[\"']? *$" "$entity_file"; then
+      if grep -Eq "^  state: +[\"']?open[\"']?( +#.*)? *$" "$entity_file"; then
         next_state=closed
         next_state=closed
       else
       else
         next_state=open
         next_state=open

+ 1 - 1
docs/modules/ROOT/images/solutions/single-button-toggle/config.yaml

@@ -16,7 +16,7 @@ actions:
     shell: |
     shell: |
       set -e
       set -e
       entity_file="${{ WATER_VALVE_ENTITY_FILE }}"
       entity_file="${{ WATER_VALVE_ENTITY_FILE }}"
-      if grep -Eq "^  state: +[\"']?open[\"']? *$" "$entity_file"; then
+      if grep -Eq "^  state: +[\"']?open[\"']?( +#.*)? *$" "$entity_file"; then
         next_state=closed
         next_state=closed
       else
       else
         next_state=open
         next_state=open

+ 1 - 1
docs/modules/ROOT/pages/solutions/single-button-toggle/index.adoc

@@ -23,7 +23,7 @@ a| image::solutions/single-button-toggle/dashboard-open.png[]
 * The **Toggle valve** action's icon is an `<img>` tag that uses `{{ .CurrentEntity.state }}` as the file name, so state `closed` shows `closed.png` and state `open` shows `open.png`.
 * The **Toggle valve** action's icon is an `<img>` tag that uses `{{ .CurrentEntity.state }}` as the file name, so state `closed` shows `closed.png` and state `open` shows `open.png`.
 * The action has no `enabledExpression`, so it is never disabled.
 * The action has no `enabledExpression`, so it is never disabled.
 * When it runs, the action reads the current state from the entity file, works out the opposite state, and changes the `state:` line in the file. OliveTin watches entity files, so the dashboard and the icon update as soon as the file changes.
 * When it runs, the action reads the current state from the entity file, works out the opposite state, and changes the `state:` line in the file. OliveTin watches entity files, so the dashboard and the icon update as soon as the file changes.
-* Each execution reads the state from the file, not from the dashboard, so a press that runs straight after another still flips the valve, even before OliveTin has reloaded the entity. The state may be written as `open` or `"open"`.
+* Each execution reads the state from the file, not from the dashboard, so a press that runs straight after another still flips the valve, even before OliveTin has reloaded the entity. The state may be written as `open` or `"open"`, and may be followed by a YAML comment.
 * OliveTin runs one execution of an action at a time by default (`maxConcurrent: 1`). A press while the action is still running is blocked, not queued, so it does not flip the valve. Press again once the first execution has finished.
 * OliveTin runs one execution of an action at a time by default (`maxConcurrent: 1`). A press while the action is still running is blocked, not queued, so it does not flip the valve. Press again once the first execution has finished.
 
 
 == Icons
 == Icons

+ 11 - 3
service/internal/filehelper/file_change_notify.go

@@ -62,6 +62,10 @@ type watchContext struct {
 	// different directory to watchedPath, so in-place edits of a symlink's
 	// different directory to watchedPath, so in-place edits of a symlink's
 	// target are seen.
 	// target are seen.
 	resolvedDir string
 	resolvedDir string
+	// dangling is set while watchedPath cannot be resolved. Edits made in the
+	// meantime may not have been seen, so the file is reloaded once it
+	// resolves again, even if it points to the same target as before.
+	dangling bool
 
 
 	interestedEvent fsnotify.Op
 	interestedEvent fsnotify.Op
 }
 }
@@ -348,22 +352,26 @@ func refreshResolvedPath(ctx *watchContext) bool {
 }
 }
 
 
 // resolveWatchedPath updates where the watched file points. It reports
 // resolveWatchedPath updates where the watched file points. It reports
-// whether the target changed, and separately whether the file resolved at
-// all.
+// whether the target changed, or resolved again after dangling, and
+// separately whether the file resolved at all.
 func resolveWatchedPath(ctx *watchContext) (changed bool, resolved bool) {
 func resolveWatchedPath(ctx *watchContext) (changed bool, resolved bool) {
 	target, err := filepath.EvalSymlinks(ctx.watchedPath)
 	target, err := filepath.EvalSymlinks(ctx.watchedPath)
 	if err != nil {
 	if err != nil {
 		log.Debugf("fsnotify could not resolve %v: %v", ctx.watchedPath, err)
 		log.Debugf("fsnotify could not resolve %v: %v", ctx.watchedPath, err)
 		watchDanglingTargetDir(ctx)
 		watchDanglingTargetDir(ctx)
+		ctx.dangling = true
 		return false, false
 		return false, false
 	}
 	}
 
 
+	recovered := ctx.dangling
+	ctx.dangling = false
+
 	// The target's directory is watched again even when the target has not
 	// The target's directory is watched again even when the target has not
 	// changed, because a dangling symlink in between may have moved the extra
 	// changed, because a dangling symlink in between may have moved the extra
 	// watch to the directory it pointed into.
 	// watch to the directory it pointed into.
 	watchResolvedDir(ctx, filepath.Dir(target))
 	watchResolvedDir(ctx, filepath.Dir(target))
 
 
-	if target == ctx.resolvedPath {
+	if target == ctx.resolvedPath && !recovered {
 		return false, true
 		return false, true
 	}
 	}
 
 

+ 28 - 0
service/internal/filehelper/file_watch_symlink_test.go

@@ -237,6 +237,34 @@ func TestWatchFileWriteKeepsWatchingTargetAfterDanglingLinkIsUndone(t *testing.T
 	recorder.expectOneCall(t)
 	recorder.expectOneCall(t)
 }
 }
 
 
+// The link points away to a missing file, the old target is edited while the
+// link dangles, then the missing file appears as a link back to the old
+// target. The resolved path is the same as before, but the content changed.
+func TestWatchFileWriteReloadsWhenDanglingLinkResolvesToSameTarget(t *testing.T) {
+	skipWithoutSymlinks(t)
+
+	linkDir, firstDir, secondDir := t.TempDir(), t.TempDir(), t.TempDir()
+	first := filepath.Join(firstDir, "entities.yaml")
+	writeFile(t, first, "a: 1\n")
+
+	path := filepath.Join(linkDir, "entities.yaml")
+	require.NoError(t, os.Symlink(first, path))
+	recorder := watchFileForTest(t, path)
+
+	second := filepath.Join(secondDir, "entities.yaml")
+	temporary := filepath.Join(linkDir, "entities.yaml.tmp")
+	require.NoError(t, os.Symlink(second, temporary))
+	require.NoError(t, os.Rename(temporary, path))
+	recorder.expectNone(t)
+
+	writeFile(t, first, "a: 2\n")
+	recorder.expectNone(t)
+
+	require.NoError(t, os.Symlink(first, second))
+	recorder.expectOneCall(t)
+	assert.Equal(t, "a: 2\n", readFile(t, path))
+}
+
 func TestWatchFileWriteReloadsRenameSave(t *testing.T) {
 func TestWatchFileWriteReloadsRenameSave(t *testing.T) {
 	path := filepath.Join(t.TempDir(), "entities.yaml")
 	path := filepath.Join(t.TempDir(), "entities.yaml")
 	writeFile(t, path, "a: 1\n")
 	writeFile(t, path, "a: 1\n")

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

@@ -4,6 +4,7 @@ import (
 	"net/http"
 	"net/http"
 	"os"
 	"os"
 	"path"
 	"path"
+	"strings"
 
 
 	log "github.com/sirupsen/logrus"
 	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,
 // (webUIDir) do not hash their asset names at all. Without Cache-Control,
 // browsers cache responses that only carry Last-Modified heuristically, and
 // browsers cache responses that only carry Last-Modified heuristically, and
 // can keep an old UI after an upgrade. no-cache makes them revalidate every
 // 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"
 const webuiCacheControl = "no-cache"
 
 
 func (s *webUIServer) handleWebui(w http.ResponseWriter, r *http.Request) {
 func (s *webUIServer) handleWebui(w http.ResponseWriter, r *http.Request) {
 	w.Header().Set("Cache-Control", webuiCacheControl)
 	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)
 	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 {
 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 {
 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) {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		w.Header().Set("Cache-Control", webuiCacheControl)
 		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"
 	"os"
 	"path/filepath"
 	"path/filepath"
 	"testing"
 	"testing"
+	"time"
 
 
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
 	"github.com/stretchr/testify/require"
+
+	config "github.com/OliveTin/OliveTin/internal/config"
 )
 )
 
 
 func TestHandleWebuiSetsCacheControl(t *testing.T) {
 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, http.StatusOK, rec.Code, p)
 		assert.Equal(t, "no-cache", rec.Header().Get("Cache-Control"), 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
+}