Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
02a0a36dc3 | ||
|
|
5a430c08f4 | ||
|
|
54e8fd5fed | ||
|
|
70460e4170 | ||
|
|
834493a4f5 | ||
|
|
a49eec909c |
No files matched your search
@@ -14,3 +14,4 @@ CORS_ALLOWED_ORIGINS=
|
||||
AUTH_RATE_LIMIT_MAX_ATTEMPTS=5
|
||||
AUTH_RATE_LIMIT_WINDOW_SECONDS=60
|
||||
TRUSTED_PROXIES=
|
||||
UPDATE_FEED_URL=https://git.floriansylvain.fr
|
||||
@@ -20,5 +20,10 @@ build-errors.log
|
||||
uploadedImages/
|
||||
*.exe
|
||||
|
||||
# AI fest
|
||||
.claude/
|
||||
CLAUDE.md
|
||||
.codex/
|
||||
.agents/
|
||||
AGENTS.md
|
||||
codex-workflow.md
|
||||
+25
-2
@@ -122,14 +122,37 @@ tasks:
|
||||
- go build -trimpath -ldflags "{{.LDFLAGS}}" -o bin/{{.BINARY}}{{exeExt}} ./cmd/server
|
||||
|
||||
release:
|
||||
desc: Cross-compile production binaries for all release targets → bin/
|
||||
deps: [build:web]
|
||||
desc: Cross-compile and sign production binaries for all release targets → bin/ (needs RELEASE_SIGNING_KEY)
|
||||
cmds:
|
||||
- task: release:check
|
||||
- task: build:web
|
||||
- for: { var: RELEASE_TARGETS }
|
||||
task: build:target
|
||||
vars:
|
||||
GOOS: '{{index (splitList "/" .ITEM) 0}}'
|
||||
GOARCH: '{{index (splitList "/" .ITEM) 1}}'
|
||||
- go run ./cmd/releasesign checksums bin --match "{{.BINARY}}_{{.VERSION}}_*"
|
||||
- go run ./cmd/releasesign sign bin/checksums.txt
|
||||
- go run ./cmd/releasesign verify bin/checksums.txt
|
||||
|
||||
release:check:
|
||||
internal: true
|
||||
cmds:
|
||||
- cmd: 'test -n "$RELEASE_SIGNING_KEY" || { echo "RELEASE_SIGNING_KEY is not set. Point it at the private release key file (see task release:keygen)." >&2; exit 1; }'
|
||||
silent: true
|
||||
- cmd: 'test -f "$RELEASE_SIGNING_KEY" || { echo "RELEASE_SIGNING_KEY points to a missing file: $RELEASE_SIGNING_KEY" >&2; exit 1; }'
|
||||
silent: true
|
||||
- mkdir -p tmp
|
||||
- echo probe > tmp/release-probe.txt
|
||||
- defer: rm -f tmp/release-probe.txt tmp/release-probe.txt.sig
|
||||
- go run ./cmd/releasesign sign tmp/release-probe.txt
|
||||
|
||||
release:keygen:
|
||||
desc: One-time release key pair. Usage, task release:keygen -- <private key path outside the repository>
|
||||
cmds:
|
||||
- cmd: 'test -n "{{.CLI_ARGS}}" || { echo "usage: task release:keygen -- <private key path outside the repository>" >&2; exit 1; }'
|
||||
silent: true
|
||||
- go run ./cmd/releasesign keygen {{.CLI_ARGS}}
|
||||
|
||||
build:target:
|
||||
internal: true
|
||||
|
||||
+114
-1
@@ -5,16 +5,22 @@ import (
|
||||
domainImage "RenewCMS/internal/domain/image"
|
||||
domainInvite "RenewCMS/internal/domain/invite"
|
||||
domainMail "RenewCMS/internal/domain/mail"
|
||||
domainUpdate "RenewCMS/internal/domain/update"
|
||||
domainUser "RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/config"
|
||||
"RenewCMS/internal/infrastructure/hashing"
|
||||
"RenewCMS/internal/infrastructure/mailer"
|
||||
"RenewCMS/internal/infrastructure/persistence/models"
|
||||
persistence "RenewCMS/internal/infrastructure/persistence/repositories"
|
||||
"RenewCMS/internal/infrastructure/update"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"crypto/ed25519"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
@@ -51,6 +57,11 @@ type UseCases struct {
|
||||
MergeMediaUseCase *useCases.MergeMediaUseCase
|
||||
GetMediaUsageUseCase *useCases.GetMediaUsageUseCase
|
||||
GetSettingsUseCase *useCases.GetSettingsUseCase
|
||||
GetUpdateStatusUseCase *useCases.GetUpdateStatusUseCase
|
||||
CheckForUpdateUseCase *useCases.CheckForUpdateUseCase
|
||||
StartUpdateDownloadUseCase *useCases.StartUpdateDownloadUseCase
|
||||
RequestRestartUseCase *useCases.RequestRestartUseCase
|
||||
RecordRunningInfoUseCase *useCases.RecordRunningInfoUseCase
|
||||
}
|
||||
|
||||
type Repositories struct {
|
||||
@@ -59,9 +70,27 @@ type Repositories struct {
|
||||
ImageRepo domainImage.Repository
|
||||
InviteRepo domainInvite.Repository
|
||||
MailRepo domainMail.Repository
|
||||
ReleaseFeed domainUpdate.ReleaseFeed
|
||||
UpdateStore domainUpdate.StatusStore
|
||||
UpdateJobs domainUpdate.JobStore
|
||||
UpdateHelper domainUpdate.HelperDetector
|
||||
AssetFetcher domainUpdate.AssetFetcher
|
||||
SignatureVerifier domainUpdate.SignatureVerifier
|
||||
StagedRunner domainUpdate.StagedBinaryRunner
|
||||
DatabaseBackup domainUpdate.DatabaseBackup
|
||||
UpdateResults domainUpdate.ResultStore
|
||||
RestartRequests domainUpdate.RestartRequestStore
|
||||
RunningInfo domainUpdate.RunningInfoStore
|
||||
}
|
||||
|
||||
const sqliteBusyTimeoutMs = 5000
|
||||
const (
|
||||
sqliteBusyTimeoutMs = 5000
|
||||
updateStatusFileName = "update-status.json"
|
||||
updateJobFileName = "update-job.json"
|
||||
updateHelperFileName = "update-helper.json"
|
||||
updatesDirName = "updates"
|
||||
backupsDirName = "backups"
|
||||
)
|
||||
|
||||
func SQLiteDSN(dbName string) string {
|
||||
return fmt.Sprintf("%s?_pragma=busy_timeout(%d)", dbName, sqliteBusyTimeoutMs)
|
||||
@@ -91,13 +120,33 @@ func getDb(dbName string, uploadDir string) *gorm.DB {
|
||||
return db
|
||||
}
|
||||
|
||||
func releasePublicKey() ed25519.PublicKey {
|
||||
key, err := update.EmbeddedPublicKey()
|
||||
if err != nil {
|
||||
panic("Unable to read the embedded release key: " + err.Error())
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
func getRepositories(db *gorm.DB, settings config.Settings) *Repositories {
|
||||
dataDir := filepath.Dir(settings.DBFile)
|
||||
return &Repositories{
|
||||
ArticleRepo: persistence.NewArticleRepository(db),
|
||||
UserRepo: persistence.NewUserRepository(db),
|
||||
ImageRepo: persistence.NewImageRepository(db, settings.UploadDir),
|
||||
InviteRepo: persistence.NewInviteRepository(db),
|
||||
MailRepo: mailer.NewMailRepository(settings.Smtp),
|
||||
ReleaseFeed: update.NewGiteaReleaseFeed(settings.UpdateFeedURL),
|
||||
UpdateStore: update.NewJSONStatusStore(filepath.Join(dataDir, updateStatusFileName)),
|
||||
UpdateJobs: update.NewJSONJobStore(filepath.Join(dataDir, updateJobFileName)),
|
||||
UpdateHelper: update.NewFileHelperDetector(filepath.Join(dataDir, updateHelperFileName)),
|
||||
AssetFetcher: update.NewHTTPAssetFetcher(settings.UpdateFeedURL),
|
||||
SignatureVerifier: update.NewEd25519SignatureVerifier(releasePublicKey()),
|
||||
StagedRunner: update.NewExecStagedBinaryRunner(),
|
||||
DatabaseBackup: update.NewSQLiteDatabaseBackup(db, filepath.Join(dataDir, backupsDirName), time.Now),
|
||||
UpdateResults: update.NewJSONResultStore(filepath.Join(dataDir, domainUpdate.ResultFileName)),
|
||||
RestartRequests: update.NewJSONRestartRequestStore(filepath.Join(dataDir, domainUpdate.RestartRequestFileName)),
|
||||
RunningInfo: update.NewJSONRunningInfoStore(filepath.Join(dataDir, domainUpdate.RunningInfoFileName)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,9 +183,34 @@ func getUseCases(repos *Repositories, settings config.Settings) *UseCases {
|
||||
MergeMediaUseCase: useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo),
|
||||
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo),
|
||||
GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version),
|
||||
GetUpdateStatusUseCase: useCases.NewGetUpdateStatusUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, time.Now),
|
||||
CheckForUpdateUseCase: useCases.NewCheckForUpdateUseCase(repos.ReleaseFeed, repos.UpdateStore, settings.Version, time.Now),
|
||||
StartUpdateDownloadUseCase: startUpdateDownloadUseCase(repos, settings),
|
||||
RequestRestartUseCase: useCases.NewRequestRestartUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, time.Now),
|
||||
RecordRunningInfoUseCase: useCases.NewRecordRunningInfoUseCase(repos.RunningInfo, settings.Version, os.Getpid(), time.Now),
|
||||
}
|
||||
}
|
||||
|
||||
func startUpdateDownloadUseCase(repos *Repositories, settings config.Settings) *useCases.StartUpdateDownloadUseCase {
|
||||
return useCases.NewStartUpdateDownloadUseCase(useCases.StartUpdateDownloadDependencies{
|
||||
Store: repos.UpdateStore,
|
||||
Jobs: repos.UpdateJobs,
|
||||
Helper: repos.UpdateHelper,
|
||||
Results: repos.UpdateResults,
|
||||
Requests: repos.RestartRequests,
|
||||
Fetcher: repos.AssetFetcher,
|
||||
Verifier: repos.SignatureVerifier,
|
||||
Runner: repos.StagedRunner,
|
||||
Backup: repos.DatabaseBackup,
|
||||
Staging: update.NewOSStagingArea(filepath.Join(filepath.Dir(settings.DBFile), updatesDirName)),
|
||||
Logger: log.Default(),
|
||||
CurrentVersion: settings.Version,
|
||||
Platform: domainUpdate.Platform{OS: runtime.GOOS, Arch: runtime.GOARCH},
|
||||
FeedURL: settings.UpdateFeedURL,
|
||||
Now: time.Now,
|
||||
})
|
||||
}
|
||||
|
||||
func InitContainer(settings config.Settings) (*UseCases, func() error) {
|
||||
db := getDb(settings.DBFile, settings.UploadDir)
|
||||
repos := getRepositories(db, settings)
|
||||
@@ -152,3 +226,42 @@ func closeDb(db *gorm.DB) func() error {
|
||||
return sqlDb.Close()
|
||||
}
|
||||
}
|
||||
|
||||
type BrowserUpdateCommands struct {
|
||||
Enable *useCases.EnableBrowserUpdatesUseCase
|
||||
Disable *useCases.DisableBrowserUpdatesUseCase
|
||||
}
|
||||
|
||||
func InitBrowserUpdateCommands() *BrowserUpdateCommands {
|
||||
units := update.NewSystemdUnits()
|
||||
dependencies := useCases.ManageBrowserUpdatesDependencies{
|
||||
Probe: update.NewSystemMachineProbe(),
|
||||
Locator: units,
|
||||
Units: units,
|
||||
Manager: update.NewSystemctlControl(domainUpdate.ServiceUnitName),
|
||||
Status: update.NewJSONHelperStatusWriter(),
|
||||
Now: time.Now,
|
||||
}
|
||||
return &BrowserUpdateCommands{
|
||||
Enable: useCases.NewEnableBrowserUpdatesUseCase(dependencies),
|
||||
Disable: useCases.NewDisableBrowserUpdatesUseCase(dependencies),
|
||||
}
|
||||
}
|
||||
|
||||
func InitApplyUpdateCommand(options domainUpdate.InstallOptions) *useCases.ApplyRestartRequestUseCase {
|
||||
layout := domainUpdate.HelperLayout{DataDir: options.DataDir, BinaryPath: options.Binary}
|
||||
files := update.NewNoFollowFilesystem()
|
||||
return useCases.NewApplyRestartRequestUseCase(useCases.ApplyRestartRequestDependencies{
|
||||
Requests: update.NewFSRestartRequestStore(files, layout.RestartRequestPath()),
|
||||
Results: update.NewFSResultStore(files, layout.ResultPath()),
|
||||
Running: update.NewJSONRunningInfoStore(filepath.Join(options.DataDir, domainUpdate.RunningInfoFileName)),
|
||||
Files: files,
|
||||
Service: update.NewSystemctlControl(options.Service),
|
||||
Health: update.NewHTTPHealthChecker(options.Port),
|
||||
Verifier: update.NewEd25519SignatureVerifier(releasePublicKey()),
|
||||
Clock: update.NewSystemClock(),
|
||||
Logger: log.Default(),
|
||||
Layout: layout,
|
||||
Platform: domainUpdate.Platform{OS: runtime.GOOS, Arch: runtime.GOARCH},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
"RenewCMS/api/pkg/claims"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const restartBodyLimitBytes = 1024
|
||||
|
||||
type Handler struct {
|
||||
GetUpdateStatusUseCase *useCases.GetUpdateStatusUseCase
|
||||
CheckForUpdateUseCase *useCases.CheckForUpdateUseCase
|
||||
StartUpdateDownloadUseCase *useCases.StartUpdateDownloadUseCase
|
||||
RequestRestartUseCase *useCases.RequestRestartUseCase
|
||||
GetUserUseCase *useCases.GetUserUseCase
|
||||
}
|
||||
|
||||
type restartRequest struct {
|
||||
Kind *string `json:"kind" validate:"omitempty,oneof=update restart"`
|
||||
}
|
||||
|
||||
func NewHandler(getStatus *useCases.GetUpdateStatusUseCase, checkForUpdate *useCases.CheckForUpdateUseCase, startDownload *useCases.StartUpdateDownloadUseCase, requestRestart *useCases.RequestRestartUseCase, getUser *useCases.GetUserUseCase) *Handler {
|
||||
return &Handler{
|
||||
GetUpdateStatusUseCase: getStatus,
|
||||
CheckForUpdateUseCase: checkForUpdate,
|
||||
StartUpdateDownloadUseCase: startDownload,
|
||||
RequestRestartUseCase: requestRestart,
|
||||
GetUserUseCase: getUser,
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) GetStatus(w http.ResponseWriter, r *http.Request) {
|
||||
isOwner, ok := h.isOwner(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeStatus(w, http.StatusOK, h.GetUpdateStatusUseCase.GetStatus(isOwner))
|
||||
}
|
||||
|
||||
func (h *Handler) Check(w http.ResponseWriter, r *http.Request) {
|
||||
if _, err := h.CheckForUpdateUseCase.Check(); err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
isOwner, ok := h.isOwner(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeStatus(w, http.StatusOK, h.GetUpdateStatusUseCase.GetStatus(isOwner))
|
||||
}
|
||||
|
||||
func (h *Handler) Download(w http.ResponseWriter, _ *http.Request) {
|
||||
status, err := h.StartUpdateDownloadUseCase.Start()
|
||||
if err != nil {
|
||||
writeDownloadError(w, err)
|
||||
return
|
||||
}
|
||||
writeStatus(w, http.StatusAccepted, status)
|
||||
}
|
||||
|
||||
func (h *Handler) Restart(w http.ResponseWriter, r *http.Request) {
|
||||
kind, ok := decodeRestartKind(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
userId, ok := claims.UserId(r)
|
||||
if !ok {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
status, err := h.RequestRestartUseCase.Request(userId, kind)
|
||||
if err != nil {
|
||||
writeRestartError(w, err)
|
||||
return
|
||||
}
|
||||
writeStatus(w, http.StatusAccepted, status)
|
||||
}
|
||||
|
||||
func decodeRestartKind(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, restartBodyLimitBytes))
|
||||
if err != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return "", false
|
||||
}
|
||||
if strings.TrimSpace(string(body)) == "" {
|
||||
return "", true
|
||||
}
|
||||
var request restartRequest
|
||||
if err := json.Unmarshal(body, &request); err != nil || validator.Validate.Struct(request) != nil {
|
||||
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||
return "", false
|
||||
}
|
||||
if request.Kind == nil {
|
||||
return "", true
|
||||
}
|
||||
return *request.Kind, true
|
||||
}
|
||||
|
||||
func (h *Handler) isOwner(w http.ResponseWriter, r *http.Request) (bool, bool) {
|
||||
userId, ok := claims.UserId(r)
|
||||
if !ok {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
return false, false
|
||||
}
|
||||
currentUser, err := h.GetUserUseCase.GetUser(userId)
|
||||
if err != nil {
|
||||
if errors.Is(err, user.ErrUserNotFound) {
|
||||
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||
return false, false
|
||||
}
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return false, false
|
||||
}
|
||||
return currentUser.Role == user.RoleOwner, true
|
||||
}
|
||||
|
||||
func writeDownloadError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotPrepared):
|
||||
http.Error(w, apperr.UpdateNotPreparedErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, domain.ErrJobInProgress), errors.Is(err, domain.ErrRestartPending):
|
||||
http.Error(w, apperr.UpdateAlreadyRunningErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, domain.ErrNothingToUpdate):
|
||||
http.Error(w, apperr.NothingToUpdateErrorMessage, http.StatusBadRequest)
|
||||
case errors.Is(err, domain.ErrPreflightRefused):
|
||||
http.Error(w, apperr.UpdateRefusedErrorMessage, http.StatusUnprocessableEntity)
|
||||
default:
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func writeRestartError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotPrepared):
|
||||
http.Error(w, apperr.UpdateNotPreparedErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, domain.ErrJobInProgress), errors.Is(err, domain.ErrRestartPending):
|
||||
http.Error(w, apperr.UpdateAlreadyRunningErrorMessage, http.StatusConflict)
|
||||
case errors.Is(err, domain.ErrRestartKindMismatch):
|
||||
http.Error(w, apperr.UpdateRestartMismatchErrorMessage, http.StatusConflict)
|
||||
default:
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
func writeStatus(w http.ResponseWriter, code int, status domain.UpdateStatus) {
|
||||
body, err := json.Marshal(status)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(code)
|
||||
_, _ = w.Write(body)
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package middleware
|
||||
|
||||
import (
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
"RenewCMS/api/pkg/claims"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
@@ -14,12 +15,25 @@ type rateLimitWindow struct {
|
||||
}
|
||||
|
||||
func NewRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
|
||||
return newKeyedRateLimiter(maxAttempts, window, func(r *http.Request) string { return r.RemoteAddr })
|
||||
}
|
||||
|
||||
func NewUserRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
|
||||
return newKeyedRateLimiter(maxAttempts, window, userRateLimitKey)
|
||||
}
|
||||
|
||||
func userRateLimitKey(r *http.Request) string {
|
||||
userId, _ := claims.UserId(r)
|
||||
return strconv.FormatUint(uint64(userId), 10)
|
||||
}
|
||||
|
||||
func newKeyedRateLimiter(maxAttempts int, window time.Duration, keyOf func(*http.Request) string) func(http.Handler) http.Handler {
|
||||
var mu sync.Mutex
|
||||
windows := make(map[string]*rateLimitWindow)
|
||||
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
retryAfter, allowed := recordAttempt(&mu, windows, r.RemoteAddr, maxAttempts, window)
|
||||
retryAfter, allowed := recordAttempt(&mu, windows, keyOf(r), maxAttempts, window)
|
||||
if !allowed {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
|
||||
http.Error(w, apperr.TooManyRequestsErrorMessage, http.StatusTooManyRequests)
|
||||
|
||||
@@ -29,3 +29,8 @@ const MediaQueryErrorMessage = "The media query is invalid."
|
||||
const MediaFilenameErrorMessage = "Enter a filename."
|
||||
const MediaMergeConflictErrorMessage = "Some of the images to merge changed. Refresh and try again."
|
||||
const MediaMergeRequestErrorMessage = "Choose an image to keep and at least one other image to merge into it."
|
||||
const UpdateNotPreparedErrorMessage = "This server cannot update itself yet."
|
||||
const UpdateAlreadyRunningErrorMessage = "An update is already running or waiting to be installed."
|
||||
const NothingToUpdateErrorMessage = "There is nothing to update."
|
||||
const UpdateRefusedErrorMessage = "This update cannot be downloaded."
|
||||
const UpdateRestartMismatchErrorMessage = "The update state changed. Reload the page and try again."
|
||||
@@ -7,11 +7,13 @@ import (
|
||||
"RenewCMS/api/handlers/media"
|
||||
"RenewCMS/api/handlers/settings"
|
||||
"RenewCMS/api/handlers/staticimages"
|
||||
"RenewCMS/api/handlers/update"
|
||||
"RenewCMS/api/handlers/user"
|
||||
"RenewCMS/api/middleware"
|
||||
"RenewCMS/internal/infrastructure/config"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/MadAppGang/httplog"
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -129,6 +131,40 @@ func NewSettingsRouter(container *UseCases) http.Handler {
|
||||
return r
|
||||
}
|
||||
|
||||
const (
|
||||
updateCheckMaxAttempts = 5
|
||||
updateCheckWindow = time.Minute
|
||||
updateDownloadMaxAttempts = 5
|
||||
updateDownloadWindow = time.Minute
|
||||
)
|
||||
|
||||
func NewSystemRouter(container *UseCases) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
updateHandler := update.NewHandler(container.GetUpdateStatusUseCase, container.CheckForUpdateUseCase, container.StartUpdateDownloadUseCase, container.RequestRestartUseCase, container.GetUserUseCase)
|
||||
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||
r.Get("/update", updateHandler.GetStatus)
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||
r.Use(middleware.NewUserRateLimiter(updateCheckMaxAttempts, updateCheckWindow))
|
||||
r.Post("/update/check", updateHandler.Check)
|
||||
})
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||
r.Use(middleware.NewUserRateLimiter(updateDownloadMaxAttempts, updateDownloadWindow))
|
||||
r.Post("/update/download", updateHandler.Download)
|
||||
})
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||
r.Post("/update/restart", updateHandler.Restart)
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
func NewMediaRouter(container *UseCases) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
@@ -162,6 +198,7 @@ func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
|
||||
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
|
||||
r.Mount("/settings", NewSettingsRouter(container))
|
||||
r.Mount("/media", NewMediaRouter(container))
|
||||
r.Mount("/system", NewSystemRouter(container))
|
||||
r.Mount("/auth", NewAuthRouter(container, settings.IsProduction(), settings.AuthRateLimit, settings.TrustedProxies))
|
||||
|
||||
return r
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/infrastructure/update/releasesign"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
os.Exit(releasesign.Run(os.Args[1:], os.Stdout, os.Stderr))
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"RenewCMS/api"
|
||||
"RenewCMS/internal/domain/update"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
)
|
||||
|
||||
const (
|
||||
enableCommand = "enable-browser-updates"
|
||||
disableCommand = "disable-browser-updates"
|
||||
applyCommand = "apply-update"
|
||||
|
||||
exitOK = 0
|
||||
exitError = 1
|
||||
exitUsage = 2
|
||||
|
||||
usageText = "usage: renewcms [--version]\n" +
|
||||
" renewcms enable-browser-updates [--service NAME] [--binary PATH] [--data-dir DIR] [--port PORT]\n" +
|
||||
" renewcms disable-browser-updates [--service NAME] [--data-dir DIR]\n" +
|
||||
" renewcms apply-update --binary PATH --data-dir DIR [--service NAME] [--port PORT]"
|
||||
|
||||
applyNeedsFlagsMessage = "apply-update needs --binary and --data-dir."
|
||||
)
|
||||
|
||||
func runCommand(args []string, stdout io.Writer, stderr io.Writer) int {
|
||||
name, rest := args[0], args[1:]
|
||||
switch name {
|
||||
case enableCommand:
|
||||
return withOptions(name, rest, stderr, func(options update.InstallOptions) int {
|
||||
message, err := api.InitBrowserUpdateCommands().Enable.Enable(options)
|
||||
return printOutcome(stdout, stderr, message, err)
|
||||
})
|
||||
case disableCommand:
|
||||
return withOptions(name, rest, stderr, func(options update.InstallOptions) int {
|
||||
message, err := api.InitBrowserUpdateCommands().Disable.Disable(options)
|
||||
return printOutcome(stdout, stderr, message, err)
|
||||
})
|
||||
case applyCommand:
|
||||
return withOptions(name, rest, stderr, func(options update.InstallOptions) int {
|
||||
return apply(options, stderr)
|
||||
})
|
||||
}
|
||||
fmt.Fprintln(stderr, usageText)
|
||||
return exitUsage
|
||||
}
|
||||
|
||||
func withOptions(name string, args []string, stderr io.Writer, run func(update.InstallOptions) int) int {
|
||||
flags := flag.NewFlagSet(name, flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
var options update.InstallOptions
|
||||
flags.StringVar(&options.Service, "service", "", "systemd service name of RenewCMS")
|
||||
flags.StringVar(&options.Binary, "binary", "", "path of the RenewCMS binary")
|
||||
flags.StringVar(&options.DataDir, "data-dir", "", "directory that holds DB_FILE")
|
||||
flags.StringVar(&options.Port, "port", "", "port RenewCMS listens on")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return exitUsage
|
||||
}
|
||||
return run(options)
|
||||
}
|
||||
|
||||
func printOutcome(stdout io.Writer, stderr io.Writer, message string, err error) int {
|
||||
if err != nil {
|
||||
fmt.Fprintln(stderr, err)
|
||||
return exitError
|
||||
}
|
||||
fmt.Fprintln(stdout, message)
|
||||
return exitOK
|
||||
}
|
||||
|
||||
func apply(options update.InstallOptions, stderr io.Writer) int {
|
||||
if options.Binary == "" || options.DataDir == "" {
|
||||
fmt.Fprintln(stderr, applyNeedsFlagsMessage)
|
||||
return exitUsage
|
||||
}
|
||||
if options.Service == "" {
|
||||
options.Service = update.DefaultService
|
||||
}
|
||||
if options.Port == "" {
|
||||
options.Port = update.DefaultPort
|
||||
}
|
||||
if err := api.InitApplyUpdateCommand(options).Apply(); err != nil {
|
||||
log.Printf("apply-update failed: %v", err)
|
||||
return exitError
|
||||
}
|
||||
return exitOK
|
||||
}
|
||||
+24
-5
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
@@ -47,9 +48,19 @@ var envDefaults = map[string]string{
|
||||
"AUTH_RATE_LIMIT_MAX_ATTEMPTS": "5",
|
||||
"AUTH_RATE_LIMIT_WINDOW_SECONDS": "60",
|
||||
"TRUSTED_PROXIES": "",
|
||||
"UPDATE_FEED_URL": "https://git.floriansylvain.fr",
|
||||
}
|
||||
|
||||
const versionFlag = "--version"
|
||||
|
||||
func main() {
|
||||
if len(os.Args) == 2 && os.Args[1] == versionFlag {
|
||||
fmt.Println(version)
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 {
|
||||
os.Exit(runCommand(os.Args[1:], os.Stdout, os.Stderr))
|
||||
}
|
||||
if err := run(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
@@ -69,7 +80,7 @@ func run() error {
|
||||
validator.InitValidator()
|
||||
|
||||
server := newServer(api.InitRoutes(container, settings), settings)
|
||||
return serveUntilStopped(server, settings)
|
||||
return serveUntilStopped(server, settings, container.RecordRunningInfoUseCase.Record)
|
||||
}
|
||||
|
||||
func initEnvVariables() {
|
||||
@@ -120,12 +131,12 @@ func newServer(handler http.Handler, settings config.Settings) *http.Server {
|
||||
}
|
||||
}
|
||||
|
||||
func serveUntilStopped(server *http.Server, settings config.Settings) error {
|
||||
func serveUntilStopped(server *http.Server, settings config.Settings, recordRunning func() error) error {
|
||||
stopSignal, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
serverErr := make(chan error, 1)
|
||||
go listen(server, serverErr, settings)
|
||||
go listen(server, serverErr, settings, recordRunning)
|
||||
|
||||
select {
|
||||
case err := <-serverErr:
|
||||
@@ -135,9 +146,17 @@ func serveUntilStopped(server *http.Server, settings config.Settings) error {
|
||||
}
|
||||
}
|
||||
|
||||
func listen(server *http.Server, serverErr chan<- error, settings config.Settings) {
|
||||
func listen(server *http.Server, serverErr chan<- error, settings config.Settings, recordRunning func() error) {
|
||||
listener, err := net.Listen("tcp", server.Addr)
|
||||
if err != nil {
|
||||
serverErr <- err
|
||||
return
|
||||
}
|
||||
if err := recordRunning(); err != nil {
|
||||
log.Printf("WARNING: could not write the running-version file: %v", err)
|
||||
}
|
||||
log.Printf("RenewCMS %s (%s) listening on %s, public URL %s", version, settings.Environment, server.Addr, settings.PublicURL)
|
||||
err := server.ListenAndServe()
|
||||
err = server.Serve(listener)
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
err = nil
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ Copy [`.env.example`](../.env.example) to `.env` to get started. When a required
|
||||
| `AUTH_RATE_LIMIT_MAX_ATTEMPTS` | `5` | Maximum number of requests a single client IP may send to `POST /v1/auth/login`, `POST /v1/auth/password-reset` or the invite-accept pair (`GET /v1/auth/invite` and `POST /v1/auth/invite/accept`, sharing one counter) within the window, tracked independently per route. |
|
||||
| `AUTH_RATE_LIMIT_WINDOW_SECONDS` | `60` | Length, in seconds, of the fixed rate-limit window for the routes above. |
|
||||
| `TRUSTED_PROXIES` | *(empty)* | Semicolon-separated list of exact IP addresses (no CIDR) of reverse proxies allowed to supply the client IP via `X-Real-IP` for the rate limiting of the routes above. When a request's connection address is not in this list, any `X-Real-IP` or `X-Forwarded-For` header it sends is ignored and the connection address is used instead. See [deployment.md](deployment.md). |
|
||||
| `UPDATE_FEED_URL` | `https://git.floriansylvain.fr` | Base URL of the Gitea server that publishes RenewCMS releases. The Settings page asks `{UPDATE_FEED_URL}/api/v1/repos/fsylvain/RenewCMS/releases` when the owner checks for updates. The last result is kept in `update-status.json`, next to `DB_FILE`. |
|
||||
|
||||
Relative paths are resolved against the process's working directory. In production, use absolute paths (see [deployment.md](deployment.md)).
|
||||
|
||||
|
||||
@@ -19,8 +19,72 @@ task build # this OS/arch → bin/renewcms[.exe]
|
||||
task release # all targets → bin/renewcms_<version>_<os>_<arch>[.exe]
|
||||
```
|
||||
|
||||
`task release` also signs the release: it writes `bin/checksums.txt` (SHA-256 of the six binaries) and signs it into `bin/checksums.txt.sig` with an Ed25519 key. It refuses to start, before building anything, unless `RELEASE_SIGNING_KEY` points to the private key file and that key matches the public key committed as `internal/infrastructure/update/release.pub`. The one-time setup is below.
|
||||
|
||||
The frontend is built once and embedded into every binary. The binaries are static (`CGO_ENABLED=0`), so a Linux build runs on any distribution. The version comes from `git describe`: tag a release (`git tag v1.2.0`) before building, and the binary logs its version at startup.
|
||||
|
||||
### Release signing key (maintainers, once)
|
||||
|
||||
1. Run `task release:keygen -- <path>` with a path outside the repository (for example `~/.renewcms/release.key`). The private key is written there and never leaves your machine; keygen refuses a path inside the work tree.
|
||||
2. Commit the printed public key as `internal/infrastructure/update/release.pub`. Until you do, the file holds a placeholder (32 zero bytes) and `task release` fails with a message saying so.
|
||||
3. Export `RELEASE_SIGNING_KEY=<path to the private key>` before every `task release`.
|
||||
|
||||
To check a download by hand: `go run ./cmd/releasesign verify checksums.txt`, with `checksums.txt.sig` next to it, then compare the binary's hash with the matching line of `checksums.txt`.
|
||||
|
||||
### Update checks
|
||||
|
||||
The owner's Settings page asks the release feed for the newest release (see `UPDATE_FEED_URL` in [configuration.md](configuration.md)) and keeps the last result in `update-status.json`, next to `DB_FILE`. Back it up with the rest of the data directory if you like; it is rebuilt by the next check when missing. The Settings page reports a newer version. To install it from the browser, set up [Browser updates](#browser-updates) once on the server.
|
||||
|
||||
### Update downloads
|
||||
|
||||
Once the restart helper is installed (it writes `update-helper.json` next to `DB_FILE`), the owner's Update button downloads the new binary, `checksums.txt` and `checksums.txt.sig` from the release feed host over https only, checks the ed25519 signature and the SHA-256, runs the staged binary with `--version`, copies the database into `backups/` (the last 3 copies are kept) and stages everything under `updates/<tag>/`, all next to `DB_FILE`. The job record is `update-job.json`. Nothing running is replaced and the site is not restarted by the download: the owner's Restart button does that, as described in [Browser updates](#browser-updates). `renewcms --version` prints the build version and exits.
|
||||
|
||||
### Browser updates
|
||||
|
||||
The owner's Restart button installs a downloaded update, or just restarts the site, without touching the server by hand. The app itself stays unprivileged: the systemd unit below keeps `ProtectSystem=strict` and only the data directory (the directory that holds `DB_FILE`) is writable. The only privileged code is a small helper, the same binary started as `renewcms apply-update` by a systemd service that runs as root.
|
||||
|
||||
Enable it once, on the server, as root:
|
||||
|
||||
```sh
|
||||
sudo renewcms enable-browser-updates
|
||||
```
|
||||
|
||||
The command reads the service name, the binary path and the data directory from your `renewcms.service` unit. Pass `--service`, `--binary`, `--data-dir` and `--port` to override them or when there is no such unit. The port, used by the helper to poll `/healthz`, comes from `--port`, else from `PORT` in the unit's `EnvironmentFile`, else 8080. It then:
|
||||
|
||||
- writes `renewcms-update.path` and `renewcms-update.service` next to your other units in `/etc/systemd/system` (no secret and no environment value goes into them);
|
||||
- runs `systemctl daemon-reload` and enables and starts the path unit;
|
||||
- writes `update-helper.json` in the data directory last, so the Settings page only offers Update and Restart once everything else worked.
|
||||
|
||||
Running it again rewrites the units and the status file to the current values. If a step fails, the units it wrote are removed again and `update-helper.json` is not written.
|
||||
|
||||
To undo it:
|
||||
|
||||
```sh
|
||||
sudo renewcms disable-browser-updates
|
||||
```
|
||||
|
||||
This stops and disables the path unit, removes both unit files and `update-helper.json`, and runs `systemctl daemon-reload`. The restart request, the result, the staged files and the backups stay where they are, and the Settings page goes back to "Not prepared".
|
||||
|
||||
How it works: pressing Restart makes the app write `update-restart-request.json` in the data directory. The path unit notices it and starts the helper, which deletes the request, checks the staged files again, installs the update, restarts the service and waits up to 60 seconds for the site to answer `/healthz` and for the new process to write `update-running.json`. The helper writes its outcome to `update-result.json`; the Settings page reads it. The technical reason of a failure goes to the journal only (`journalctl -u renewcms-update`).
|
||||
|
||||
Files in the data directory:
|
||||
|
||||
| File | Written by | What |
|
||||
|------|------------|------|
|
||||
| `update-restart-request.json` | the app | The request: `kind` (`update` or `restart`), `tag` (updates only), `requested_at`, `requested_by`. The helper deletes it first. |
|
||||
| `update-result.json` | the helper | The outcome: `running`, `succeeded`, `rolled_back` or `failed`, with `kind`, `tag`, `from_version`, `started_at`, `finished_at`. It stays until the next download or restart. |
|
||||
| `update-helper.json` | `enable-browser-updates` | Marks browser updates as set up (`version`, `service`, `binary`, `data_dir`, `installed_at`). |
|
||||
| `update-running.json` | the server, at every start | `version`, `pid` and `started_at` of the running process. The helper uses it to tell a new process from an old one. |
|
||||
|
||||
What is supported and what is not:
|
||||
|
||||
- Linux with systemd only. Not Windows, macOS, Docker or other init systems: there the command refuses with a clear message and the Settings page keeps showing "Not prepared".
|
||||
- Before the swap the helper copies the staged files into a private temp directory, checks the signature and the SHA-256 on that copy and installs the copy. It refuses symbolic links under `updates/` and on the request file.
|
||||
- The previous binary is kept as `<name>.previous` next to the binary, and the update download keeps a database backup in `backups/`.
|
||||
- If the new version does not come up within 60 seconds, the helper puts `<name>.previous` back, restarts the service and records `rolled_back`. If even that fails the result is `failed` and the journal says so loudly.
|
||||
- A plain restart (no update waiting) restarts the service the same way and records `succeeded` or `failed`; no binary is replaced.
|
||||
- Only the owner can press Restart. The site is unavailable for about 10 seconds.
|
||||
|
||||
## 2. Lay out the server
|
||||
|
||||
The following is a suggested layout for Linux:
|
||||
|
||||
@@ -25,7 +25,7 @@ The visual spec of record for the back-office SPA and the transactional emails,
|
||||
| [Forgot password](screens/forgot-password.md) | `/register/reset/request` | 6 | `source/RenewCMS Screens Auth.dc.html` |
|
||||
| [Reset password](screens/reset-password.md) | `/register/reset/validate?c=CODE&email=EMAIL` | 7 | `source/RenewCMS Screens Auth.dc.html` |
|
||||
| [Boot](screens/boot.md) | `any route, first load` | 1 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Home](screens/home.md) | `/home` | 4 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Home](screens/home.md) | `/home` | 6 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Articles](screens/articles.md) | `/article` | 14 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [New article](screens/new-article.md) | `modal from anywhere · /article/new` | 5 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Editor](screens/editor.md) | `/article/:id/edit` | 22 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
@@ -33,7 +33,7 @@ The visual spec of record for the back-office SPA and the transactional emails,
|
||||
| [Media picker](screens/media-picker.md) | `/article/:id/edit` (dialog) | 13 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Integration](screens/integration.md) | `/integration` | 2 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Users](screens/users.md) | `/users` | 17 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Settings](screens/settings.md) | `/settings` | 1 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Settings](screens/settings.md) | `/settings` | 25 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Profile](screens/profile.md) | `/profile` | 13 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
| [Accept invite](screens/accept-invite.md) | `/invite/accept?c=CODE` | 9 | `source/RenewCMS Screens Auth.dc.html` |
|
||||
| [Global](screens/global.md) | `any route` | 4 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||
|
||||
@@ -784,3 +784,18 @@ Exact values live in `source/MediaFrame.dc.html`. Copy and states are in [media]
|
||||
| MediaPicker | UTabs inside ImageUploader | articleId | picked(item, alt) | Editor |
|
||||
|
||||
ImageUploader (changed): it gains the Upload and Library tabs and the "Already in your library" card. The remove-image confirm becomes neutral and only detaches the image from the article.
|
||||
|
||||
## Added with Updates
|
||||
|
||||
Exact values live in `source/AppFrame.dc.html` (the Settings and Home states). Copy and states are in [settings](screens/settings.md) and [home](screens/home.md).
|
||||
|
||||
| Component | Nuxt UI base | Props | Emits | Used in |
|
||||
|---|---|---|---|---|
|
||||
| UpdatesCard | custom card, UProgress, UButton, UCollapsible | status: UpdateStatus, role | check, update, restart, copy-command | Settings |
|
||||
| UpdateStatusBlock | custom (polite live region) | tone, icon, title, text, meta | none | UpdatesCard |
|
||||
| UpdateProgress | UProgress | label, text, value or indeterminate | none | UpdatesCard |
|
||||
| ReleaseNotes | UCollapsible | version, date, items | none | UpdatesCard |
|
||||
| ServerCommand | UButton, code block | line | copy | UpdatesCard (Not prepared) |
|
||||
| RestartOverlay | custom full-page `role="status"` | title, text, startedAt, slow | reload | App shell |
|
||||
| UpdateBanner | UAlert | state: 'available'\|'ready' | go-to-settings, dismiss | Home (owner) |
|
||||
| UpdatePill | UBadge | none | none | DashboardShell Settings item (dot on mobile) |
|
||||
@@ -11,14 +11,14 @@ A global `router.beforeEach` guard reads `meta.auth`. On the first navigation it
|
||||
| `/register/validate` | AuthShell | public | VerifyPage | POST /v1/auth/verify (+ POST /login inline on 401) |
|
||||
| `/register/reset/request` | AuthShell | public | ResetRequestPage | POST /v1/auth/password-reset |
|
||||
| `/register/reset/validate` | AuthShell | public | ResetConfirmPage | POST /v1/auth/password-reset/confirm |
|
||||
| `/home` | DashboardShell | verified | HomePage | GET /v1/article/ |
|
||||
| `/home` | DashboardShell | verified | HomePage | GET /v1/article/ · GET /v1/system/update (owner, for the banner) |
|
||||
| `/article` | DashboardShell | verified | ArticlesPage | GET /v1/article/ · PATCH /{id}/publish\|unpublish · DELETE /{id} |
|
||||
| `/article/new` | DashboardShell | verified | ArticlesPage + NewArticleModal | POST /v1/article/ |
|
||||
| `/article/:id/edit` | DashboardShell | verified | EditorPage | GET /{id} · PATCH /{id} · PATCH /{id}/publish\|unpublish · GET /v1/media/ · POST /v1/media/ · DELETE /{id} |
|
||||
| `/media` | DashboardShell | verified | MediaPage | GET /v1/media/ · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage |
|
||||
| `/integration` | DashboardShell | verified | IntegrationPage | none |
|
||||
| `/users` | DashboardShell | verified | UsersPage + InviteUserModal | GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id · POST /v1/user/invite/:id/renew |
|
||||
| `/settings` | DashboardShell | verified | SettingsPage | GET /v1/settings |
|
||||
| `/settings` | DashboardShell | verified | SettingsPage | GET /v1/settings · GET /v1/system/update · POST /v1/system/update/check · POST /v1/system/update/download · POST /v1/system/update/restart |
|
||||
| `/profile` | DashboardShell | verified | ProfilePage | GET /v1/auth/me · PATCH /v1/user/me · POST /v1/auth/password-reset |
|
||||
| `/invite/accept` | AuthShell | public | AcceptInvitePage | GET /v1/auth/invite?c=* · POST /v1/auth/invite/accept* |
|
||||
| `/:pathMatch(.*)*` | either | any | NotFoundPage | none |
|
||||
|
||||
@@ -40,3 +40,17 @@ The greeting reads "Good morning, {name}", where the name is the display name wh
|
||||
- Breadcrumbs: Home (mobile title "Home")
|
||||
- Subtitle: "Here's where things stand on your site."
|
||||
- Error state for the list request
|
||||
|
||||
### Update available (owner)
|
||||
|
||||
**Trigger:** The owner only. A quiet banner above the content, and an "Update" pill on the Settings sidebar item (a dot on the menu icon on mobile, read as "Update available"). Dismissing hides the banner until the next version; the pill stays. Admins see neither.
|
||||
|
||||
- Breadcrumbs: Home (mobile title "Home")
|
||||
- Subtitle: "Here's where things stand on your site."
|
||||
- Banner: `role="region"` labelled "Update available", info tone, `circle-arrow-up` icon, title "Version 2.3.0 is available", text "Update it from Settings. It takes about 2 minutes and the site stays online.", button "Go to Settings", and a dismiss button
|
||||
|
||||
### Update ready to install (owner)
|
||||
|
||||
**Trigger:** The download is checked. The same banner changes its copy, and a dismiss comes back on the next visit because the update is waiting.
|
||||
|
||||
- Banner: success tone, `circle-check` icon, title "Version 2.3.0 is ready to install", text "Restart from Settings to finish. The site is unavailable for about 10 seconds.", button "Go to Settings"
|
||||
+111
-21
@@ -1,35 +1,125 @@
|
||||
# Settings
|
||||
|
||||
- **Route:** `/settings`
|
||||
- **API:** GET /v1/settings (not drawn, see the notes)
|
||||
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Settings" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
||||
- **API:** GET /v1/settings (version) · GET /v1/system/update · POST /v1/system/update/check · POST /v1/system/update/download · POST /v1/system/update/restart
|
||||
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Settings", drawn by `source/AppFrame.dc.html` (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
||||
|
||||
Opened from the sidebar (Settings, settings icon, after Integration) and from the mobile drawer. Every verified user sees it, owner and admins alike. For now it holds a single section, Version. Nothing on it can be edited.
|
||||
Opened from the sidebar (Settings, settings icon, after Integration) and from the mobile drawer. Every verified user sees it. It holds two sections: Version (everyone) and Updates (the owner has the buttons, admins read the status).
|
||||
|
||||
The Updates card lets a non-technical owner update the site without a terminal. **Update** downloads the new version and checks it, and changes nothing. **Restart** installs it and restarts the site (about 10 seconds). "Restart later" is simply closing the dialog or leaving the page; the update waits. A plain **Restart** appears only when no update is waiting. The state lives on the server, so any owner on any device sees the same card, and the buttons are disabled while any step runs.
|
||||
|
||||
Out of scope: choosing versions, downgrades, automatic updates, update history.
|
||||
|
||||
## The page
|
||||
|
||||
Title "Settings" and the subtitle "Workspace information.", 720 px wide at most. Page padding 32 px on desktop and `20px 16px 88px` on mobile, 20 px between the header and the card.
|
||||
Title "Settings", subtitle "Workspace information.", 720 px at most, 20 px between sections. Page padding 32 px on desktop and `20px 16px 88px` on mobile.
|
||||
|
||||
One card (`--ui-bg`, 1 px `--ui-border`, 20 px padding on desktop and 16 px on mobile), a single row with the label on the left and the value on the right, 16 px apart:
|
||||
**Version card** (unchanged): label "Version" and the running build's version in IBM Plex Mono 14 px, shown exactly as the server reports it (for example `v2.2.0-beta`).
|
||||
|
||||
**Updates card**, under it: `--ui-bg`, 1 px `--ui-border`, 20 px padding (16 px on mobile), 16 px gap. A region labelled by its heading "Updates" (`id="updates-h"`, `tabindex="-1"`, focus ring `2px solid var(--ui-primary)` with 4 px offset when focus is moved there). Inside:
|
||||
|
||||
| Part | Content |
|
||||
|---|---|
|
||||
| Label | "Version", 15 px semibold, `--ui-text-highlighted` |
|
||||
| Value | The running build's version in IBM Plex Mono 14 px, `--ui-text-toned`. The board shows `v2.2.0-beta`. Shown exactly as the server reports it, so the SPA adds no `v` prefix. |
|
||||
| Status block | A polite live region (`aria-live="polite"`): 14 px padding, 12 px gap, an 18 px icon, a semibold title, the text, and a muted `meta` line. Background and icon color follow the tone: neutral `--ui-bg-muted`, success, info, warning, error (`--rc-<tone>-soft` fill, `--ui-<tone>` icon). |
|
||||
| Progress | A `progressbar` with a value (`aria-valuenow`) while downloading, labelled for example "Downloading version 2.3.0", with the text `42% · 11 of 26 MB`. Indeterminate while verifying (35 % wide moving bar), labelled "Checking the download", text "Almost there". Announced at 25 % steps and when the step changes, never on every tick. |
|
||||
| Release notes | A button "What's new in 2.3.0" with `aria-expanded` and a chevron, collapsed by default. Open: "Released 24 Sep 2026" and a plain-text list. |
|
||||
| Server command | Only in the "Not prepared" state: "For whoever manages the server", a one-line `code` block, a Copy button (reads "Copied" with a check for 2 s, announced), and the note "They run this once on the server. After that, Update and Restart appear here." The command shown is `renewcms enable-browser-updates` and is subject to the real one. |
|
||||
| Buttons | 32 px high (44 px on mobile, stacked full width), 14 px side padding. One primary at most. Disabled buttons use 40 % opacity. |
|
||||
| Hint | 12 px muted line under the buttons. |
|
||||
| Link | Underlined, with an `arrow-up-right`: "How to update" or "Read the release notes". |
|
||||
|
||||
Buttons used: **Check for updates** (`refresh-cw`, secondary), **Update** (`download`, primary), **Restart** (`power`, primary when an update is ready, otherwise secondary), **Try again** (`rotate-cw`, primary), and the disabled "Checking…" and "Updating…" (`loader-circle`). Copy such as "Version 2.3.0" names the newer release. Decision for the spec: show the release tag without its leading `v` ("Version 2.3.0-beta" for tag `v2.3.0-beta`), while the Version card keeps the running build exactly as the server reports it.
|
||||
|
||||
## Copy
|
||||
|
||||
| Where | Copy |
|
||||
|---|---|
|
||||
| Up to date | `circle-check`, success: "You're up to date" / "You have the latest version of RenewCMS." / "Last checked today at 09:41"; buttons "Check for updates" and "Restart"; hint "Restart takes about 10 seconds. Your site is unavailable while it restarts." |
|
||||
| Checking | `loader-circle`: "Checking for updates…" / "This usually takes a few seconds."; "Checking…" disabled |
|
||||
| Check failed | `wifi-off`, warning: "Couldn't check for updates" / "RenewCMS couldn't reach the update server. Check your connection and try again. Your site isn't affected." / "Last checked yesterday at 18:12"; "Try again" (primary) and "Restart" |
|
||||
| Available | `circle-arrow-up`, info: "Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart."; "Update"; hint "Takes about 2 minutes. Your site stays online." |
|
||||
| Downloading | `download`, info: "Downloading version 2.3.0…" / "You can leave this page. The download continues and your site stays online."; "Updating…" disabled |
|
||||
| Verifying | `shield-check`, info: "Checking the download…" / "Making sure the file is complete and safe to install. This takes a few seconds." |
|
||||
| Ready | `circle-check`, success: "Version 2.3.0 is ready to install" / "The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds." / "Nothing has changed yet."; "Restart"; hint "Not now? Leave this page. The update waits here, and the banner on Home reminds you." |
|
||||
| Done | "You're on version 2.3.0" / "The update is installed and your site is running again." / "Updated today at 09:52"; link "Read the release notes"; toast `circle-check` "Update installed" / "RenewCMS is now on version 2.3.0." |
|
||||
| Rolled back | `triangle-alert`, warning: "The update didn't install" / "RenewCMS put the previous version back, so your site is running as before. Nothing was lost." / "What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update."; "Try again"; toast (error, stays) `circle-x` "The update didn't install" / "Your site is back on v2.2.0-beta." |
|
||||
| Download failed | `circle-x`, error: "The download didn't finish" / "The connection dropped before the file was complete. Nothing was changed and your site is running as before."; "Try again" |
|
||||
| Not trusted | `triangle-alert`, warning: "We didn't use this update" / "The file didn't pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support." Technical detail goes to the server log. |
|
||||
| Rate limited | `info`: "Too many tries" / "Wait a moment before trying again."; button "Try again in 0:42" counting down Retry-After |
|
||||
| Not prepared | `info`: "Version 2.3.0 is available" / "This site can't update itself from the browser yet. Whoever manages your server can set it up once, or update RenewCMS for you." and a link "How to update". No buttons, not even Restart. |
|
||||
| Admin | "Version 2.3.0 is available" / "You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site." No buttons. Up to date reads "You're up to date" and "Only the owner can update or restart the site." |
|
||||
|
||||
## Dialogs and overlays
|
||||
|
||||
Both dialogs use the ConfirmDialog behaviour: focus moves to the first button, Escape and the cancel button close it, and focus returns to the button that opened it. The confirm button is neutral, not red, because nothing is lost.
|
||||
|
||||
| Dialog | Title | Description | Cancel / Confirm |
|
||||
|---|---|---|---|
|
||||
| Install | "Restart to finish the update?" | "RenewCMS will install version 2.3.0 and restart. Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first." | "Restart later" / "Restart now" |
|
||||
| Plain restart | "Restart the site?" | "Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first." | "Cancel" / "Restart site" |
|
||||
|
||||
Failure inside the install dialog: "Couldn't start the restart. Nothing was changed and your site is still running. Try again in a moment."
|
||||
|
||||
Restart overlay: a full-page `role="status"` live region (`--ui-bg-muted`, 440 px card) that survives the server going away, with a moving bar. Copy: "Installing version 2.3.0" / "Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back." / "Started at 09:51". Announced once as "Installing version 2.3.0. Your site is restarting." After 60 seconds with no answer: "Still restarting" / "This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now." / "Started at 09:51 · 1 minute ago" and a "Reload page" button. Plain restart: "Restarting your site" / "This takes about 10 seconds. This page reloads on its own when the site is back." After the reload: focus lands on the "Updates" heading and a toast `circle-check` "Site restarted" / "Your site is running again."
|
||||
|
||||
## Elsewhere
|
||||
|
||||
For the owner only: an **Update** pill on the Settings sidebar item, and a dot on the menu icon on mobile (read as "Update available"). Admins see neither. The Home banner is described in [home](home.md).
|
||||
|
||||
## Status to copy
|
||||
|
||||
| Status | Where | Copy |
|
||||
|---|---|---|
|
||||
| 200 | Check, up to date | "You're up to date" and the last-checked line |
|
||||
| 200 | Check, newer version | "Version 2.3.0 is available" and its text |
|
||||
| 202 | Update, Restart | Accepted. The card switches to progress, announced as "Downloading version 2.3.0, 25 percent". |
|
||||
| 200 | Update finished | "Version 2.3.0 is ready to install" |
|
||||
| 200 | After restart | Toast "Update installed" or "Site restarted" |
|
||||
| 400 | Update, nothing to install | Info toast "Nothing to update" / "You already have the latest version." The card refreshes. |
|
||||
| 401 | any | Global: /login?redirect=/settings&reason=expired. No local copy. |
|
||||
| 403 | any button, not the owner | Error toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." The card reloads as the admin view. An unverified account is handled globally. |
|
||||
| 409 | Update, Restart | Already running: info toast "An update is already running" / "Another owner started it. Progress shows here." Not prepared: the card shows the "Not prepared" state. |
|
||||
| 422 | Update, file not trusted | The "Not trusted" card above |
|
||||
| 429 | Check, Update | The rate-limited card above |
|
||||
| 500 / network | Check | "Couldn't check for updates" with "Try again" |
|
||||
| 500 / network | Update | "The download didn't finish" with "Try again" |
|
||||
| 500 / network | Restart dialog | "Couldn't start the restart. Nothing was changed and your site is still running. Try again in a moment." |
|
||||
| Site back, old version | after restart | The rolled-back card above |
|
||||
| No answer, 60 s | restart overlay | "Still restarting" |
|
||||
| Offline | whole page | Existing banner. Check, Update and Restart are disabled. During a restart the overlay keeps polling and ignores the offline state. |
|
||||
|
||||
## Behaviour notes
|
||||
|
||||
- The page asks for `GET /v1/system/update` on open and, when a step is running, polls it every second. The server holds the state (idle, downloading, verifying, ready, restarting, succeeded, failed), so another device or owner sees the same card.
|
||||
- A check runs on the first open after 24 hours and when "Check for updates" is pressed.
|
||||
- Update takes no confirmation because it changes nothing. Restart always asks.
|
||||
|
||||
## States
|
||||
|
||||
### Default
|
||||
|
||||
**Trigger:** Opened from the sidebar.
|
||||
|
||||
- Breadcrumbs: Settings (mobile title "Settings")
|
||||
- Section: Version, `v2.2.0-beta`
|
||||
|
||||
The board draws no loading or error state. Decide them in the spec (see the notes).
|
||||
|
||||
## Notes for implementation
|
||||
|
||||
- The board's API line says "none (static)", but the version lives in the Go binary (`main.version`, set with `-ldflags -X`, `dev` when unset), so the SPA has to ask for it. The recommendation is `GET /v1/settings` returning `{ "version": "..." }` inside the verified group, so later settings have a home. It is read once at startup and never from the environment at request time.
|
||||
- Not drawn: loading (the recommendation is a skeleton for the value only, after 150 ms, like the other pages), and a failed request (an inline error in the card with "Try again", using the global copy "Couldn't reach RenewCMS. Check your connection and try again.").
|
||||
- Keep the page free of actions, toggles and links until a later slice adds a real setting.
|
||||
| State | Trigger and behaviour |
|
||||
|---|---|
|
||||
| Up to date | Opened with no newer version. Restart is available but not emphasised. |
|
||||
| Checking | Check for updates pressed, or the first open after 24 hours. Announced as "Checking for updates". Buttons are disabled. |
|
||||
| Check failed | Offline, or the update server didn't answer (500, network). The last known result is kept. |
|
||||
| Update available | A newer version exists. Release notes are collapsed. Update is the one primary button. |
|
||||
| Update available, notes open | "What's new in 2.3.0" expanded. It is a button with aria-expanded, and the list is plain text. |
|
||||
| Downloading | Update pressed (202). Progress polls every second. Announced as "Downloading, 25 percent" and so on, never every tick. |
|
||||
| Verifying | The download finished. No percentage, so the bar is indeterminate. Announced as "Checking the download". |
|
||||
| Ready to install | The file passed its checks. Restart becomes the primary action. "Restart later" is closing the dialog or leaving the page. |
|
||||
| Restart: confirm | Restart pressed. Same dialog behaviour as the delete confirm: focus moves to the first button, Escape and "Restart later" close it, and focus returns to Restart. The confirm button is neutral, not red, because nothing is lost. |
|
||||
| Restart: request failed | 500 or network failure before the restart began. The site is still running. |
|
||||
| Restarting to install | Full-page overlay, so it survives the server going away. The page polls until the site answers, then reloads. It is a live region announced once as "Installing version 2.3.0. Your site is restarting." |
|
||||
| Restarting, taking longer | No answer after 60 seconds. The copy changes and a manual reload appears. The overlay stays until the site is back. |
|
||||
| Update done | The page reloaded on the new version. Focus lands on the "Updates" heading (ring shown), the toast is announced, and the version updates. |
|
||||
| Update failed, rolled back | The site came back on v2.2.0-beta. The error toast stays until dismissed and the card keeps the explanation. |
|
||||
| Download failed | A 500, or the connection dropped. Focus moves to the card heading. Try again restarts the download. |
|
||||
| Verification failed | The downloaded file isn't trusted. The tone is a warning, and the file is thrown away. Technical detail goes to the server log, not the screen. |
|
||||
| Too many requests (429) | Retry-After counted down in the button. It re-enables at zero. |
|
||||
| Not prepared | The server can't update from the browser. No buttons, not even Restart. The command is for the person who runs the server and is a single line. The placeholder command is subject to the real one. |
|
||||
| Not prepared: command copied | Copy pressed. The button reads "Copied" for 2 s and it is announced. |
|
||||
| Plain restart: confirm | Restart with no update waiting. Nothing is installed. |
|
||||
| Plain restart: restarting | Same overlay as the update restart with shorter copy. |
|
||||
| Plain restart: done | The page reloaded. Focus lands on the "Updates" heading. |
|
||||
| Admin view | Admins see the version and the note, with no buttons. Up to date: "You're up to date" and "Only the owner can update or restart the site." No Home banner or Settings pill. |
|
||||
| Role changed (403) | An owner was changed to admin while the page was open and pressed a button. The card reloads in the admin view. |
|
||||
| Update already running (409) | Another owner started it. The card switches to that run's progress. |
|
||||
@@ -12,7 +12,7 @@
|
||||
<div style="width:224px;flex-shrink:0;background:var(--ui-bg);border-right:1px solid var(--ui-border);display:flex;flex-direction:column;padding:12px;gap:2px">
|
||||
<div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;margin-bottom:10px"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">RenewCMS</span></div>
|
||||
<sc-for list="{{ nav }}" as="n" hint-placeholder-count="3">
|
||||
<div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span>{{ n.t }}</div>
|
||||
<div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span>{{ n.t }}<sc-if value="{{ n.badge }}"><span style="margin-left:auto;height:18px;padding:0 6px;display:inline-flex;align-items:center;background:var(--ui-info);color:var(--ui-bg);font:500 11px 'IBM Plex Sans',sans-serif">Update</span></sc-if></div>
|
||||
</sc-for>
|
||||
<div style="flex:1"></div>
|
||||
<sc-if value="{{ s.boot }}"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px"><span style="width:26px;height:26px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></div></sc-if>
|
||||
@@ -25,7 +25,7 @@
|
||||
<div style="height:48px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 24px;gap:8px;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/panel-left-close.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/panel-left-close.svg') center / contain no-repeat"></span><span style="width:1px;height:16px;background:var(--ui-border);margin:0 6px"></span><sc-for list="{{ crumbs }}" as="c" hint-placeholder-count="1"><sc-if value="{{ c.sep }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat"></span></sc-if><span style="color:{{ c.fg }};font-weight:{{ c.fw }}">{{ c.t }}</span></sc-for></div>
|
||||
</sc-if>
|
||||
<sc-if value="{{ mob }}">
|
||||
<div style="height:56px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 6px;gap:4px;color:var(--ui-text-highlighted)"><span data-act="m-lead" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat"></span></span><span style="flex:1;min-width:0;font-weight:600;font-size:16px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ s.mTitle }}</span><sc-if value="{{ s.mAction }}"><span data-act="m-action" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat"></span></span></sc-if></div>
|
||||
<div style="height:56px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 6px;gap:4px;color:var(--ui-text-highlighted)"><span data-act="m-lead" style="position:relative;width:44px;height:44px;display:flex;align-items:center;justify-content:center"><sc-if value="{{ s.navBadge }}"><span aria-label="Update available" style="position:absolute;top:9px;right:9px;width:10px;height:10px;background:var(--ui-info);border:2px solid var(--ui-bg)"></span></sc-if><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat"></span></span><span style="flex:1;min-width:0;font-weight:600;font-size:16px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ s.mTitle }}</span><sc-if value="{{ s.mAction }}"><span data-act="m-action" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat"></span></span></sc-if></div>
|
||||
</sc-if>
|
||||
<sc-if value="{{ s.offline }}"><div role="status" style="flex-shrink:0;display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/wifi-off.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/wifi-off.svg') center / contain no-repeat"></span><span style="flex:1">You're offline. You can keep writing, but saving and publishing will wait until you're back online.</span></div></sc-if>
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
<sc-if value="{{ isHome }}">
|
||||
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:{{ gap }};max-width:1040px">
|
||||
<div style="display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap"><div style="flex:1;min-width:200px;display:flex;flex-direction:column;gap:4px"><span style="font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Good morning, {{ who }}</span><span style="color:var(--ui-text-muted);font-size:14px">{{ s.home.sub }}</span></div><sc-if value="{{ desk }}"><span data-act="new" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat"></span>New article</span></sc-if></div>
|
||||
<sc-if value="{{ s.home.banner }}"><div role="region" aria-label="Update available" style="display:flex;flex-direction:{{ upBtnDir }};align-items:{{ upBannerAlign }};gap:12px;padding:12px 14px;background:{{ s.home.banner.bg }};border:1px solid var(--ui-border)"><div style="flex:1;display:flex;gap:10px;min-width:0"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:{{ s.home.banner.fg }};-webkit-mask:url('https://api.iconify.design/lucide/{{ s.home.banner.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.home.banner.icon }}.svg') center / contain no-repeat"></span></span><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;color:var(--ui-text-highlighted)">{{ s.home.banner.title }}</span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ s.home.banner.text }}</span></div></div><div style="display:flex;align-items:center;gap:8px"><span style="flex:1;height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500">{{ s.home.banner.btn }}</span><span role="button" aria-label="Dismiss" style="width:{{ btnH }};height:{{ btnH }};display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat"></span></span></div></div></sc-if>
|
||||
<sc-if value="{{ s.home.error }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><div style="flex:1;display:flex;flex-direction:column;gap:8px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Couldn't load your articles</span><span style="color:var(--ui-text-toned)">Check your connection and try again.</span></div><span style="align-self:flex-start;height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;font-size:12px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat"></span>Try again</span></div></div></sc-if>
|
||||
<sc-if value="{{ s.home.stats }}">
|
||||
<div style="display:grid;grid-template-columns:{{ cols3 }};gap:12px">
|
||||
@@ -229,7 +230,16 @@
|
||||
<sc-if value="{{ isSettings }}">
|
||||
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:20px;max-width:720px;overflow:hidden">
|
||||
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Settings</span><span style="color:var(--ui-text-muted)">Workspace information.</span></div>
|
||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;align-items:center;justify-content:space-between;gap:16px"><span style="font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Version</span><span style="font:400 14px/22px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)">v2.2.0-beta</span></div>
|
||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;align-items:center;justify-content:space-between;gap:16px"><span style="font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Version</span><span style="font:400 14px/22px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)">{{ s.upd.v }}</span></div>
|
||||
<div role="region" aria-labelledby="updates-h" style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:16px">
|
||||
<span id="updates-h" tabindex="-1" style="align-self:flex-start;font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted);outline:{{ s.upd.focus }};outline-offset:4px">Updates</span>
|
||||
<div aria-live="polite" style="display:flex;gap:12px;padding:14px;background:{{ s.upd.bg }}"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:{{ s.upd.fg }};-webkit-mask:url('https://api.iconify.design/lucide/{{ s.upd.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.icon }}.svg') center / contain no-repeat"></span></span><div style="flex:1;min-width:0;display:flex;flex-direction:column;gap:4px"><span style="font:600 14px/22px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ s.upd.title }}</span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ s.upd.text }}</span><sc-if value="{{ s.upd.bar }}"><div style="display:flex;flex-direction:column;gap:6px;padding-top:8px"><div role="progressbar" aria-label="{{ s.upd.barLabel }}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ s.upd.pct }}" style="height:6px;background:var(--ui-bg-accented)"><div style="height:6px;width:{{ s.upd.barW }};margin-left:{{ s.upd.barL }};background:var(--ui-primary)"></div></div><span style="font:400 12px/16px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ s.upd.barText }}</span></div></sc-if><sc-if value="{{ s.upd.meta }}"><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.upd.meta }}</span></sc-if></div></div>
|
||||
<sc-if value="{{ s.upd.notes }}"><div style="display:flex;flex-direction:column;gap:10px"><span role="button" aria-expanded="{{ s.upd.notes.open }}" style="align-self:flex-start;display:flex;align-items:center;gap:6px;min-height:{{ btnH }};font-weight:500;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.upd.notes.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.notes.chev }}.svg') center / contain no-repeat"></span>What's new in {{ s.upd.notes.ver }}</span><sc-if value="{{ s.upd.notes.open }}"><div style="display:flex;flex-direction:column;gap:8px;padding:0 0 0 20px"><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.upd.notes.date }}</span><sc-for list="{{ s.upd.notes.items }}" as="it" hint-placeholder-count="3"><div style="display:flex;gap:8px"><span aria-hidden="true" style="flex-shrink:0;width:4px;height:4px;margin-top:8px;background:var(--ui-text-muted)"></span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ it.t }}</span></div></sc-for><span style="align-self:flex-start;color:var(--ui-text-highlighted);text-decoration:underline;text-underline-offset:3px;font-weight:500">Read the full release notes</span></div></sc-if></div></sc-if>
|
||||
<sc-if value="{{ s.upd.cmd }}"><div style="display:flex;flex-direction:column;gap:8px"><span style="font-weight:500;color:var(--ui-text-highlighted)">For whoever manages the server</span><div style="display:flex;flex-direction:{{ upCmdDir }};align-items:{{ upBtnAlign }};gap:8px"><code style="flex:1;min-width:0;padding:8px 12px;background:var(--ui-bg-elevated);color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:22px">{{ s.upd.cmd.line }}</code><span role="button" style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ s.upd.cmd.fg }};font-weight:500"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.upd.cmd.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.cmd.icon }}.svg') center / contain no-repeat"></span>{{ s.upd.cmd.t }}</span></div><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.upd.cmd.note }}</span></div></sc-if>
|
||||
<sc-if value="{{ s.upd.btns }}"><div style="display:flex;flex-direction:{{ upBtnDir }};align-items:{{ upBtnAlign }};gap:8px"><sc-for list="{{ s.upd.btns }}" as="b" hint-placeholder-count="1"><span role="button" style="height:{{ btnH }};padding:0 14px;display:flex;align-items:center;justify-content:center;gap:6px;background:{{ b.bg }};color:{{ b.fg }};border:1px solid {{ b.bd }};opacity:{{ b.op }};font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ b.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ b.icon }}.svg') center / contain no-repeat"></span>{{ b.t }}</span></sc-for></div></sc-if>
|
||||
<sc-if value="{{ s.upd.hint }}"><span style="font-size:12px;color:var(--ui-text-muted);text-wrap:pretty">{{ s.upd.hint }}</span></sc-if>
|
||||
<sc-if value="{{ s.upd.link }}"><span style="align-self:flex-start;display:flex;align-items:center;gap:6px;color:var(--ui-text-highlighted);text-decoration:underline;text-underline-offset:3px;font-weight:500">{{ s.upd.link }}<span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat"></span></span></sc-if>
|
||||
</div>
|
||||
</div>
|
||||
</sc-if>
|
||||
|
||||
@@ -272,6 +282,8 @@
|
||||
|
||||
<sc-if value="{{ mobMenu }}"><div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="menu" aria-label="Account" style="width:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);padding:8px 0 24px"><div style="margin:0 auto 8px;width:36px;height:4px;background:var(--ui-bg-accented)"></div><div style="padding:8px 16px 14px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="width:36px;height:36px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 13px 'IBM Plex Sans',sans-serif">{{ ini }}</span><div style="display:flex;flex-direction:column;min-width:0"><span style="font-weight:600;font-size:15px;color:var(--ui-text-highlighted)">{{ who }}</span><span style="color:var(--ui-text-muted)">marta@renew.example</span></div></div><div data-act="nav-profile" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><sc-for list="{{ themeSeg }}" as="m" hint-placeholder-count="3"><div data-act="{{ m.act }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:48px;padding:0 16px;display:flex;align-items:center;justify-content:space-between;font-size:15px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:18px;height:18px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></div></sc-if>
|
||||
|
||||
<sc-if value="{{ s.overlay }}"><div role="status" aria-live="polite" style="position:absolute;inset:0;z-index:70;background:var(--ui-bg-muted);display:flex;align-items:center;justify-content:center;padding:24px"><div style="width:100%;max-width:440px;display:flex;flex-direction:column;gap:16px;align-items:flex-start"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges" aria-hidden="true"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><div style="display:flex;flex-direction:column;gap:6px"><span style="font:600 22px/30px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ s.overlay.title }}</span><span style="font-size:14px;line-height:22px;color:var(--ui-text-toned);text-wrap:pretty">{{ s.overlay.text }}</span></div><div role="progressbar" aria-label="Restarting" style="width:100%;height:4px;background:var(--ui-bg-accented)"><div style="width:35%;height:4px;margin-left:{{ s.overlay.barL }};background:var(--ui-primary)"></div></div><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.overlay.meta }}</span><sc-if value="{{ s.overlay.btn }}"><span role="button" style="height:{{ btnH }};padding:0 14px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500">{{ s.overlay.btn }}</span></sc-if></div></div></sc-if>
|
||||
|
||||
<sc-if value="{{ s.modal }}">
|
||||
<div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:{{ modalAlign }};justify-content:center;padding:{{ modalPad }}">
|
||||
<div role="dialog" aria-modal="true" style="width:{{ modalW }};background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column">
|
||||
@@ -344,7 +356,7 @@ class Component extends DCLogic {
|
||||
const m = !!this.props.mobile
|
||||
const k = s.kind || 'home'
|
||||
const navItems = [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['users', 'users', 'Users'], ['integration', 'plug', 'Integration'], ['settings', 'settings', 'Settings']]
|
||||
const nav = navItems.map(([key, icon, t]) => ({ key, icon, t, bg: s.nav === key ? 'var(--rc-sand)' : 'transparent', fg: s.nav === key ? '#111111' : 'var(--ui-text-toned)', fw: s.nav === key ? 500 : 400 }))
|
||||
const nav = navItems.map(([key, icon, t]) => ({ key, icon, t, bg: s.nav === key ? 'var(--rc-sand)' : 'transparent', badge: key === 'settings' && !!s.navBadge, fg: s.nav === key ? '#111111' : 'var(--ui-text-toned)', fw: s.nav === key ? 500 : 400 }))
|
||||
const crumbs = (s.crumbs || []).map((t, i, a) => ({ t, sep: i > 0, fg: i === a.length - 1 ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', fw: i === a.length - 1 ? 500 : 400 }))
|
||||
const L = s.list || {}
|
||||
const counts = L.counts || [6, 4, 2]
|
||||
@@ -426,14 +438,14 @@ class Component extends DCLogic {
|
||||
themeSeg: [['system','monitor','System'],['light','sun','Light'],['dark','moon','Dark']].map(([k,icon,tt])=>{const on=(s.mode||'light')===k;return {act:'theme-'+k,icon,t:tt,on,op:on?1:0}}), menuOpen: !!s.userMenu, deskMenu: !m && !!s.userMenu, mobMenu: m && !!s.userMenu, pfItemBg: 'var(--ui-bg-elevated)',
|
||||
chipBg: s.userMenu || s.nav === 'profile' ? 'var(--rc-sand)' : 'transparent', chipFg: s.userMenu || s.nav === 'profile' ? '#111111' : 'var(--ui-text-highlighted)',
|
||||
isSettings: k === 'settings', isProfile: k === 'profile', pfLoading: k === 'profile' && !!pf.loading, pfReady: k === 'profile' && !pf.loading,
|
||||
cardPad: m ? '16px' : '20px', cardPadX: m ? '16px' : '20px', inH: m ? '44px' : '40px', pfCols: m ? 'minmax(0,1fr)' : 'minmax(0,1fr) minmax(0,1.4fr)', pwDir: m ? 'column' : 'row', pwAlign: m ? 'stretch' : 'flex-end', edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar,
|
||||
upBtnDir: m ? 'column' : 'row', upBtnAlign: m ? 'stretch' : 'flex-start', cardPad: m ? '16px' : '20px', cardPadX: m ? '16px' : '20px', inH: m ? '44px' : '40px', pfCols: m ? 'minmax(0,1fr)' : 'minmax(0,1fr) minmax(0,1.4fr)', pwDir: m ? 'column' : 'row', pwAlign: m ? 'stretch' : 'flex-end', edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar,
|
||||
desk: !m, mob: m, notBoot: !s.boot,
|
||||
fw: m ? '390px' : '1440px', fh: m ? '844px' : '900px', dir: m ? 'column' : 'row',
|
||||
mLead: s.mLead || 'menu',
|
||||
isBoot: !!s.boot, isHome: k === 'home' && !s.boot, isList: k === 'articles', isEditor: k === 'editor', isInteg: k === 'integration', isError: k === 'error', isUsers: k === 'users',
|
||||
usRows, usError: !!US.error, usOnly: !!US.only && !US.error, usTable: !m && !US.error, usCards: m && !US.error,
|
||||
pad: m ? '20px 16px 88px' : '32px', gap: m ? '20px' : '28px', cols3: m ? 'repeat(3,minmax(0,1fr))' : 'repeat(3,minmax(0,1fr))',
|
||||
btnH: m ? '44px' : '32px', rowH: m ? '52px' : '44px', inF: m ? '16px' : '14px',
|
||||
upBannerAlign: m ? 'stretch' : 'center', upCmdDir: m ? 'column' : 'row', btnH: m ? '44px' : '32px', rowH: m ? '52px' : '44px', inF: m ? '16px' : '14px',
|
||||
tbDir: m ? 'column' : 'row', tbGap: m ? '12px' : '16px', tbBorder: m ? '0' : '1px solid var(--ui-border)', tabBorder: m ? '1px solid var(--ui-border)' : '0', tabH: m ? '44px' : '36px', tabF: m ? '14px' : '13px',
|
||||
qText: L.q ? L.q : 'Search by title', qFg: L.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)',
|
||||
showTable: !m && !L.empty, showCards: m && !L.empty, listFab: !s.modal,
|
||||
|
||||
@@ -118,6 +118,18 @@ class Component extends DCLogic {
|
||||
const rowFail = { n: 'roof.png', sz: '1.4 MB', st: 'fail', im: 10 }
|
||||
const gone = [1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12]
|
||||
const pk = (o = {}, x = {}) => MS({ kind: 'picker', picker: true, pk: { tab: 'Library', ...o }, ...x })
|
||||
const TB = { neutral: 'var(--ui-bg-muted)', success: 'var(--rc-success-soft)', info: 'var(--rc-info-soft)', warning: 'var(--rc-warning-soft)', error: 'var(--rc-error-soft)' }
|
||||
const B = (t, kind, icon, dis) => ({ t, icon, bg: kind === 'primary' ? 'var(--ui-primary)' : 'var(--ui-bg)', fg: kind === 'primary' ? 'var(--ui-bg)' : 'var(--ui-text-highlighted)', bd: kind === 'primary' ? 'var(--ui-primary)' : 'var(--ui-border-accented)', op: dis ? '0.4' : '1' })
|
||||
const UPD = (o) => { const tone = o.tone || 'neutral'; return { v: 'v2.2.0-beta', focus: 'none', ...o, fg: tone === 'neutral' ? 'var(--ui-text-toned)' : 'var(--ui-' + tone + ')', bg: TB[tone], bar: o.pct !== undefined || !!o.indet, barW: o.indet ? '35%' : (o.pct || 0) + '%', barL: o.indet ? '30%' : '0', pct: o.indet ? undefined : o.pct } }
|
||||
const NOTES = (open) => ({ open, chev: open ? 'chevron-down' : 'chevron-right', ver: '2.3.0', date: 'Released 24 Sep 2026', items: [{ t: 'Images upload faster, and large images no longer stall.' }, { t: 'Fixed a problem where a draft could show an old title after saving.' }, { t: 'Small improvements to the Users page.' }] })
|
||||
const SU = (o, extra) => withM({ kind: 'settings', nav: 'settings', crumbs: ['Settings'], mTitle: 'Settings', ...extra, upd: UPD(o) })
|
||||
const LAST = 'Last checked today at 09:41'
|
||||
const RESTART_FOOT = 'Restart takes about 10 seconds. Your site is unavailable while it restarts.'
|
||||
const bn = (icon, title, text) => ({ icon, title, text, btn: 'Go to Settings', fg: 'var(--ui-info)', bg: 'var(--rc-info-soft)' })
|
||||
const cmdLine = 'renewcms enable-browser-updates'
|
||||
const notPrep = (copied) => ({ icon: 'info', tone: 'info', title: 'Version 2.3.0 is available', text: 'This site can\'t update itself from the browser yet. Whoever manages your server can set it up once, or update RenewCMS for you.', meta: LAST, cmd: { line: cmdLine, t: copied ? 'Copied' : 'Copy', icon: copied ? 'check' : 'copy', fg: copied ? 'var(--ui-success)' : 'var(--ui-text-highlighted)', note: 'They run this once on the server. After that, Update and Restart appear here.' }, link: 'How to update' })
|
||||
const restartModal = (o) => ({ title: 'Restart the site?', desc: 'Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you\'re editing first.', cancel: 'Cancel', confirm: 'Restart site', ...o })
|
||||
const installModal = (o) => ({ title: 'Restart to finish the update?', desc: 'RenewCMS will install version 2.3.0 and restart. Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you\'re editing first.', cancel: 'Restart later', confirm: 'Restart now', ...o })
|
||||
return this.finish([
|
||||
{ label: 'Boot', title: 'App boot', route: 'any route, first load', api: 'GET /v1/auth/me (pending)', note: 'While the session is checked, the shell renders with skeletons, never a spinner. The possible outcomes are: 200 with a verified user, which renders the route; 200 with an unverified user, which goes to /register/pending; and 401, which goes to /login?redirect=<path>. Public routes skip this check.', states: [
|
||||
withM({ ...home, name: 'Checking session', trigger: 'The first paint on any back-office URL, and usually visible for well under a second.', boot: true })
|
||||
@@ -126,7 +138,9 @@ class Component extends DCLogic {
|
||||
withM({ ...home, name: 'Default', trigger: 'The articles loaded.', home: { sub: 'Here\'s where things stand on your site.', stats, recent } }),
|
||||
withM({ ...home, name: 'Loading', trigger: 'The list request is in flight. Skeletons appear after 150 ms.', home: { sub: 'Here\'s where things stand on your site.', stats: stats.map(() => ({ skel: true })), recent: Array.from({ length: 5 }, () => ({ skel: true })) } }),
|
||||
withM({ ...home, name: 'Empty, first run', trigger: 'Zero articles: a single call to action, and no stats.', home: { sub: 'Welcome to RenewCMS.', empty: true } }),
|
||||
withM({ ...home, name: 'Error', trigger: 'A 500 or network failure on the list request.', home: { sub: 'Here\'s where things stand on your site.', error: true } })
|
||||
withM({ ...home, name: 'Error', trigger: 'A 500 or network failure on the list request.', home: { sub: 'Here\'s where things stand on your site.', error: true } }),
|
||||
withM({ ...home, navBadge: true, name: 'Update available (owner)', trigger: 'The owner only. A quiet banner above the content, and an "Update" pill on the Settings item (a dot on the menu icon on mobile, read as "Update available"). Dismissing hides the banner until the next version; the pill stays. Admins see neither.', home: { sub: 'Here\'s where things stand on your site.', stats, recent, banner: bn('circle-arrow-up', 'Version 2.3.0 is available', 'Update it from Settings. It takes about 2 minutes and the site stays online.') } }),
|
||||
withM({ ...home, navBadge: true, name: 'Update ready to install (owner)', trigger: 'The download is checked. The same banner changes its copy, and a dismiss comes back on the next visit because the update is waiting.', home: { sub: 'Here\'s where things stand on your site.', stats, recent, banner: bn('circle-check', 'Version 2.3.0 is ready to install', 'Restart from Settings to finish. The site is unavailable for about 10 seconds.') } })
|
||||
] },
|
||||
{ label: 'Articles', title: 'Articles', route: '/article', api: 'GET /v1/article/ · PATCH …/publish · PATCH …/unpublish · DELETE /v1/article/{id}', note: 'Rows update when the server responds, not optimistically. Search, tab and sort are stored in the query string.', states: [
|
||||
withM({ ...L(), name: 'Default', trigger: 'The list loaded, sorted by last updated.' }),
|
||||
@@ -274,8 +288,50 @@ class Component extends DCLogic {
|
||||
withM({ ...U({ toasts: [T('error', 'circle-x', 'Couldn\'t renew the invite', 'Try again in a moment.')] }), name: 'Renew invite: failed', trigger: '500 or network failure. The row stays Expired and the button can be pressed again.' }),
|
||||
withM({ ...U({ users: { rows: [{ email: 'lea.martin@renew.example', role: 'admin', st: 'pending', c: 'Today', hl: true }, ...people] } , toasts: [T('success', 'circle-check', 'Invite sent', 'lea.martin@renew.example has 3 days to accept.')] }), name: 'Invite sent', trigger: '201: the dialog closes, the new invite appears at the top as Pending, and a toast confirms.' })
|
||||
] },
|
||||
{ label: 'Settings', title: 'Settings', route: '/settings', api: 'none (static)', note: 'Opened from the sidebar. For now it holds only the Version section.', states: [
|
||||
withM({ kind: 'settings', nav: 'settings', crumbs: ['Settings'], mTitle: 'Settings', name: 'Default', trigger: 'Opened from the sidebar.' })
|
||||
{ label: 'Settings', title: 'Settings: Updates', route: '/settings', api: 'GET /v1/system/update · POST …/check · POST …/download · POST …/restart (all pending)', note: 'New Updates card under Version, owner only. Update downloads and checks the new version and changes nothing. Restart installs it and restarts the site (about 10 seconds). "Restart later" is simply leaving the card or the dialog. A plain Restart shows only when no update is waiting. Admins see the version and a note. When the server isn\'t prepared, the card shows the notice and a "How to update" link with no buttons. Progress is a progressbar with a value, announced at 25% steps and when each step changes. The card is a polite live region. After the restart the page reloads, focus lands on the "Updates" heading, and a toast confirms. Buttons are disabled while any step runs, and any owner on any device sees the same state from the server. Cue elsewhere: see Home. Out of scope: choosing versions, downgrades, automatic updates, update history.', states: [
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re up to date', text: 'You have the latest version of RenewCMS.', meta: LAST, btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Up to date', trigger: 'Opened with no newer version. Restart is available but not emphasised.' }),
|
||||
SU({ icon: 'loader-circle', title: 'Checking for updates…', text: 'This usually takes a few seconds.', btns: [B('Checking…', 'sec', 'loader-circle', true)] }, { name: 'Checking', trigger: 'Check for updates pressed, or the first open after 24 hours. Announced as "Checking for updates". Buttons are disabled.' }),
|
||||
SU({ icon: 'wifi-off', tone: 'warning', title: 'Couldn\'t check for updates', text: 'RenewCMS couldn\'t reach the update server. Check your connection and try again. Your site isn\'t affected.', meta: 'Last checked yesterday at 18:12', btns: [B('Try again', 'primary', 'rotate-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Check failed', trigger: 'Offline, or the update server didn\'t answer (500, network). The last known result is kept.' }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, notes: NOTES(false), btns: [B('Update', 'primary', 'download')], hint: 'Takes about 2 minutes. Your site stays online.' }, { name: 'Update available', trigger: 'A newer version exists. Release notes are collapsed. Update is the one primary button.', navBadge: true }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, notes: NOTES(true), btns: [B('Update', 'primary', 'download')], hint: 'Takes about 2 minutes. Your site stays online.' }, { name: 'Update available, notes open', trigger: '"What\'s new in 2.3.0" expanded. It is a button with aria-expanded, and the list is plain text.', navBadge: true }),
|
||||
SU({ icon: 'download', tone: 'info', title: 'Downloading version 2.3.0…', text: 'You can leave this page. The download continues and your site stays online.', pct: 42, barLabel: 'Downloading version 2.3.0', barText: '42% · 11 of 26 MB', btns: [B('Updating…', 'sec', 'loader-circle', true)] }, { name: 'Downloading', trigger: 'Update pressed (202). Progress polls every second. Announced as "Downloading, 25 percent" and so on, never every tick.', navBadge: true }),
|
||||
SU({ icon: 'shield-check', tone: 'info', title: 'Checking the download…', text: 'Making sure the file is complete and safe to install. This takes a few seconds.', indet: true, barLabel: 'Checking the download', barText: 'Almost there', btns: [B('Updating…', 'sec', 'loader-circle', true)] }, { name: 'Verifying', trigger: 'The download finished. No percentage, so the bar is indeterminate. Announced as "Checking the download".', navBadge: true }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', notes: NOTES(false), btns: [B('Restart', 'primary', 'power')], hint: 'Not now? Leave this page. The update waits here, and the banner on Home reminds you.' }, { name: 'Ready to install', trigger: 'The file passed its checks. Restart becomes the primary action. "Restart later" is closing the dialog or leaving the page.', navBadge: true }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', btns: [B('Restart', 'primary', 'power')] }, { name: 'Restart: confirm', trigger: 'Restart pressed. Same dialog behaviour as the delete confirm: focus moves to the first button, Escape and "Restart later" close it, and focus returns to Restart. The confirm button is neutral, not red, because nothing is lost.', navBadge: true, modal: installModal() }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', btns: [B('Restart', 'primary', 'power')] }, { name: 'Restart: request failed', trigger: '500 or network failure before the restart began. The site is still running.', navBadge: true, modal: installModal({ notice: 'Couldn\'t start the restart. Nothing was changed and your site is still running. Try again in a moment.' }) }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: '', btns: [] }, { name: 'Restarting to install', trigger: 'Full-page overlay, so it survives the server going away. The page polls until the site answers, then reloads. It is a live region announced once as "Installing version 2.3.0. Your site is restarting."', overlay: { title: 'Installing version 2.3.0', text: 'Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back.', meta: 'Started at 09:51', barL: '30%' } }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: '', text: '', btns: [] }, { name: 'Restarting, taking longer', trigger: 'No answer after 60 seconds. The copy changes and a manual reload appears. The overlay stays until the site is back.', overlay: { title: 'Still restarting', text: 'This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now.', meta: 'Started at 09:51 · 1 minute ago', btn: 'Reload page', barL: '65%' } }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re on version 2.3.0', text: 'The update is installed and your site is running again.', meta: 'Updated today at 09:52', btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT, link: 'Read the release notes', v: 'v2.3.0', focus: '2px solid var(--ui-primary)', toasts: undefined }, { name: 'Update done', trigger: 'The page reloaded on the new version. Focus lands on the "Updates" heading (ring shown), the toast is announced, and the version updates.', toasts: [T('success', 'circle-check', 'Update installed', 'RenewCMS is now on version 2.3.0.')] }),
|
||||
SU({ icon: 'triangle-alert', tone: 'warning', title: 'The update didn\'t install', text: 'RenewCMS put the previous version back, so your site is running as before. Nothing was lost.', meta: 'What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Update failed, rolled back', trigger: 'The site came back on v2.2.0-beta. The error toast stays until dismissed and the card keeps the explanation.', toasts: [T('error', 'circle-x', 'The update didn\'t install', 'Your site is back on v2.2.0-beta.')] }),
|
||||
SU({ icon: 'circle-x', tone: 'error', title: 'The download didn\'t finish', text: 'The connection dropped before the file was complete. Nothing was changed and your site is running as before.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Download failed', trigger: 'A 500, or the connection dropped. Focus moves to the card heading. Try again restarts the download.', navBadge: true }),
|
||||
SU({ icon: 'triangle-alert', tone: 'warning', title: 'We didn\'t use this update', text: 'The file didn\'t pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Verification failed', trigger: 'The downloaded file isn\'t trusted. The tone is a warning, and the file is thrown away. Technical detail goes to the server log, not the screen.', navBadge: true }),
|
||||
SU({ icon: 'info', tone: 'info', title: 'Too many tries', text: 'Wait a moment before trying again.', btns: [B('Try again in 0:42', 'sec', 'clock', true)] }, { name: 'Too many requests (429)', trigger: 'Retry-After counted down in the button. It re-enables at zero.' }),
|
||||
SU(notPrep(false), { name: 'Not prepared', trigger: 'The server can\'t update from the browser. No buttons, not even Restart. The command is for the person who runs the server and is a single line. The placeholder command is subject to the real one.', navBadge: true }),
|
||||
SU(notPrep(true), { name: 'Not prepared: command copied', trigger: 'Copy pressed. The button reads "Copied" for 2 s and it is announced.', navBadge: true }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re up to date', text: 'You have the latest version of RenewCMS.', meta: LAST, btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Plain restart: confirm', trigger: 'Restart with no update waiting. Nothing is installed.', modal: restartModal() }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: '', text: '', btns: [] }, { name: 'Plain restart: restarting', trigger: 'Same overlay as the update restart with shorter copy.', overlay: { title: 'Restarting your site', text: 'This takes about 10 seconds. This page reloads on its own when the site is back.', meta: 'Started at 09:51', barL: '30%' } }),
|
||||
SU({ icon: 'circle-check', tone: 'success', title: 'Your site is back', text: '', btns: [] }, { name: 'Plain restart: done', trigger: 'The page reloaded. Focus lands on the "Updates" heading.', toasts: [T('success', 'circle-check', 'Site restarted', 'Your site is running again.')] }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.', meta: LAST }, { name: 'Admin view', trigger: 'Admins see the version and the note, with no buttons. Up to date: "You\'re up to date" and "Only the owner can update or restart the site." No Home banner or Settings pill.' }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.', meta: LAST }, { name: 'Role changed (403)', trigger: 'An owner was changed to admin while the page was open and pressed a button. The card reloads in the admin view.', toasts: [T('error', 'circle-x', 'Only the owner can do this', 'Ask the owner of this site to update RenewCMS.')] }),
|
||||
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, btns: [B('Update', 'primary', 'download', true)] }, { name: 'Update already running (409)', trigger: 'Another owner started it. The card switches to that run\'s progress.', navBadge: true, toasts: [T('info', 'info', 'An update is already running', 'Another owner started it. Progress shows here.')] })
|
||||
], tableTitle: 'Status to copy', table: [
|
||||
{ a: '200', b: 'Check, up to date', c: '"You\'re up to date" / "You have the latest version of RenewCMS." / "Last checked today at 09:41"' },
|
||||
{ a: '200', b: 'Check, newer version', c: '"Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart."' },
|
||||
{ a: '202', b: 'Update, Restart', c: 'Accepted. The card switches to progress. Announced: "Downloading version 2.3.0, 25 percent".' },
|
||||
{ a: '200', b: 'Update finished', c: '"Version 2.3.0 is ready to install" / "The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds."' },
|
||||
{ a: '200', b: 'After restart', c: 'Toast: "Update installed" / "RenewCMS is now on version 2.3.0." Plain restart: "Site restarted" / "Your site is running again."' },
|
||||
{ a: '400', b: 'Update, nothing to install', c: 'Toast (info): "Nothing to update" / "You already have the latest version." The card refreshes.' },
|
||||
{ a: '401', b: 'Any call', c: 'Handled globally: /login?redirect=/settings&reason=expired. No local copy.' },
|
||||
{ a: '403', b: 'Any button, not the owner', c: 'Toast (error): "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." The card reloads as the admin view. An unverified account is handled globally.' },
|
||||
{ a: '409', b: 'Update, Restart', c: 'Already running: toast (info) "An update is already running" / "Another owner started it. Progress shows here." Not prepared: the card shows the "Not prepared" state and "How to update".' },
|
||||
{ a: '422', b: 'Update, file not trusted', c: '"We didn\'t use this update" / "The file didn\'t pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support."' },
|
||||
{ a: '429', b: 'Check, Update', c: 'Card alert (info): "Too many tries" / "Wait a moment before trying again." Button reads "Try again in 0:42" and counts down.' },
|
||||
{ a: '500 / network', b: 'Check', c: '"Couldn\'t check for updates" / "RenewCMS couldn\'t reach the update server. Check your connection and try again. Your site isn\'t affected." with "Try again".' },
|
||||
{ a: '500 / network', b: 'Update', c: '"The download didn\'t finish" / "The connection dropped before the file was complete. Nothing was changed and your site is running as before." with "Try again".' },
|
||||
{ a: '500 / network', b: 'Restart dialog', c: '"Couldn\'t start the restart. Nothing was changed and your site is still running. Try again in a moment."' },
|
||||
{ a: 'Site back, old version', b: 'After restart', c: '"The update didn\'t install" / "RenewCMS put the previous version back, so your site is running as before. Nothing was lost." Next step: "try again in a few minutes. If it fails again, ask whoever manages your server to check the update."' },
|
||||
{ a: 'No answer, 60 s', b: 'Restart overlay', c: '"Still restarting" / "This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now."' },
|
||||
{ a: 'Offline', b: 'Whole page', c: 'Existing banner. Check, Update and Restart are disabled. During a restart, the overlay keeps polling and ignores the offline state.' }
|
||||
] },
|
||||
{ label: 'Profile', title: 'Profile', route: '/profile', api: 'GET /v1/auth/me · PATCH /v1/user/me (pending) · POST /v1/auth/password-reset', note: 'Opened from the account menu at the bottom of the sidebar. Username, email and password are read-only. The display name is optional, trimmed, and up to 60 characters. Once saved it replaces the username everywhere a person is named: the sidebar, the account menu, the Home greeting, the Users list (with the username beside it) and the emails RenewCMS sends, such as "Marta Alves invited you to RenewCMS". Saving it empty goes back to the username. The reset link uses the same flow as "Forgot password" and ends on the auth board\'s "Choose a new password" screen.', states: [
|
||||
withM({ ...home, home: { sub: 'Here\'s where things stand on your site.', stats, recent }, userMenu: true, name: 'Account menu', trigger: 'The account chip at the bottom of the sidebar. On mobile, the account row in the navigation drawer opens it as a sheet. Escape or a click outside closes it.' }),
|
||||
|
||||
+35
-1
@@ -149,7 +149,33 @@ Every state is drawn at desktop and mobile on the screen boards, with final copy
|
||||
| Users | `/users` | Renew invite: sending | "Renew invite" on an Expired row; POST in flight | [users](screens/users.md) |
|
||||
| Users | `/users` | Renew invite: done | 200: row Pending on top, toast | [users](screens/users.md) |
|
||||
| Users | `/users` | Renew invite: failed | 500 or network: toast, row stays Expired | [users](screens/users.md) |
|
||||
| Settings | `/settings` | Default | Opened from the sidebar | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Up to date | Opened with no newer version | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Checking | Check for updates pressed, or the first open after 24 hours | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Check failed | Offline, or the update server didn't answer (500, network) | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Update available | A newer version exists | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Update available, notes open | "What's new in 2.3.0" expanded | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Downloading | Update pressed (202) | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Verifying | The download finished | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Ready to install | The file passed its checks | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Restart: confirm | Restart pressed | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Restart: request failed | 500 or network failure before the restart began | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Restarting to install | Full-page overlay, so it survives the server going away | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Restarting, taking longer | No answer after 60 seconds | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Update done | The page reloaded on the new version | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Update failed, rolled back | The site came back on v2.2.0-beta | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Download failed | A 500, or the connection dropped | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Verification failed | The downloaded file isn't trusted | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Too many requests (429) | Retry-After counted down in the button | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Not prepared | The server can't update from the browser | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Not prepared: command copied | Copy pressed | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Plain restart: confirm | Restart with no update waiting | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Plain restart: restarting | Same overlay as the update restart with shorter copy | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Plain restart: done | The page reloaded | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Admin view | Admins see the version and the note, with no buttons | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Role changed (403) | An owner was changed to admin while the page was open and pressed a button | [settings](screens/settings.md) |
|
||||
| Settings | `/settings` | Update already running (409) | Another owner started it | [settings](screens/settings.md) |
|
||||
| Home | `/home` | Update available (owner) | Owner only: quiet banner and Settings pill | [home](screens/home.md) |
|
||||
| Home | `/home` | Update ready to install (owner) | Download checked: banner copy changes | [home](screens/home.md) |
|
||||
| Profile | `/profile` | Account menu | Account chip clicked | [profile](screens/profile.md) |
|
||||
| Profile | `/profile` | Loading | Opened by URL before /auth/me returns | [profile](screens/profile.md) |
|
||||
| Profile | `/profile` | Default, no display name | First visit | [profile](screens/profile.md) |
|
||||
@@ -220,6 +246,14 @@ Still not supported, so shown disabled or omitted:
|
||||
|
||||
Renaming a title (shown read-only, with an explanation in Details), resending the verification email (the pending page explains how to start over), changing the email or username, removing users, promoting or demoting anyone, and any role other than owner and admin. Changing the password while logged in works only through the emailed reset link on the Profile page.
|
||||
|
||||
Added by the Updates card, none of which exists yet (owner only unless noted, see [settings](screens/settings.md)):
|
||||
|
||||
- `GET /v1/system/update` (any verified user): `{ current, latest, available, notes: { version, released_at, items }, checked_at, can_apply, state, progress, error, started_at }`. `state` is `idle`, `downloading`, `verifying`, `ready`, `restarting`, `succeeded` or `failed`. `can_apply` is false when the server hasn't been prepared, or for admins.
|
||||
- `POST /v1/system/update/check`: asks the release feed. 200, 429 with `Retry-After`, 500 when the feed can't be reached.
|
||||
- `POST /v1/system/update/download`: 202 starts the download and verification, 400 when there is nothing to update, 403, 409 when one is already running or the server isn't prepared, 422 when the file fails verification, 429.
|
||||
- `POST /v1/system/update/restart`: 202 starts the install and restart (or only a restart when no update is ready), 403, 409, 500.
|
||||
- A restart must survive the server going away: the SPA polls `/healthz` and `GET /v1/system/update` until they answer.
|
||||
|
||||
Added by the Media screens, none of which exist yet:
|
||||
|
||||
- `GET /v1/media/?q=&filter=&sort=&limit=&cursor=&hash=`: the library, newest first by default. `hash` (SHA-256 hex) returns only the images with that content, which is how the browser checks for a duplicate before uploading. Each item carries `id`, `filename`, `url`, `size`, `content_type`, `width`, `height` (null for SVG), `uploaded_by`, `created_at`, `used_in` (count) and `duplicate` (bool). The response also carries the counts for the Unused and Duplicates tabs.
|
||||
|
||||
@@ -17,7 +17,7 @@ Rules: bullets are full sentences ending with a period; user-facing wording, no
|
||||
|
||||
## Published releases
|
||||
|
||||
Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create --tag <tag> --title "<name>" --note-file docs/releases/<tag>.md --prerelease --asset <binary>` (one `--asset` per binary), after `task release`.
|
||||
Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create --tag <tag> --title "<name>" --note-file docs/releases/<tag>.md --prerelease --asset <file>` after `task release`, with one `--asset` per file: the six binaries, `bin/checksums.txt` and `bin/checksums.txt.sig`. `task release` produces all eight and fails before building when the signing key is missing or wrong (see [deployment.md](deployment.md#release-signing-key-maintainers-once)). Never publish a release without the two checksum files.
|
||||
|
||||
| Tag | Name |
|
||||
| --- | --- |
|
||||
@@ -27,3 +27,4 @@ Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create -
|
||||
| `v2.3.0-beta` | v2.3.0-beta - Multi-user invitations, display names & profile page |
|
||||
| `v2.4.0-beta` | v2.4.0-beta - Owner role, invite management & Settings page |
|
||||
| `v2.5.0-beta` | v2.5.0-beta - Media library & image picker |
|
||||
| `v2.6.0-beta` | v2.6.0-beta - Signed updates and browser restart |
|
||||
@@ -0,0 +1,46 @@
|
||||
RenewCMS can now check for releases, download a signed update and install it from Settings. On Linux with systemd, the owner can restart the site from the browser, with automatic binary rollback if the new version fails to start.
|
||||
|
||||
## New
|
||||
|
||||
**Updates in Settings**
|
||||
- Owners can check for a newer release, read its release notes and download it while the site stays online.
|
||||
- Downloads show progress, verify the release signature and binary checksum, check the staged version and back up the database before becoming ready to install.
|
||||
- The Home page and Settings navigation show an owner-only update notification, and the Home banner can be dismissed for each version.
|
||||
- Admins can read the update status without starting an update or restart.
|
||||
|
||||
**Browser restart and installation**
|
||||
- Owners can confirm an update installation or a plain site restart from Settings.
|
||||
- A restart overlay waits for the site to return and offers a reload action when the restart takes longer than expected.
|
||||
- Linux installations with systemd can enable browser updates using `renewcms enable-browser-updates` and remove the helper using `renewcms disable-browser-updates`.
|
||||
- The helper verifies the staged files again, keeps the previous binary and restores it if the new version does not start successfully.
|
||||
|
||||
## Improvements and fixes
|
||||
- Update status and download progress survive navigation and are shared between owners.
|
||||
- Update checks and download starts have separate per-user rate limits with retry countdowns.
|
||||
- Restart confirmations identify whether the action installs an update or only restarts the site, and refuse a request when another owner's action has changed that state.
|
||||
- Completion messages are shown in the browser tab that requested the restart.
|
||||
|
||||
## API
|
||||
- `GET /v1/system/update` returns the current and latest versions, release notes, release URL, helper availability, progress, state, error kind and operation timestamps for verified users, without changing state.
|
||||
- `POST /v1/system/update/check` checks the release feed for owners and returns 200, 403 for insufficient permissions, 429 with `Retry-After`, or 500 when the feed cannot be reached.
|
||||
- `POST /v1/system/update/download` starts an owner-only background download with 202, or returns 400 when nothing is available, 403, 409 for an unavailable helper or conflicting job, 422 for a pre-flight refusal, or 429.
|
||||
- `POST /v1/system/update/restart` accepts an optional `kind` of `update` or `restart` and returns 202, 400 for invalid input, 403, 409 for an unavailable helper or conflicting state, or 500 when the request cannot be saved.
|
||||
|
||||
## Under the hood
|
||||
- Releases include signed `checksums.txt` and `checksums.txt.sig` files alongside the six platform binaries.
|
||||
- The update helper runs separately from the unprivileged app, copies staged files into a private directory and verifies the bytes it installs rather than trusting a mutable staged path.
|
||||
- Feature specifications, fake-backed Go tests and SPA tests cover release checks, downloads, restart requests and rollback decisions.
|
||||
|
||||
## Upgrading
|
||||
- Back up your SQLite database and uploads, then replace the binary and restart manually for this first release with browser-update support.
|
||||
- No database schema change is introduced by the update features.
|
||||
- `UPDATE_FEED_URL` is optional and defaults to the project's release feed; existing configuration remains usable.
|
||||
- On Linux with systemd, run `sudo renewcms enable-browser-updates` after the manual upgrade to enable future updates and restarts from Settings.
|
||||
- Keep the update status files, staged files and backups beside the database in the data directory, with the permissions described in `docs/deployment.md`.
|
||||
|
||||
## Known limitations
|
||||
- The privileged update helper has automated coverage through fakes, but its first real Linux/systemd update and rollback checks are still pending.
|
||||
- Browser installation and restart require Linux with systemd; Windows, macOS and other init systems remain manual upgrades.
|
||||
- Updating or restarting briefly takes the site offline, and a reverse proxy may return errors during that interval.
|
||||
- Automatic rollback restores the previous binary; it does not restore the database, so schema-changing upgrades still require a backup and a recovery plan.
|
||||
- Update assets and redirects must use HTTPS on the configured feed host.
|
||||
@@ -0,0 +1,334 @@
|
||||
Feature: Updates part 2: the Update button (download, verify, stage)
|
||||
|
||||
As the owner of a RenewCMS site
|
||||
I want one button that downloads the new release, proves it is genuine, backs up the database and stages it
|
||||
So that the later Restart (slice 3) installs a file that was already checked, while the site stays online
|
||||
|
||||
Background:
|
||||
Given slices 1 to 3 of Updates ship in one release
|
||||
And this slice changes nothing that is running: it never replaces the running binary and never restarts the site
|
||||
And the domain package internal/domain/update (stdlib only) gains these interfaces, each faked in tests:
|
||||
AssetFetcher (downloads one asset to a path, reporting bytes done and total),
|
||||
SignatureVerifier (ed25519 check of checksums.txt against checksums.txt.sig with the embedded release.pub),
|
||||
StagedBinaryRunner (runs <path> --version and returns its output),
|
||||
DatabaseBackup (consistent copy of the SQLite file with VACUUM INTO, prune to the last 3),
|
||||
HelperDetector (reports whether the slice 3 helper is installed),
|
||||
JobStore (persists the update job record)
|
||||
And update.Release gains Assets (name, download URL, size) read by the Gitea adapter, and the stored CheckResult keeps
|
||||
them, so POST /v1/system/update/download never contacts the feed
|
||||
And the use cases depend only on domain interfaces; handlers in api/handlers/update receive them through NewHandler;
|
||||
only api/dependecyInjection.go builds the adapters
|
||||
And the job runs in one background goroutine owned by the use case; the HTTP handler returns as soon as it is started
|
||||
And POST /v1/system/update/download is mounted in NewSystemRouter behind jwtauth.Verifier, jwtauth.Authenticator,
|
||||
RequireCurrentToken, RequireVerifiedUser, RequireOwner and its own limiter of 5 starts per minute per user_id
|
||||
(constants, separate from the check limiter and the auth limiter) answering 429 with an integer Retry-After
|
||||
And the checks on POST run in this order: no cookie or stale token (401), unverified (403), not owner (403),
|
||||
limiter (429), can_apply false (409), a job running or already ready (409), available false (400),
|
||||
pre-flight refusal (422), then 202
|
||||
And errors are plain text from http.Error
|
||||
And the data directory is the directory that holds DB_FILE; no new env var is added
|
||||
And the job record is update-job.json in the data directory, shared by all owners and surviving a restart
|
||||
And a job record found as "downloading" or "verifying" at startup (no goroutine owns it) reads as failed with
|
||||
error "download"; a record "ready" whose staged binary is gone reads as idle
|
||||
And the staged files live in <data dir>/updates/<tag>/: the binary, checksums.txt and checksums.txt.sig
|
||||
And the asset to download is named renewcms_<tag>_<runtime.GOOS>_<runtime.GOARCH>, plus ".exe" on windows
|
||||
And the job runs these steps in order: download checksums.txt, checksums.txt.sig and the binary; verify the
|
||||
ed25519 signature of checksums.txt; verify the SHA-256 of the binary against its checksums.txt line; run the
|
||||
staged binary with --version and require the output to equal the tag; back up the database; mark "ready"
|
||||
And state is "downloading" during the downloads and "verifying" from the signature check until "ready"
|
||||
(the version run and the backup happen in "verifying")
|
||||
And the download policy, enforced in the production adapter: the URL must be https, its host (with port) must equal
|
||||
the host of UPDATE_FEED_URL, and every redirect must satisfy the same rule; there is a size cap per file
|
||||
(binary 200 MiB, checksums.txt 64 KiB, checksums.txt.sig 1 KiB) and an overall timeout of 10 minutes (named constants)
|
||||
And in tests the policy is relaxed only through the adapter constructor, which takes the allowed host, an
|
||||
"allow insecure scheme" option, a smaller cap and a shorter timeout; there is no env var or build flag that relaxes it
|
||||
And GET /v1/system/update keeps its 12 keys; state is one of idle, downloading, verifying, ready, failed;
|
||||
progress is {percent, downloaded_bytes, total_bytes} while downloading and null otherwise;
|
||||
error is null, "download" or "verification" (a kind only, never technical text); started_at is the job start
|
||||
And can_apply is true only for the owner when HelperDetector reports the helper installed; it is false for admins
|
||||
And the real HelperDetector reads <data dir>/update-helper.json (the status file the slice 3 helper writes); nothing
|
||||
writes it in this slice, so can_apply is false on real builds until slice 3
|
||||
And disk errors and database backup failures end the job as failed with error "download"
|
||||
And on any failure the staged files are deleted, the technical reason is logged server side, and no response carries it
|
||||
And a failed record stays until the next job starts; ready stays until slice 3 consumes it
|
||||
And the SPA shows the newer release without its leading "v" ("Version 2.3.0-beta") and the running version exactly as reported
|
||||
And the Restart button in "Ready to install" is rendered but disabled in this slice: the board frame draws it as the
|
||||
primary action, it has no handler, and slice 3 enables it; plain Restart (no update waiting) stays not rendered until slice 3
|
||||
|
||||
Scenario: Start the update, happy path
|
||||
Given the owner, can_apply true, a stored result with latest "v2.3.0-beta" (running "v2.2.0-beta", available true)
|
||||
and assets for the host platform, all served by the fake fetcher and signed with a throwaway key
|
||||
When the owner sends POST /v1/system/update/download
|
||||
Then the status is 202 and the body is the status JSON with state "downloading" and started_at set
|
||||
And GET /v1/system/update then reports downloading with progress.total_bytes equal to the asset size
|
||||
And when the job finishes GET reports state "ready", error null, progress null, latest "v2.3.0-beta"
|
||||
And the staged binary, checksums.txt and checksums.txt.sig are in <data dir>/updates/v2.3.0-beta/
|
||||
And a database backup exists in <data dir>/backups/ before state became "ready"
|
||||
And the running binary and the database are unchanged
|
||||
|
||||
Scenario Outline: The asset name follows the platform
|
||||
Given the runtime is <os>/<arch> and the release lists all six binaries
|
||||
When the update starts
|
||||
Then the fetcher is asked for "<asset>", "checksums.txt" and "checksums.txt.sig" only
|
||||
|
||||
Examples:
|
||||
| os | arch | asset |
|
||||
| linux | amd64 | renewcms_v2.3.0-beta_linux_amd64 |
|
||||
| linux | arm64 | renewcms_v2.3.0-beta_linux_arm64 |
|
||||
| darwin | arm64 | renewcms_v2.3.0-beta_darwin_arm64 |
|
||||
| windows | amd64 | renewcms_v2.3.0-beta_windows_amd64.exe |
|
||||
|
||||
Scenario: Progress is reported in bytes
|
||||
Given the fake fetcher has delivered 11 of 26 MiB
|
||||
When any verified user sends GET /v1/system/update
|
||||
Then state is "downloading" and progress is {percent: 42, downloaded_bytes: 11534336, total_bytes: 27262976}
|
||||
And percent is the floor of done * 100 / total
|
||||
|
||||
Scenario: Every owner sees the same job
|
||||
Given owner A started the job
|
||||
When owner B and an admin send GET /v1/system/update
|
||||
Then both read state "downloading" with the same progress and started_at
|
||||
And the owner's can_apply is true and the admin's can_apply is false
|
||||
|
||||
Scenario: The job record survives a restart
|
||||
Given the job is "ready" for "v2.3.0-beta" with its staged binary present
|
||||
When a new status use case is built over the same data directory
|
||||
Then GET reports state "ready"
|
||||
And a record "downloading" at startup reads as state "failed", error "download"
|
||||
And a record "ready" with the staged binary deleted reads as "idle"
|
||||
And a missing or corrupt job file reads as "idle" and is not fatal
|
||||
|
||||
Scenario: Only the owner
|
||||
When an admin sends POST /v1/system/update/download
|
||||
Then the status is 403 and the body is apperr.OwnerRequiredErrorMessage
|
||||
And no job starts and the fetcher is not called
|
||||
|
||||
Scenario Outline: POST is guarded like the other system routes
|
||||
When <caller> sends POST /v1/system/update/download
|
||||
Then the status is <status>
|
||||
And no job starts
|
||||
|
||||
Examples:
|
||||
| caller | status |
|
||||
| no jwt cookie | 401 |
|
||||
| a stale token version | 401 |
|
||||
| an unverified owner | 403 |
|
||||
|
||||
Scenario: Nothing to update
|
||||
Given a stored result with available false, or no stored result
|
||||
When the owner sends POST /v1/system/update/download
|
||||
Then the status is 400 and no job starts and the fetcher is not called
|
||||
|
||||
Scenario: The server is not prepared
|
||||
Given HelperDetector reports no helper
|
||||
When the owner sends POST /v1/system/update/download
|
||||
Then the status is 409 and no job starts
|
||||
And GET reports can_apply false
|
||||
And this holds even when available is false (409 before 400)
|
||||
|
||||
Scenario Outline: A second start while a job exists
|
||||
Given the job state is <state>
|
||||
When the owner sends POST /v1/system/update/download
|
||||
Then the status is 409 and the existing job is untouched
|
||||
|
||||
Examples:
|
||||
| state |
|
||||
| downloading |
|
||||
| verifying |
|
||||
| ready |
|
||||
|
||||
Scenario: Two starts at once run one job
|
||||
When two owners send POST /v1/system/update/download concurrently
|
||||
Then exactly one answers 202 and the other 409
|
||||
And the fetcher downloads each asset once
|
||||
|
||||
Scenario: Try again after a failure
|
||||
Given the job state is "failed"
|
||||
When the owner sends POST /v1/system/update/download
|
||||
Then the status is 202, error returns to null, started_at is new and the old staged files are replaced
|
||||
|
||||
Scenario: Start is rate limited per user
|
||||
When the owner sends 6 starts within one minute
|
||||
Then the first 5 are answered by the checks above and the 6th is 429 with apperr.TooManyRequestsErrorMessage
|
||||
and an integer Retry-After of at least 1
|
||||
And a different owner is not limited, and the check limiter and auth limiter counters are untouched
|
||||
|
||||
Scenario Outline: 422 is only a pre-flight refusal
|
||||
Given a stored result where <condition>
|
||||
When the owner sends POST /v1/system/update/download
|
||||
Then the status is 422 and the body is plain text without technical detail
|
||||
And no job starts, the fetcher is not called and the technical reason is logged
|
||||
|
||||
Examples:
|
||||
| condition |
|
||||
| no asset is named for the host platform |
|
||||
| checksums.txt or checksums.txt.sig is missing from the assets |
|
||||
| an asset URL is http, not https |
|
||||
| an asset URL is on a host other than UPDATE_FEED_URL's host |
|
||||
|
||||
Scenario Outline: Verification failures end the job as failed, kind "verification"
|
||||
Given a started job and <fault>
|
||||
When the job reaches the check
|
||||
Then GET reports state "failed", error "verification", progress null
|
||||
And <data dir>/updates/<tag>/ is deleted
|
||||
And the technical reason is logged and appears in no response body
|
||||
|
||||
Examples:
|
||||
| fault |
|
||||
| the binary was changed after signing (SHA-256 mismatch) |
|
||||
| checksums.txt was changed after signing |
|
||||
| the signature is from a different key |
|
||||
| checksums.txt has no line for the asset |
|
||||
| the staged binary prints "v2.2.9-beta" for --version |
|
||||
| the staged binary cannot be run |
|
||||
|
||||
Scenario Outline: Download and disk failures end the job as failed, kind "download"
|
||||
Given a started job and <fault>
|
||||
Then GET reports state "failed", error "download"
|
||||
And <data dir>/updates/<tag>/ is deleted and the technical reason is logged, not returned
|
||||
|
||||
Examples:
|
||||
| fault |
|
||||
| the connection drops after half the bytes (truncated download) |
|
||||
| the bytes received differ from the size the release declares |
|
||||
| a file exceeds its size cap |
|
||||
| the download passes the overall timeout |
|
||||
| the feed host answers 404 or 500 for an asset |
|
||||
| the updates directory cannot be created or written (disk error) |
|
||||
| the disk fills during the write |
|
||||
| the database backup fails |
|
||||
|
||||
Scenario: The backup comes before ready, and the last 3 are kept
|
||||
Given the backups directory holds 3 earlier backups
|
||||
When a job completes
|
||||
Then a new consistent copy exists (opened read-only it holds the same article rows as the live file)
|
||||
And only the 3 newest backups remain, the oldest being deleted
|
||||
And no job is "ready" until the new backup exists
|
||||
And a failed backup leaves state "failed", error "download" and does not prune the earlier backups
|
||||
|
||||
Scenario: The production download policy
|
||||
Given the production adapter with UPDATE_FEED_URL "https://git.example"
|
||||
Then an http:// asset URL, an https URL on another host, and a redirect to another host or to http are refused
|
||||
And an https URL on git.example is accepted
|
||||
|
||||
Scenario: A server --version flag
|
||||
When the server binary is run with --version
|
||||
Then it prints the build version and exits 0
|
||||
And it does not read .env, open the database or start listening
|
||||
And with no -ldflags version it prints "dev"
|
||||
|
||||
Scenario: Settings, owner, Update available with the helper detected (route /settings)
|
||||
Given the owner and GET /v1/system/update resolves available true, can_apply true, state "idle", latest "v2.3.0-beta"
|
||||
Then the block shows icon circle-arrow-up (info), "Version 2.3.0-beta is available" /
|
||||
"You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart."
|
||||
and the meta "Last checked ..."
|
||||
And the notes button "What's new in 2.3.0-beta" is collapsed, and when open shows "Released 24 Sep 2026" and the list
|
||||
And the one button is "Update" (download, primary) and the hint is "Takes about 2 minutes. Your site stays online."
|
||||
And no server command, no "How to update" link, no Restart and no "Check for updates" is rendered
|
||||
|
||||
Scenario: Settings, owner, Downloading
|
||||
When the owner presses "Update" and POST /v1/system/update/download answers 202
|
||||
Then the block shows icon download (info), "Downloading version 2.3.0-beta…" /
|
||||
"You can leave this page. The download continues and your site stays online."
|
||||
And a progressbar labelled "Downloading version 2.3.0-beta" has aria-valuenow equal to progress.percent
|
||||
and the text "42% · 11 of 26 MB"
|
||||
And the button reads "Updating…" (loader-circle, secondary) and is disabled
|
||||
And GET /v1/system/update is polled every second while state is downloading or verifying
|
||||
|
||||
Scenario: Settings, progress is announced at 25 percent steps only
|
||||
Given the polled percent goes 3, 9, 24, 25, 26, 49, 50, 74, 75, 99, 100
|
||||
Then the announcer text changes only at 25, 50, 75 and the step change, reading
|
||||
"Downloading version 2.3.0-beta, 25 percent" and so on
|
||||
And the visible text and aria-valuenow still update on every poll
|
||||
And the live region does not announce the per-tick text
|
||||
|
||||
Scenario: Settings, owner, Verifying
|
||||
Given the poll answers state "verifying"
|
||||
Then the block shows icon shield-check (info), "Checking the download…" /
|
||||
"Making sure the file is complete and safe to install. This takes a few seconds."
|
||||
And the progressbar is indeterminate (no aria-valuenow, a 35% wide moving bar) labelled "Checking the download"
|
||||
with the text "Almost there"
|
||||
And the button reads "Updating…" and is disabled
|
||||
And "Checking the download" is announced once, when the step changes
|
||||
|
||||
Scenario: Settings, owner, Ready to install
|
||||
Given the poll answers state "ready"
|
||||
Then polling stops
|
||||
And the block shows icon circle-check (success), "Version 2.3.0-beta is ready to install" /
|
||||
"The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds." /
|
||||
"Nothing has changed yet."
|
||||
And the notes button is shown collapsed
|
||||
And the Restart button (power, primary) is rendered with disabled set and 40% opacity, and activating it does nothing
|
||||
And the hint is "Not now? Leave this page. The update waits here, and the banner on Home reminds you."
|
||||
And no dialog, overlay or POST /v1/system/update/restart exists
|
||||
|
||||
Scenario: Settings, Download failed
|
||||
Given the poll answers state "failed" with error "download", or POST download answers 500 or never reaches the server
|
||||
Then focus moves to the "Updates" heading (id="updates-h")
|
||||
And the block shows icon circle-x (error), "The download didn't finish" /
|
||||
"The connection dropped before the file was complete. Nothing was changed and your site is running as before."
|
||||
And the one button is "Try again" (rotate-cw, primary), which sends POST /v1/system/update/download
|
||||
|
||||
Scenario: Settings, Verification failed
|
||||
Given the poll answers state "failed" with error "verification", or POST download answers 422
|
||||
Then the block shows icon triangle-alert (warning), "We didn't use this update" /
|
||||
"The file didn't pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support."
|
||||
And the one button is "Try again" (rotate-cw, primary), as the board frame draws it
|
||||
And focus does not move to the heading
|
||||
And no technical detail is on screen
|
||||
|
||||
Scenario: Settings, 409 already running
|
||||
Given POST /v1/system/update/download answers 409 and the reload answers state "downloading" or "verifying"
|
||||
Then an info toast "An update is already running" / "Another owner started it. Progress shows here." shows
|
||||
And the card switches to that run's progress and polls
|
||||
When the reload instead answers can_apply false
|
||||
Then the card shows the "Not prepared" state and no toast
|
||||
When the reload instead answers state "ready"
|
||||
Then the card shows "Ready to install" and no toast
|
||||
|
||||
Scenario: Settings, 400 nothing to update
|
||||
Given POST /v1/system/update/download answers 400
|
||||
Then an info toast "Nothing to update" / "You already have the latest version." shows
|
||||
And the card reloads GET /v1/system/update
|
||||
|
||||
Scenario: Settings, 403 role changed on Update
|
||||
Given POST /v1/system/update/download answers 403
|
||||
Then an error toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." shows
|
||||
And the card reloads and renders the admin view
|
||||
|
||||
Scenario: Settings, 429 on Update
|
||||
Given POST /v1/system/update/download answers 429 with Retry-After 42
|
||||
Then the block shows icon info "Too many tries" / "Wait a moment before trying again."
|
||||
And the button reads "Try again in 0:42" (clock, disabled) and counts down each second through useRetryAfter
|
||||
And at zero it is re-enabled as "Try again" and pressing it sends POST /v1/system/update/download again
|
||||
|
||||
Scenario: Settings, reload keeps progress
|
||||
Given a job is downloading and the owner leaves /settings
|
||||
Then polling stops and the job continues on the server
|
||||
When the owner opens /settings again, from this or another device
|
||||
Then GET /v1/system/update is read on open and the card shows the job's current state and progress
|
||||
And polling resumes while state is downloading or verifying
|
||||
|
||||
Scenario: Settings, a poll that fails keeps the card
|
||||
Given a poll answers 500 or never reaches the server while downloading
|
||||
Then the card keeps its last progress, no failure card shows, and polling continues each second
|
||||
|
||||
Scenario: Settings, admin view during a job
|
||||
Given the session role is "admin" and state is "downloading"
|
||||
Then the admin view of slice 1 shows ("Version 2.3.0-beta is available" / "You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.")
|
||||
And no button, progressbar or poll is rendered
|
||||
|
||||
Scenario: Home banner, ready to install (owner)
|
||||
Given the owner is on /home and state is "ready"
|
||||
Then a region labelled "Update available" shows above the content in info tone (as the board frame draws it)
|
||||
with icon circle-check, title "Version 2.3.0-beta is ready to install",
|
||||
text "Restart from Settings to finish. The site is unavailable for about 10 seconds.",
|
||||
a "Go to Settings" button that navigates to /settings, and a Dismiss button
|
||||
And it shows although the "available" banner for this version was dismissed earlier
|
||||
When the owner dismisses it
|
||||
Then it hides for this visit only and shows again on the next visit, and nothing is written to localStorage
|
||||
And an admin sees no banner; with state "downloading" or "verifying" the "available" banner shows as before
|
||||
|
||||
Scenario: Pending states for slice 3
|
||||
Then these remain pending in the visual gate, never passing: Restart confirm, Restart request failed, Restarting to install,
|
||||
Restarting taking longer, Update done, Rolled back, Plain restart (confirm, restarting, done)
|
||||
@@ -0,0 +1,113 @@
|
||||
# QA: Updates part 2 (download, verify, stage)
|
||||
|
||||
## Automated Go (`task test`, package `test`, black-box, no live network, no real SMTP)
|
||||
|
||||
Files: `test/update_download_test.go` (domain, use case), `test/update_download_http_test.go` (HTTP),
|
||||
`test/update_assets_test.go` (production download adapter against a local server). Fakes with unique names:
|
||||
`fakeAssetFetcher` (serves bytes, can truncate, stall, fail, counts calls), `fakeHelperDetector`, `fakeJobStore`,
|
||||
`fakeStagedRunner` (returns a configured --version output or error), `fakeDatabaseBackup`; reuse `fakeReleaseFeed`,
|
||||
`fakeUpdateStore` and `mockUserRepo` from the slice 1 tests.
|
||||
|
||||
HTTP setup: `validator.InitValidator()`; `token := jwtauth.New("HS256", []byte("test-secret"), nil)`; a fresh `chi.NewRouter()` at
|
||||
`/v1/system` mirroring `NewSystemRouter` (Verifier, Authenticator, RequireCurrentToken, RequireVerifiedUser; the download
|
||||
route also RequireOwner and its limiter, 5 per minute); cookies as in `test/stale_token_invalidation_http_test.go`.
|
||||
Job state, staged files and backups go in `t.TempDir()`. Wait for the job with a poll loop on GET (deadline 5 s), never a bare
|
||||
`time.Sleep`. Use a throwaway ed25519 key generated in the test and sign `checksums.txt` with it; never read the committed
|
||||
`release.pub`.
|
||||
|
||||
Local asset server: `httptest.NewServer` (plain HTTP) and `httptest.NewTLSServer` for the policy cases. The production adapter is
|
||||
built through its constructor with the test's allowed host, allow-insecure true for the plain server, the TLS server's client for
|
||||
the TLS cases, a small size cap and a short timeout. Never relax the policy by env var or build flag.
|
||||
|
||||
1. Happy path: owner POST gives 202 with state "downloading"; poll GET until "ready"; files in `updates/<tag>/`, one backup in
|
||||
`backups/`; running binary unchanged; the fetcher was asked for exactly the three asset names.
|
||||
2. Asset naming table over GOOS/GOARCH (including the `.exe` case). Inject the platform into the use case; never assert on the
|
||||
test machine's own platform.
|
||||
3. Progress: a fetcher paused at 11 of 26 MiB gives `{percent:42, downloaded_bytes, total_bytes}` on GET; `progress` is null in
|
||||
verifying, ready and failed; `error` is null until a failure.
|
||||
4. Shared state: GET as owner A, owner B and admin agree; admin `can_apply` false, owner true with the fake detector on.
|
||||
5. Persistence: JSON job store round trip in a temp dir; "downloading" at startup reads failed/"download"; "ready" with the staged
|
||||
binary deleted reads idle; a missing or corrupt file reads idle without error. The real helper detector reads
|
||||
`<data dir>/update-helper.json`: absent file gives false, a present valid file gives true.
|
||||
6. Guards: admin 403 with `apperr.OwnerRequiredErrorMessage+"\n"`; no cookie 401; stale token 401; unverified 403; none start a job.
|
||||
7. Status codes: available false or nothing stored gives 400; detector off gives 409; state downloading, verifying, ready each give
|
||||
409; after "failed" a new POST gives 202 with a new started_at. Order check: detector off and available false gives 409.
|
||||
8. Concurrency: two simultaneous POSTs (goroutines) give one 202 and one 409; each asset fetched once (run with `-race`).
|
||||
9. Rate limit: owner A sends 6 POSTs within a minute; the 6th is 429 with `apperr.TooManyRequestsErrorMessage+"\n"` and an integer
|
||||
Retry-After >= 1; owner B is unaffected; the check limiter and a login limiter built in the test are untouched.
|
||||
10. 422 pre-flight: each of the four conditions in the feature gives 422, the body is plain text with no URL, host or file name from
|
||||
the fixture, no job record is created, fetcher count is 0, and the reason is captured from an injected logger.
|
||||
11. Verification failures, one subtest per row, each ending with GET `state` "failed", `error` "verification", `updates/<tag>/`
|
||||
removed, a body free of the fault text, and the fault text present in the injected logger: tampered binary, tampered
|
||||
checksums.txt, signature from another key, no checksum line for the asset, wrong `--version` output, runner error.
|
||||
12. Download failures, one subtest per row, each ending "failed", `error` "download", directory removed: truncated body, size
|
||||
mismatch with the release, over the size cap, timeout (server stalls; adapter timeout shortened), 404/500, unwritable updates
|
||||
directory (a file placed where the directory should be), disk full (a writer fake returning an error mid-write), backup failure
|
||||
(earlier backups not pruned).
|
||||
13. Backup: with the real SQLite backup adapter against a SQLite file created in `t.TempDir()` (pure-Go driver, `CGO_ENABLED=0`):
|
||||
the copy opens and holds the same rows, four jobs leave only the 3 newest files, and a job is not "ready" before the copy exists.
|
||||
14. Production policy: http URL, another host, redirect to another host and redirect to http are refused (no request reaches the
|
||||
second server); the TLS server on the allowed host is accepted.
|
||||
15. `--version`: build with `go build -tags nofrontend -ldflags "-X main.version=v9.9.9" ./cmd/server` into `t.TempDir()` and run
|
||||
it with `--version` and an empty environment: stdout `v9.9.9`, exit 0, no `data/` created; without ldflags it prints `dev`.
|
||||
16. Review items, not Go tests: `internal/domain/update` imports only the stdlib; use cases import no `net/http`, `os/exec`, `gorm`
|
||||
or adapter; the handler imports no adapter; no secret value is in the repo; the helper detector reads only its status file.
|
||||
|
||||
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mock `useApi.request` for `GET /v1/system/update`, `POST /v1/system/update/check` and `POST /v1/system/update/download`. Fake timers
|
||||
drive the 1 s poll and the countdown. No test freezes the system date and none asserts a relative date. Reuse the board's data:
|
||||
running `v2.2.0-beta`, latest `v2.3.0-beta`, 26 MB total, 11 MB done (42 %), released 24 Sep 2026.
|
||||
|
||||
One test per state:
|
||||
1. Update available, can_apply true: copy, notes collapsed, only "Update", hint; no command, no link, no Restart.
|
||||
2. Update available, notes open (`aria-expanded`, "Released 24 Sep 2026").
|
||||
3. Downloading: 202 then the card copy, progressbar label, `aria-valuenow` 42, "42% · 11 of 26 MB", "Updating…" disabled; GET called once per second.
|
||||
4. Announcements: percents 3, 24, 25, 26, 49, 50, 75, 100; the announcer text changes only at 25, 50, 75 and the step change;
|
||||
`aria-valuenow` changes on each tick.
|
||||
5. Verifying: indeterminate bar (no `aria-valuenow`), "Almost there", announced once.
|
||||
6. Ready: copy, meta, hint, Restart present with `disabled` and no request on click, notes button, polling stopped.
|
||||
7. Download failed (state failed/download; a 500; a `NetworkError`): copy, focus on `#updates-h`, "Try again" posts download again.
|
||||
8. Verification failed (state failed/verification; a 422): copy, "Try again", focus not moved, no technical text.
|
||||
9. 409: reload downloading gives the info toast and progress; reload ready gives no toast and the Ready card; reload can_apply false
|
||||
gives the Not prepared card.
|
||||
10. 400: info toast "Nothing to update" and one GET.
|
||||
11. 403: error toast and the admin view after reload.
|
||||
12. 429: "Too many tries", "Try again in 0:42" counting down through `useRetryAfter`, re-enabled as "Try again" and it re-posts
|
||||
download (not check).
|
||||
13. Reload: unmount stops the poll; mount reads GET and resumes the poll for a running state; no poll for idle, ready or failed.
|
||||
14. A failed poll keeps the last progress and keeps polling.
|
||||
15. Admin with state downloading: admin copy, no button, no progressbar, no poll.
|
||||
16. Home banner ready: info tone, copy, `role="region"` labelled "Update available", "Go to Settings" navigates, shows although the
|
||||
available banner was dismissed, Dismiss hides until remount and writes nothing to localStorage; admin sees none.
|
||||
17. Sidebar pill and mobile dot stay for ready, downloading and verifying (owner only, `available` true).
|
||||
|
||||
## Visual (`task visual:check -- settings` and `-- home`; desktop and mobile, light and dark; every capture within 10 %)
|
||||
|
||||
Add the setups to `web/visual/states.ts` with the board's sample data (v2.2.0-beta, v2.3.0-beta, 42 % / "11 of 26 MB"). Exact values
|
||||
from `docs/design/source/AppFrame.dc.html` and the "Settings" and "Home" groups of the Screens board; layout as drawn.
|
||||
|
||||
- [ ] Settings: Update available, Update available (notes open), Downloading (42 %), Verifying, Ready to install,
|
||||
Download failed, Verification failed. The frame draws an enabled Restart; the disabled one (40 % opacity) must still be
|
||||
within budget. If it is not, stop and report; do not widen the budget or add an exception without the user's approval.
|
||||
- [ ] Home: Update ready to install (owner), with the sidebar pill and the mobile dot as drawn.
|
||||
- [ ] Settings: Update already running (409): the frame shows the card in progress; set up with the mocked 409 then the
|
||||
downloading reload (the toast only if the frame draws it; check the markup).
|
||||
- [ ] `skip: 'clock-sensitive'`: any state whose meta line is relative ("Last checked today at 09:41"), as in slice 1.
|
||||
- [ ] Pending, never passing (slice 3): Restart confirm, Restart request failed, Restarting, Restarting taking longer,
|
||||
Update done, Rolled back, Plain restart (confirm, restarting, done).
|
||||
- [ ] Not covered by screenshots: keyboard and focus order, the focus ring on `#updates-h` after Download failed, the 25 %
|
||||
announcements (screen reader), hover and motion of the indeterminate bar.
|
||||
|
||||
## Manual verification
|
||||
|
||||
- `can_apply` stays false on real builds until slice 3 writes `<data dir>/update-helper.json`: use the fake in tests, or place the
|
||||
file by hand to see the Update button.
|
||||
- Against a real signed release on the real feed host (needs `release.pub` replaced and `task release` signing): press Update, watch
|
||||
progress, the Verifying step and the Ready card; check `<data dir>/updates/<tag>/` and one file in `<data dir>/backups/`.
|
||||
- The real staged binary on the target OS runs `--version` and prints the tag.
|
||||
- Flip one byte of a asset on a test mirror: the card shows "We didn't use this update" and the folder is gone.
|
||||
- Kill the server mid-download and restart it: the card shows "The download didn't finish".
|
||||
- Open the card in two browsers (two owners) and confirm the same progress; the second press shows the 409 toast.
|
||||
- Embedded SPA build (no `-tags nofrontend`) serves /settings and /home with the new states.
|
||||
- Confirm no secret or feed credential appears in logs, and that technical failure reasons are in the log only.
|
||||
@@ -0,0 +1,292 @@
|
||||
Feature: Updates part 1: signed releases, release feed and read-only update notification
|
||||
|
||||
As the owner of a RenewCMS site
|
||||
I want to see when a newer signed release exists, and have admins see the same status read-only
|
||||
So that I know when to update, while downloading and restarting arrive in later slices
|
||||
|
||||
Background:
|
||||
Given slices 1 to 3 of Updates ship in one release, so no released build shows the command
|
||||
"renewcms enable-browser-updates" before it exists (it is implemented in slice 3)
|
||||
And every release is published as a Gitea prerelease with the six binaries, checksums.txt and checksums.txt.sig
|
||||
And cmd/releasesign is a stdlib-only tool (crypto/ed25519, no new dependency) with the commands
|
||||
keygen <private-key-path> [--pub-out <path>], sign <file> [--key <path>] [--pub <path>],
|
||||
verify <file> [--pub <path>]
|
||||
And keygen writes the private key to the path given and refuses a path inside the repository work tree
|
||||
And sign and verify use the embedded public key unless --pub is given; tests always pass --pub with a throwaway key
|
||||
And sign refuses to sign when the private key does not match the public key, naming the mismatch
|
||||
And the public key is internal/infrastructure/update/release.pub, embedded with go:embed
|
||||
And until the user runs task release:keygen and commits the real public key, release.pub holds the placeholder:
|
||||
the base64 of 32 zero bytes (AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=); an all-zero key is recognised
|
||||
as the placeholder, and sign and verify refuse it with a clear message
|
||||
And the real private key is generated by the user outside the repo; the coder never generates or commits it
|
||||
And task release writes checksums.txt (SHA-256 of every binary) next to the binaries and signs it into
|
||||
checksums.txt.sig with the private key at the path in the env var RELEASE_SIGNING_KEY
|
||||
And task release fails clearly, before building anything, when RELEASE_SIGNING_KEY is unset, the file is missing,
|
||||
the embedded key is the placeholder, or the private key does not match the embedded public key
|
||||
And task release:keygen creates the one-time key pair and prints where to commit the public key
|
||||
And docs/release-notes.md gains the publish step (attach checksums.txt and checksums.txt.sig with the six binaries),
|
||||
docs/deployment.md and docs/configuration.md are updated, and nothing is published
|
||||
And the domain package internal/domain/update (stdlib only) holds Release, ReleaseNotes, version comparison,
|
||||
UpdateStatus, the ReleaseFeed interface, the StatusStore interface and the Err sentinels
|
||||
And the Gitea adapter lives under internal/infrastructure/update and implements update.ReleaseFeed with
|
||||
var _ update.ReleaseFeed = &X{}; it requests GET {UPDATE_FEED_URL}/api/v1/repos/fsylvain/RenewCMS/releases
|
||||
(the list, not "latest")
|
||||
And UPDATE_FEED_URL is in requiredEnvVars/envDefaults, .env.example and docs/configuration.md, defaulting to the repo base URL
|
||||
And a JSON file store implements update.StatusStore and keeps the last result and checked_at in update-status.json
|
||||
beside DB_FILE, shared by all owners and surviving a restart; no new env var is added
|
||||
And GetUpdateStatusUseCase and CheckForUpdateUseCase depend only on the domain interfaces; handlers in
|
||||
api/handlers/update receive them through NewHandler; api/dependecyInjection.go builds the adapters
|
||||
And NewSystemRouter is mounted at /v1/system behind jwtauth.Verifier, jwtauth.Authenticator, RequireCurrentToken
|
||||
and RequireVerifiedUser; POST /update/check also sits behind RequireOwner and a limiter of 5 checks per minute
|
||||
per user_id (constants, not env vars, separate from the auth limiter) that answers 429 with an integer Retry-After
|
||||
And GET /v1/system/update returns 200 with JSON of exactly these snake_case keys: current, latest, available,
|
||||
release_url, notes {version, released_at, items}, checked_at, can_apply, state, progress, error, started_at
|
||||
And release_url is the release's html_url, null when never checked; in slice 3 the "How to update" link is
|
||||
repointed at the "Browser updates" section of docs/deployment.md
|
||||
And in this slice can_apply is always false and state is always "idle"; never-checked values are latest "",
|
||||
available false, release_url null, notes null, checked_at null, progress null, error null, started_at null
|
||||
And versions compare numerically per segment, a final release beats a beta of the same number, and the
|
||||
running build "dev" never reports an update
|
||||
And release notes are the release body converted to a plain-text list of items
|
||||
And the API returns raw tags; the SPA shows the newer release without its leading "v" ("Version 2.3.0-beta")
|
||||
and the running version exactly as reported
|
||||
And the download and restart endpoints are not mounted; ReleaseFeed, StatusStore and UpdateStatus are shaped so
|
||||
slices 2 and 3 only add use cases
|
||||
And errors are plain text from http.Error
|
||||
|
||||
Scenario Outline: Version comparison
|
||||
Given the running version is "<current>" and the newest feed release is "<latest>"
|
||||
When the versions are compared
|
||||
Then available is <available>
|
||||
|
||||
Examples:
|
||||
| current | latest | available |
|
||||
| v2.2.0-beta | v2.3.0-beta | true |
|
||||
| v2.5.0-beta | v2.5.0 | true |
|
||||
| v2.5.0 | v2.5.0-beta | false |
|
||||
| v2.9.0 | v2.10.0 | true |
|
||||
| v2.5.0-beta | v2.5.0-beta | false |
|
||||
| v2.5.0 | v2.4.9 | false |
|
||||
| dev | v9.9.9 | false |
|
||||
|
||||
Scenario: The newest release is chosen from the list regardless of feed order
|
||||
Given the feed list holds v2.4.0-beta, v2.5.0-beta and v2.3.0-beta, all marked prerelease
|
||||
When the feed is read
|
||||
Then the latest release is v2.5.0-beta
|
||||
|
||||
Scenario: Drafts are ignored
|
||||
Given the feed list holds a draft release v9.0.0 and a published v2.5.0-beta
|
||||
When the feed is read
|
||||
Then the latest release is v2.5.0-beta
|
||||
|
||||
Scenario: Release notes become a plain-text list
|
||||
Given a release body "## What's new\n- **Media** library\n- Fixed [caching](http://x) bug\n\n* Faster start"
|
||||
When the notes are built
|
||||
Then notes.items is ["Media library","Fixed caching bug","Faster start"]
|
||||
And notes.released_at is the release's published date
|
||||
|
||||
Scenario: GET returns the idle shape, never applicable
|
||||
Given a verified user, running version "v2.2.0-beta", and a stored result with latest "v2.3.0-beta",
|
||||
html_url "https://git.example/fsylvain/RenewCMS/releases/tag/v2.3.0-beta" and checked_at 2026-09-30T09:41:00Z
|
||||
When the client sends GET /v1/system/update
|
||||
Then the status is 200 and the body has exactly the 12 keys
|
||||
And current is "v2.2.0-beta", latest is "v2.3.0-beta", available is true, can_apply is false, state is "idle"
|
||||
And release_url is the stored html_url and checked_at is "2026-09-30T09:41:00Z"
|
||||
And the feed is not contacted
|
||||
|
||||
Scenario: GET before any check
|
||||
Given no stored result
|
||||
When a verified user sends GET /v1/system/update
|
||||
Then the status is 200, available is false, latest is "", release_url, notes and checked_at are null, state is "idle"
|
||||
|
||||
Scenario Outline: GET is open to any verified user
|
||||
Given the caller is <role> with a valid jwt cookie
|
||||
When the client sends GET /v1/system/update
|
||||
Then the status is 200
|
||||
|
||||
Examples:
|
||||
| role |
|
||||
| owner |
|
||||
| admin |
|
||||
|
||||
Scenario: GET without a cookie
|
||||
When the client sends GET /v1/system/update with no jwt cookie
|
||||
Then the status is 401
|
||||
|
||||
Scenario: GET with a stale token
|
||||
Given the jwt cookie was minted with a token version older than the account's
|
||||
When the client sends GET /v1/system/update
|
||||
Then the status is 401 and the body is apperr.UnauthorizedErrorMessage
|
||||
|
||||
Scenario: GET by an unverified account
|
||||
When an unverified user with a valid cookie sends GET /v1/system/update
|
||||
Then the status is 403 and the body is apperr.VerificationRequiredErrorMessage
|
||||
|
||||
Scenario: The owner checks and the result is stored
|
||||
Given the fake feed returns v2.3.0-beta and the running version is "v2.2.0-beta"
|
||||
When the owner sends POST /v1/system/update/check
|
||||
Then the status is 200 with the same body shape as GET and available true
|
||||
And the fake store holds latest "v2.3.0-beta" and checked_at at the check time
|
||||
And a later GET returns the same result without contacting the feed
|
||||
|
||||
Scenario: A check with nothing newer
|
||||
Given the feed returns v2.2.0-beta and the running version is "v2.2.0-beta"
|
||||
When the owner sends POST /v1/system/update/check
|
||||
Then the status is 200 and available is false
|
||||
|
||||
Scenario: A dev build never reports an update
|
||||
Given the running version is "dev" and the feed returns v9.9.9
|
||||
When the owner sends POST /v1/system/update/check
|
||||
Then the status is 200 and available is false
|
||||
|
||||
Scenario: An admin cannot check
|
||||
Given the caller is an admin
|
||||
When the client sends POST /v1/system/update/check
|
||||
Then the status is 403 and the body is apperr.OwnerRequiredErrorMessage
|
||||
And the feed is not contacted
|
||||
|
||||
Scenario: Feed failure keeps the last result
|
||||
Given the store holds latest "v2.3.0-beta" checked at 2026-09-30T09:41:00Z and the feed returns an error
|
||||
When the owner sends POST /v1/system/update/check
|
||||
Then the status is 500
|
||||
And the store still holds the previous result and checked_at
|
||||
And no feed error detail appears in the body
|
||||
|
||||
Scenario: Check is rate limited per user
|
||||
When the owner sends 6 checks within one minute
|
||||
Then the first 5 answer 200 and the 6th answers 429 with apperr.TooManyRequestsErrorMessage and an integer Retry-After
|
||||
And the feed is contacted 5 times
|
||||
And a different owner is not limited by the first owner's checks
|
||||
And the auth limiter's counters are untouched
|
||||
|
||||
Scenario: The stored result survives a restart
|
||||
Given the JSON file store saved a result
|
||||
When a new store is opened on the same file
|
||||
Then the same latest, release_url and checked_at are returned
|
||||
And a missing or corrupt file reads as "no result" and is not fatal
|
||||
|
||||
Scenario: Release signing round trip with a throwaway key
|
||||
Given a key pair made by keygen at a path outside the repo
|
||||
When sign is run on checksums.txt with that key and verify with its public key
|
||||
Then verify exits 0
|
||||
And after one byte of checksums.txt changes, verify exits non-zero with a clear message
|
||||
And verify with a different public key exits non-zero
|
||||
|
||||
Scenario: keygen refuses a path inside the repository
|
||||
When keygen is given a path inside the work tree
|
||||
Then it exits non-zero, writes nothing and says why
|
||||
|
||||
Scenario: The placeholder public key is refused
|
||||
Given release.pub holds the placeholder (32 zero bytes, base64)
|
||||
When sign or verify uses the embedded key
|
||||
Then it exits non-zero with a message that the placeholder key has not been replaced
|
||||
|
||||
Scenario: sign refuses a private key that does not match the public key
|
||||
Given a private key whose public half differs from the public key in use
|
||||
When sign is run
|
||||
Then it exits non-zero naming the mismatch and writes no .sig file
|
||||
|
||||
Scenario Outline: task release refuses to sign
|
||||
Given <condition>
|
||||
When task release is run
|
||||
Then it fails before building any binary with a message naming <what>
|
||||
And nothing is published
|
||||
|
||||
Examples:
|
||||
| condition | what |
|
||||
| RELEASE_SIGNING_KEY is unset | RELEASE_SIGNING_KEY |
|
||||
| RELEASE_SIGNING_KEY points to a missing file | the missing path |
|
||||
| the embedded public key is the placeholder | the placeholder key |
|
||||
| the private key does not match the public key | the key mismatch |
|
||||
|
||||
Scenario: Settings, owner, Up to date (route /settings)
|
||||
Given the session role is "owner" and GET /v1/system/update resolves available false with checked_at set
|
||||
When the owner opens /settings
|
||||
Then the Updates card shows the status block with icon circle-check (success), title "You're up to date",
|
||||
text "You have the latest version of RenewCMS." and a meta line "Last checked ..." built from checked_at
|
||||
And the only button is "Check for updates" (refresh-cw, secondary)
|
||||
And no Restart button, hint or progress is rendered
|
||||
|
||||
Scenario: Settings, owner, Checking
|
||||
When the owner presses "Check for updates"
|
||||
Then the block shows icon loader-circle, "Checking for updates…" / "This usually takes a few seconds."
|
||||
in a polite live region
|
||||
And the button reads "Checking…" and is disabled
|
||||
And POST /v1/system/update/check is sent once
|
||||
|
||||
Scenario: Settings, owner, Check failed
|
||||
Given POST /v1/system/update/check answers 500 or never reaches the server
|
||||
Then the block shows icon wifi-off (warning), "Couldn't check for updates" /
|
||||
"RenewCMS couldn't reach the update server. Check your connection and try again. Your site isn't affected."
|
||||
and the meta "Last checked ..." from the kept result
|
||||
And the only button is "Try again" (rotate-cw, primary)
|
||||
|
||||
Scenario: Settings, owner, newer version, not prepared
|
||||
Given the session role is "owner" and GET /v1/system/update resolves available true, can_apply false, latest "v2.3.0-beta"
|
||||
When the owner opens /settings
|
||||
Then the block shows icon info, "Version 2.3.0-beta is available" /
|
||||
"This site can't update itself from the browser yet. Whoever manages your server can set it up once, or update RenewCMS for you."
|
||||
And "For whoever manages the server" shows the one-line code "renewcms enable-browser-updates" with a Copy button
|
||||
And the note "They run this once on the server. After that, Update and Restart appear here." shows
|
||||
And the link "How to update" (arrow-up-right) opens release_url in a new tab
|
||||
And no button other than Copy is rendered: not Update, not Restart, not even Check for updates
|
||||
|
||||
Scenario: Settings, owner, newer version, notes open
|
||||
Given the same state with notes.items and notes.released_at 2026-09-24
|
||||
When the owner activates "What's new in 2.3.0-beta" (a button with aria-expanded false then true)
|
||||
Then "Released 24 Sep 2026" and the plain-text list show, and activating it again collapses them
|
||||
And the notes are collapsed by default
|
||||
|
||||
Scenario: Settings, command copied
|
||||
When the owner presses Copy
|
||||
Then the button reads "Copied" with a check for 2 s, is announced, then reads "Copy" again
|
||||
|
||||
Scenario: Settings, admin view
|
||||
Given the session role is "admin"
|
||||
When GET /v1/system/update resolves available true with latest "v2.3.0-beta"
|
||||
Then the card shows "Version 2.3.0-beta is available" /
|
||||
"You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site." and no button
|
||||
When it resolves available false
|
||||
Then the card shows "You're up to date" / "Only the owner can update or restart the site." and no button
|
||||
|
||||
Scenario: Settings, Role changed (403)
|
||||
Given an owner is on /settings and POST /v1/system/update/check answers 403
|
||||
Then an error toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." shows
|
||||
And the card reloads GET /v1/system/update and renders the admin view
|
||||
|
||||
Scenario: Settings, Too many requests (429)
|
||||
Given POST /v1/system/update/check answers 429 with Retry-After 42
|
||||
Then the block shows icon info "Too many tries" / "Wait a moment before trying again."
|
||||
And the button reads "Try again in 0:42", counts down each second and is re-enabled at zero
|
||||
|
||||
Scenario: A check runs on the first open after 24 hours, for the owner only
|
||||
Given the owner opens /settings and checked_at is null or older than 24 hours
|
||||
Then POST /v1/system/update/check is sent once automatically and the Checking state shows
|
||||
When checked_at is under 24 hours old
|
||||
Then no automatic check is sent
|
||||
And an admin never sends one
|
||||
|
||||
Scenario: Home banner for the owner, update available
|
||||
Given the owner is on /home and available is true with latest "v2.3.0-beta"
|
||||
Then a region labelled "Update available" shows above the content in info tone with icon circle-arrow-up,
|
||||
title "Version 2.3.0-beta is available",
|
||||
text "Update it from Settings. It takes about 2 minutes and the site stays online.",
|
||||
a "Go to Settings" button and a dismiss button
|
||||
When the owner dismisses it
|
||||
Then the banner is hidden and localStorage remembers the dismissed version
|
||||
And it shows again when latest changes to a newer version
|
||||
|
||||
Scenario: Settings sidebar pill and mobile dot
|
||||
Given the owner and available is true
|
||||
Then the Settings sidebar item shows an "Update" pill, and on mobile the menu icon shows a dot read as "Update available"
|
||||
And the pill stays after the banner is dismissed
|
||||
|
||||
Scenario: Admins and an up-to-date owner see no banner, pill or dot
|
||||
Then an admin, or an owner with available false, sees no banner, pill or dot
|
||||
|
||||
Scenario: Pending states of slices 2 and 3
|
||||
Then these states are listed as pending in the visual gate, never passing: Update available with its Update button
|
||||
(and its notes-open frame), Downloading, Verifying, Ready to install, Restart confirm, Restart request failed,
|
||||
Restarting, Restarting taking longer, Update done, Rolled back, Download failed, Verification failed,
|
||||
Plain restart confirm, restarting and done, Update already running (409), and the Home "ready to install" banner
|
||||
And the Update, Restart and progress elements are not rendered in any state of this slice
|
||||
@@ -0,0 +1,105 @@
|
||||
# QA: Updates part 1 (signed releases, release feed, notification)
|
||||
|
||||
## Automated Go (`task test`, package `test`, black-box)
|
||||
|
||||
Files: `test/update_test.go` (domain, use cases), `test/update_http_test.go` (HTTP), `test/update_feed_test.go`
|
||||
(Gitea adapter, JSON store), `test/releasesign_test.go` (signing tool). Fakes with unique names: `fakeReleaseFeed`
|
||||
(returns a list or an error, counts calls), `fakeUpdateStore`; reuse `mockUserRepo` from `test/user_test.go`.
|
||||
|
||||
HTTP setup: `validator.InitValidator()`; `token := jwtauth.New("HS256", []byte("test-secret"), nil)`; mount a fresh
|
||||
`chi.NewRouter()` at `/v1/system` mirroring `NewSystemRouter` (Verifier, Authenticator, RequireCurrentToken,
|
||||
RequireVerifiedUser; the check route also RequireOwner and the per-user limiter, 5 per minute); cookies via
|
||||
`token.Encode({"user_id","token_version"})` as in `test/stale_token_invalidation_http_test.go`. `httptest` only: no live
|
||||
server, no SQLite, no SMTP.
|
||||
|
||||
1. Version comparison, table-driven over the Examples in the feature (domain; `errors.Is` for sentinels).
|
||||
2. Feed adapter against `httptest.NewServer` serving a Gitea JSON list: path is
|
||||
`/api/v1/repos/fsylvain/RenewCMS/releases`; newest by numeric order regardless of order; drafts skipped; final beats
|
||||
beta; notes markdown converted to items; `html_url` carried; a 500 and invalid JSON return an error.
|
||||
3. `GET /v1/system/update` as owner and as admin: 200, exactly the 12 keys, `can_apply` false, `state` "idle", values
|
||||
from the stored result, `release_url` from the stored `html_url`; the fake feed call count is 0.
|
||||
4. GET before any check: `latest` "", `available` false, `release_url`, `notes`, `checked_at`, `progress`, `error`,
|
||||
`started_at` null.
|
||||
5. GET: no cookie 401; stale token 401 with `apperr.UnauthorizedErrorMessage`; unverified 403 with
|
||||
`apperr.VerificationRequiredErrorMessage`.
|
||||
6. `POST /v1/system/update/check` as owner: 200, store updated with latest, `release_url` and `checked_at`, feed called
|
||||
once, a later GET equals it. Nothing newer: `available` false. Running version "dev": `available` false.
|
||||
7. POST check as admin: 403, body `apperr.OwnerRequiredErrorMessage+"\n"`, feed not called.
|
||||
8. Feed error: 500, store unchanged (latest and `checked_at` as before), body contains no feed error text.
|
||||
9. Rate limit: owner A sends 6 checks: first 5 are 200, the 6th is 429 with `apperr.TooManyRequestsErrorMessage+"\n"`
|
||||
and an integer `Retry-After` of at least 1; feed called 5 times; owner B's first check still 200; a login-limiter
|
||||
instance built in the same test is unaffected.
|
||||
10. JSON file store in `t.TempDir()`: save, reopen, same values; missing file and corrupt file read as empty without error.
|
||||
11. Signing tool, run through `go run ./cmd/releasesign` (or its exported package) with a throwaway key pair generated
|
||||
in `t.TempDir()` at test time, always with `--pub`; never read the committed `release.pub` key except in case 13:
|
||||
keygen creates the key; sign then verify passes; one flipped byte fails verify; a different public key fails verify;
|
||||
keygen into a path inside the repo tree is refused and writes nothing; sign with a private key that does not match
|
||||
`--pub` fails, naming the mismatch, and writes no `.sig`.
|
||||
12. Placeholder: a `--pub` file holding base64 of 32 zero bytes makes sign and verify fail with the placeholder message.
|
||||
13. The committed `internal/infrastructure/update/release.pub` is checked only for shape: a valid base64 string that
|
||||
decodes to 32 bytes. Do not assert that it is or is not the placeholder, since the user replaces it later.
|
||||
14. Review items, not Go tests: `internal/domain/update` imports only the stdlib; use cases import no `net/http`,
|
||||
`gorm`, adapter or `config`; the handler imports no adapter; `UPDATE_FEED_URL` is in `requiredEnvVars`/`envDefaults`,
|
||||
`.env.example` and `docs/configuration.md`; no private key or secret value is in the repo.
|
||||
|
||||
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mock `useApi.request` for `GET /v1/system/update` and `POST /v1/system/update/check`. Fake timers for the countdown and
|
||||
the 2 s "Copied". No test freezes the system date and none asserts a relative date or "Last checked today". Reuse the
|
||||
board's sample data: running `v2.2.0-beta`, latest `v2.3.0-beta`, released 24 Sep 2026, items from the frame's script.
|
||||
|
||||
One test per state:
|
||||
1. Up to date (owner): "You're up to date", only "Check for updates" rendered.
|
||||
2. Checking: text, polite live region, "Checking…" disabled, one POST.
|
||||
3. Check failed (500, then `NetworkError`): copy, only "Try again", last result kept.
|
||||
4. Not prepared (available, `can_apply` false): copy, command line, note, "How to update" link with `href` equal to
|
||||
`release_url` and an external target; no button other than Copy.
|
||||
5. Notes open: collapsed by default, `aria-expanded` toggles, "Released 24 Sep 2026" and the plain-text list.
|
||||
6. Command copied: Copy writes the command to the clipboard mock, reads "Copied" for 2 s, then "Copy".
|
||||
7. Admin view: both texts, no button; no auto check.
|
||||
8. Role changed (403): toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS.", then a
|
||||
reload of the GET and the admin view.
|
||||
9. 429: "Too many tries", button "Try again in 0:42" counting down to enabled.
|
||||
10. Auto check: sent once when `checked_at` is null or older than 24 h, not when fresh, never for admin.
|
||||
11. Home banner: shown for the owner when available, copy and "Go to Settings" navigates to /settings, dismiss writes
|
||||
the version to localStorage and hides it, same version stays hidden after remount, a newer `latest` shows it again,
|
||||
absent for admin and when not available.
|
||||
12. Sidebar pill and mobile dot: owner and available only, pill remains after the banner is dismissed; absent for admin.
|
||||
13. No Update, Restart or progressbar element exists in any of the states above; the shown version drops the leading
|
||||
"v" ("Version 2.3.0-beta") while the Version card keeps `v2.2.0-beta`.
|
||||
|
||||
## Visual (`task visual:check -- settings` and `-- home`; desktop and mobile, light and dark; every capture within 10 %)
|
||||
|
||||
Add the setups to `web/visual/states.ts` using the board's own sample data. Exact values from
|
||||
`docs/design/source/AppFrame.dc.html` (Settings and Home blocks); layout as drawn, not from the prose.
|
||||
|
||||
- [ ] Settings: Checking (mock a never-resolving check after the click setup), Not prepared, Admin view (available),
|
||||
Too many requests (429, Retry-After 42).
|
||||
- [ ] Settings, `skip: 'clock-sensitive'` (the meta line is relative: "Last checked today at 09:41", "yesterday at 18:12"):
|
||||
Up to date, Check failed, Admin view (up to date).
|
||||
- [ ] Settings, Not prepared: command copied (the "Copied" state is time-bound; Vitest only), listed as not visual.
|
||||
- [ ] Home: Update available (owner), with the sidebar pill and the mobile dot as drawn.
|
||||
- [ ] Pending, never passing (slices 2 and 3): Update available with its Update button, Update available with notes
|
||||
open (its frame draws the Update button), Downloading, Verifying, Ready to install, Restart confirm, Restart
|
||||
request failed, Restarting, Restarting taking longer, Update done, Rolled back, Download failed, Verification
|
||||
failed, Plain restart (confirm, restarting, done), Update already running (409), Home "ready to install" banner.
|
||||
- [ ] Not covered by screenshots: keyboard and focus order, focus ring on the "Updates" heading (`id="updates-h"`),
|
||||
hover and motion, the Copy announcement, the dismiss button focus.
|
||||
|
||||
## Manual verification
|
||||
|
||||
- Replace the placeholder key: run `task release:keygen`, store the private key outside the repo, set
|
||||
`RELEASE_SIGNING_KEY` to its path, commit the printed public key as `internal/infrastructure/update/release.pub`, and
|
||||
rebuild. Never commit or paste the private key. Until this is done, `task release` must fail with the placeholder message.
|
||||
- Run `task release` with `RELEASE_SIGNING_KEY` unset, pointing to a missing file, and pointing to a key that does not
|
||||
match `release.pub`: each fails before any binary is built, with a message naming the cause. With the correct key,
|
||||
`checksums.txt` and `checksums.txt.sig` appear next to the six binaries and `cmd/releasesign verify` passes on them.
|
||||
- Against the real Gitea feed (default `UPDATE_FEED_URL`), run a dev API with a lower fake version and press "Check for
|
||||
updates" in the SPA: it reports the newest release; the "How to update" link opens that release's page.
|
||||
- Real release notes (the markdown body) render as a sensible plain-text list.
|
||||
- Restart the API and confirm the last result and `checked_at` survive, in `update-status.json` beside `DB_FILE`.
|
||||
- Embedded SPA build (no `-tags nofrontend`) serves /settings and /home with the card, banner and pill.
|
||||
- Confirm `docs/release-notes.md` (publish step: attach `checksums.txt` and `checksums.txt.sig` with the six binaries),
|
||||
`docs/deployment.md` and `docs/configuration.md` are updated, and that nothing was published.
|
||||
- Release gate: slices 1 to 3 ship together, so no released build shows `renewcms enable-browser-updates` before slice 3
|
||||
implements it.
|
||||
@@ -0,0 +1,508 @@
|
||||
Feature: Updates part 3: Restart, the privileged helper and rollback
|
||||
|
||||
As the owner of a RenewCMS site
|
||||
I want one Restart button that installs the staged release, or just restarts the site, and puts the old version back if the new one does not come up
|
||||
So that I can update from the browser while the app itself stays unprivileged and sandboxed
|
||||
|
||||
Background:
|
||||
Given slices 1 to 3 of Updates ship in one release
|
||||
And the app never gains privileges: the documented systemd unit keeps ProtectSystem=strict and only the data directory writable
|
||||
And only the helper runs as root; it is the same binary, started as "renewcms apply-update" by a oneshot systemd service
|
||||
And the data directory is the directory that holds DB_FILE; no new env var is added
|
||||
And the files in the data directory are:
|
||||
update-restart-request.json (marker, written by the app):
|
||||
{"kind":"update"|"restart","tag" (update only),"requested_at" RFC3339 UTC,"requested_by" user_id};
|
||||
update-result.json (written by the helper):
|
||||
{"outcome":"running"|"succeeded"|"rolled_back"|"failed","kind","tag","from_version","started_at","finished_at"};
|
||||
update-helper.json (status file, written by enable-browser-updates):
|
||||
{"version":1,"service","binary","data_dir","installed_at"};
|
||||
update-running.json (written by the server at every startup):
|
||||
{"version","pid","started_at"}
|
||||
And the marker is written atomically (temp file in the data directory, then rename) and deleted by the helper after reading it
|
||||
And the technical reason of a failure goes to the log or journal only, never into a file the app serves or a response
|
||||
And the domain package internal/domain/update (stdlib only) gains these interfaces, each faked in tests:
|
||||
RestartRequestStore (write, read, delete the marker),
|
||||
ResultStore (read, write and delete the result),
|
||||
RunningInfoStore (the server writes update-running.json; the helper reads it),
|
||||
HelperFilesystem (lstat, open with no-follow, read, create-exclusive, copy, rename, remove, chmod, make a fresh private
|
||||
temp directory, all of them symlink-aware),
|
||||
ServiceControl (restart and status of the systemd service),
|
||||
HealthChecker (GET http://127.0.0.1:<port>/healthz, true on 200),
|
||||
Clock
|
||||
And the helper logic depends only on those interfaces and on update.SignatureVerifier from slice 2 with the embedded release.pub
|
||||
And O_NOFOLLOW and lstat behaviour sit behind HelperFilesystem so the logic is tested on any OS; the real adapter is Linux-only
|
||||
(build-tagged) and is covered by the manual systemd checklist
|
||||
And RequestRestartUseCase and the extended GetUpdateStatusUseCase depend only on domain interfaces; handlers in
|
||||
api/handlers/update receive them through NewHandler; only api/dependecyInjection.go builds the adapters
|
||||
And POST /v1/system/update/restart is mounted in NewSystemRouter behind jwtauth.Verifier, jwtauth.Authenticator,
|
||||
RequireCurrentToken, RequireVerifiedUser and RequireOwner; there is no limiter
|
||||
And its optional JSON body is {"kind":"update"|"restart"}, bound to a request struct with
|
||||
validate:"omitempty,oneof=update restart" and checked by validator.Validate.Struct; an empty body is allowed
|
||||
And the checks on POST run in this order: no cookie or stale token (401), unverified (403), not owner (403),
|
||||
malformed body or invalid kind (400), can_apply false (409), job downloading or verifying (409), a restart already pending
|
||||
or running (409), kind that does not match the state (409), marker write error (500), then 202
|
||||
And with no body the server picks by state: job "ready" gives kind "update", anything else kind "restart"
|
||||
And the kind given must match: "update" needs a job "ready"; "restart" needs no job "ready"; otherwise 409 and nothing is written
|
||||
And POST download and POST restart delete update-result.json before they start a new job or write a marker
|
||||
And the 202 body is the status JSON with state "restarting" and started_at equal to the marker's requested_at (server clock)
|
||||
And errors are plain text from http.Error and carry no path or technical detail
|
||||
And GET /v1/system/update has no side effects; it keeps the 12 keys of slice 1 and gains exactly one key, "finished_at":
|
||||
the result's finished_at (RFC3339 UTC) whenever a result file exists, otherwise null, whatever the state
|
||||
And state is one of idle, downloading, verifying, ready, restarting, succeeded, failed, derived from the files by one rule:
|
||||
marker present, or result "running" younger than 5 minutes: "restarting";
|
||||
result "running" older than 5 minutes and no marker: "failed", error "install";
|
||||
result "succeeded", kind "update", tag equal to the running version: "succeeded";
|
||||
result "succeeded" for kind "restart", or kind "update" whose tag is no longer the running version: "idle";
|
||||
result "rolled_back": "failed", error "rolled_back";
|
||||
result "failed": "failed", error "install";
|
||||
otherwise the slice 2 job state; a missing or corrupt result file counts as no result
|
||||
And a result persists and is read the same on every GET until POST download or POST restart deletes it
|
||||
And error is null, "download", "verification", "rolled_back" or "install"
|
||||
And GET /healthz is unchanged: body "ok", no version header
|
||||
And the server writes update-running.json at every startup, after the listener is bound and before it serves, atomically; a write error
|
||||
is logged and is not fatal
|
||||
And the helper judges a restart by two things: GET /healthz answers 200 AND update-running.json holds the expected version AND it is
|
||||
NEW: its pid differs from the pid read before the restart, or its started_at is later than the instant the restart command
|
||||
was issued; a stale file with the old pid or started_at never counts
|
||||
And main gains a minimal dispatcher before the normal start: the subcommands enable-browser-updates, disable-browser-updates and
|
||||
apply-update run their own code and never read .env, open the database or listen; "--version" and the normal start are unchanged
|
||||
And the new subcommands never write a secret value or an env value into a unit file
|
||||
|
||||
Scenario: Request an update restart, happy path
|
||||
Given the owner, can_apply true and a job "ready" for "v2.3.0-beta"
|
||||
When the owner sends POST /v1/system/update/restart with no body, or with {"kind":"update"}
|
||||
Then the status is 202 and the body is the status JSON with state "restarting"
|
||||
And the marker holds kind "update", tag "v2.3.0-beta", requested_by the owner's user_id and requested_at
|
||||
And update-result.json was deleted first
|
||||
And the running binary, the staged files and the database are unchanged by the app
|
||||
And GET reports state "restarting" for any verified user
|
||||
|
||||
Scenario: Request a plain restart
|
||||
Given the owner, can_apply true and no job "ready"
|
||||
When the owner sends POST /v1/system/update/restart with no body, or with {"kind":"restart"}
|
||||
Then the status is 202, the marker holds kind "restart" and no tag, and GET reports state "restarting"
|
||||
|
||||
Scenario Outline: The kind must match the state
|
||||
Given the owner, can_apply true and <state>
|
||||
When the owner sends POST /v1/system/update/restart with {"kind":"<kind>"}
|
||||
Then the status is 409, no marker is written, the result file and the job are untouched
|
||||
|
||||
Examples:
|
||||
| state | kind |
|
||||
| no job "ready" (idle) | update |
|
||||
| a job "failed" | update |
|
||||
| a job "ready" | restart |
|
||||
|
||||
Scenario: Restart site never installs an update another owner just made ready
|
||||
Given owner A opened the Plain restart dialog while the job was idle
|
||||
And owner B then made a job "ready"
|
||||
When owner A confirms and the SPA sends {"kind":"restart"}
|
||||
Then the status is 409, nothing is installed and the staged files are untouched
|
||||
And the SPA reloads the card and shows "Ready to install"
|
||||
|
||||
Scenario Outline: A bad body is a 400
|
||||
Given the owner and can_apply true
|
||||
When the owner sends POST /v1/system/update/restart with <body>
|
||||
Then the status is 400 with a plain text body and no marker is written
|
||||
|
||||
Examples:
|
||||
| body |
|
||||
| {"kind":"upgrade"} |
|
||||
| {"kind":""} |
|
||||
| {"kind":7} |
|
||||
| {"kind":"update" |
|
||||
| not json |
|
||||
|
||||
Scenario Outline: POST is guarded like the other system routes
|
||||
When <caller> sends POST /v1/system/update/restart
|
||||
Then the status is <status> and no marker is written and no result is deleted
|
||||
|
||||
Examples:
|
||||
| caller | status | body |
|
||||
| no jwt cookie | 401 | the existing 401 text |
|
||||
| a stale token version | 401 | the existing 401 text |
|
||||
| an unverified owner | 403 | the existing unverified text |
|
||||
| an admin | 403 | apperr.OwnerRequiredErrorMessage |
|
||||
|
||||
Scenario Outline: Restart is refused with 409
|
||||
Given the owner and <condition>
|
||||
When the owner sends POST /v1/system/update/restart
|
||||
Then the status is 409, the existing marker, result and job are untouched and no new marker is written
|
||||
|
||||
Examples:
|
||||
| condition |
|
||||
| can_apply is false (no update-helper.json) |
|
||||
| the job state is downloading |
|
||||
| the job state is verifying |
|
||||
| a marker is already pending |
|
||||
| the result file reads "running" (helper at work) |
|
||||
|
||||
Scenario: Two restarts at once write one marker
|
||||
When two owners send POST /v1/system/update/restart concurrently
|
||||
Then exactly one answers 202 and the other 409 and one marker exists
|
||||
|
||||
Scenario: The marker cannot be written
|
||||
Given the data directory is not writable, or a directory sits where the marker file goes
|
||||
When the owner sends POST /v1/system/update/restart
|
||||
Then the status is 500 with a plain text body without paths, no marker exists and the job record is untouched
|
||||
|
||||
Scenario Outline: GET derives the state from the files and never changes them
|
||||
Given <files>
|
||||
When any verified user sends GET /v1/system/update twice
|
||||
Then both answers are identical, state is <state>, error is <error> and finished_at is <finished>
|
||||
And no file in the data directory changed
|
||||
|
||||
Examples:
|
||||
| files | state | error | finished |
|
||||
| a marker is present | restarting | null | null |
|
||||
| result "running" written 30 s ago | restarting | null | null |
|
||||
| result "running" written 6 minutes ago, no marker | failed | "install" | its value |
|
||||
| result "succeeded", kind "update", tag equal to the running version | succeeded | null | its value |
|
||||
| result "succeeded", kind "update", tag older than the running one | idle | null | its value |
|
||||
| result "succeeded", kind "restart" | idle | null | its value |
|
||||
| result "rolled_back" | failed | "rolled_back" | its value |
|
||||
| result "failed" | failed | "install" | its value |
|
||||
| no marker, no result | idle | null | null |
|
||||
| a corrupt result file | idle | null | null |
|
||||
|
||||
Scenario: The result lives until the next job
|
||||
Given a result "rolled_back"
|
||||
When the owner sends POST /v1/system/update/download and the job reaches "ready"
|
||||
Then the result file was deleted by the POST, GET reports state "ready", error null and finished_at null
|
||||
And GET /v1/system/update still has exactly the 12 keys of slice 1 plus finished_at
|
||||
|
||||
Scenario: After a successful update the status is consistent
|
||||
Given a result "succeeded" for "v2.3.0-beta" and the running version "v2.3.0-beta"
|
||||
Then GET reports state "succeeded", available false, current "v2.3.0-beta" and finished_at set
|
||||
|
||||
Scenario: The server writes update-running.json at startup
|
||||
When the server starts with version "v2.3.0-beta"
|
||||
Then update-running.json holds {"version":"v2.3.0-beta","pid":<its pid>,"started_at":<now>} written atomically
|
||||
And it is written after the listener is bound and before requests are served
|
||||
And a write error is logged and the server still starts
|
||||
And a second start replaces the file with the new pid and started_at
|
||||
And the file is not served by any route
|
||||
|
||||
Scenario: Healthz is unchanged
|
||||
When a client sends GET /healthz
|
||||
Then the status is 200, the body is "ok" and there is no version header, and the route stays public
|
||||
|
||||
Scenario Outline: The command dispatcher
|
||||
When the binary is run with "<args>" and an empty environment
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| args | outcome |
|
||||
| --version | it prints the version, exits 0 (unchanged from slice 2) |
|
||||
| enable-browser-updates | it runs the installer, never reads .env or opens the database |
|
||||
| disable-browser-updates | it runs the uninstaller, never reads .env or opens the database |
|
||||
| apply-update | it runs the helper, never reads .env or opens the database |
|
||||
| no arguments | the normal server start |
|
||||
| an unknown subcommand | a usage message on stderr and a non-zero exit, the server is not started |
|
||||
|
||||
Scenario Outline: enable-browser-updates refuses when it cannot work
|
||||
Given <situation>
|
||||
When "renewcms enable-browser-updates" runs
|
||||
Then it exits non-zero with the clear message "<message>" and writes nothing
|
||||
|
||||
Examples:
|
||||
| situation | message |
|
||||
| the OS is not Linux | Browser updates need Linux with systemd. |
|
||||
| Linux without systemd (no /run/systemd/system) | Browser updates need systemd, which this machine is not running. |
|
||||
| not run as root | Run this command as root, for example with sudo. |
|
||||
| no unit for the service and no flags | Could not find the RenewCMS service. Pass --service, --binary and --data-dir. |
|
||||
| the data directory cannot be resolved | Could not find the data directory. Pass --data-dir. |
|
||||
|
||||
Scenario: enable-browser-updates installs the units
|
||||
Given systemd on Linux, root, and an existing renewcms.service with ExecStart=/opt/renewcms/renewcms and ReadWritePaths=/var/lib/renewcms
|
||||
When "renewcms enable-browser-updates" runs
|
||||
Then it reads the service name, binary path and data directory from the unit, with --service, --binary and --data-dir overriding them
|
||||
And it writes renewcms-update.path (PathExists= the marker) and renewcms-update.service (Type=oneshot, User=root,
|
||||
ExecStart=<binary> apply-update with the service, binary, data directory and port as flags)
|
||||
And the port comes from --port, else from PORT in the service's environment file, else 8080
|
||||
And it runs daemon-reload and enables and starts the path unit
|
||||
And it writes update-helper.json last, so can_apply becomes true only when everything else worked
|
||||
And no secret and no environment value is written into either unit
|
||||
And it prints what it installed and how to undo it
|
||||
|
||||
Scenario: enable-browser-updates is idempotent
|
||||
Given it ran once
|
||||
When it runs again, including after the binary path or service name changed
|
||||
Then the units and the status file are rewritten to the current values, no duplicate unit exists and the exit is 0
|
||||
|
||||
Scenario: enable-browser-updates undoes its own partial work
|
||||
Given writing the second unit, daemon-reload or enable fails
|
||||
Then the first unit is removed, update-helper.json is not written and the exit is non-zero with the reason
|
||||
|
||||
Scenario: disable-browser-updates
|
||||
Given browser updates are enabled
|
||||
When "renewcms disable-browser-updates" runs
|
||||
Then the path unit is stopped and disabled, both unit files and update-helper.json are removed, daemon-reload runs
|
||||
And the marker and result files, the staged files and backups are left in place
|
||||
And running it again, or where it was never enabled, exits 0 with a message
|
||||
And can_apply reads false afterwards
|
||||
|
||||
Scenario: apply-update, a plain restart
|
||||
Given a marker of kind "restart" and update-running.json with pid 100 and started_at T0
|
||||
When the helper runs
|
||||
Then it reads the marker without following symlinks, deletes it, and writes the result "running" with started_at
|
||||
And it records the current update-running.json, restarts the service once and polls until /healthz answers 200
|
||||
and update-running.json is new (pid differs from 100, or started_at is later than the restart instant)
|
||||
And it then writes "succeeded" with kind "restart" and finished_at
|
||||
And the binary and the staged files are untouched
|
||||
|
||||
Scenario Outline: A stale running file never counts as success
|
||||
Given a marker and update-running.json that <staleness> while /healthz answers 200
|
||||
When the helper polls
|
||||
Then it keeps polling and it is not declared succeeded or rolled back until a new file appears or 60 s pass
|
||||
|
||||
Examples:
|
||||
| staleness |
|
||||
| still holds the old pid and old started_at |
|
||||
| holds the target version but the old pid and an old started_at |
|
||||
| is missing |
|
||||
| is corrupt |
|
||||
| holds the old version with a new pid (for an update) |
|
||||
|
||||
Scenario: apply-update, an update, happy path
|
||||
Given a marker of kind "update" for "v2.3.0-beta" and a staged binary, checksums.txt and checksums.txt.sig under updates/v2.3.0-beta/
|
||||
When the helper runs
|
||||
Then it creates a fresh root-owned temp directory with mode 0700 and copies the staged files into it, opening each original with no-follow
|
||||
And it verifies the signature of the COPIED checksums.txt with the embedded public key
|
||||
And it verifies the SHA-256 of the COPIED binary against its checksums.txt line, ignoring the earlier job record
|
||||
And it copies the current binary to <name>.previous, replacing an older .previous
|
||||
And it writes the verified copy to a temp file in the binary's directory (mode 0755), checks that it still hashes to the verified value,
|
||||
and installs it with an atomic rename; the original staged path is never installed
|
||||
And it restarts the service and polls /healthz and update-running.json for up to 60 s
|
||||
And when /healthz answers 200 and update-running.json is new and holds "v2.3.0-beta" it writes "succeeded", success being declared on the
|
||||
first matching poll
|
||||
And it removes the temp directory and updates/v2.3.0-beta/
|
||||
And the marker was deleted before any other step ran
|
||||
|
||||
Scenario Outline: apply-update refuses an untrusted staged binary
|
||||
Given a marker of kind "update" and <fault>
|
||||
When the helper runs
|
||||
Then the current binary is not touched, no .previous is written and the service is not restarted
|
||||
And it writes "failed", logs the technical reason only, and removes the temp directory and updates/<tag>/
|
||||
|
||||
Examples:
|
||||
| fault |
|
||||
| the binary was changed after the job verified it |
|
||||
| checksums.txt was changed |
|
||||
| the signature is from a different key or is missing |
|
||||
| checksums.txt has no line for the asset |
|
||||
| the staged binary is missing |
|
||||
|
||||
Scenario Outline: apply-update refuses symlinks
|
||||
Given a marker of kind "update" and <symlink>
|
||||
When the helper runs
|
||||
Then it never reads through the link, the current binary is untouched, there is no .previous and no restart
|
||||
And it writes "failed" and logs which path was a symlink
|
||||
And whatever the link pointed to is not read, copied, written or removed
|
||||
|
||||
Examples:
|
||||
| symlink |
|
||||
| the marker itself is a symlink |
|
||||
| <data>/updates is a symlink to another directory |
|
||||
| <data>/updates/<tag> is a symlink to another directory |
|
||||
| the staged binary is a symlink to /usr/bin/something |
|
||||
| checksums.txt is a symlink |
|
||||
| checksums.txt.sig is a symlink |
|
||||
| a symlink is placed at the result path or at a temp file name |
|
||||
|
||||
Scenario: A symlinked marker is removed, not followed
|
||||
Given the marker is a symlink to a file outside the data directory
|
||||
When the helper runs
|
||||
Then the link itself is unlinked, the target is untouched, and the result is "failed"
|
||||
|
||||
Scenario: A file swapped after verification is not installed
|
||||
Given the staged binary is verified and a fake attacker replaces the original staged path with other bytes right after the copy step
|
||||
When the helper installs
|
||||
Then the installed bytes equal the verified copy's bytes and not the swapped bytes
|
||||
And the same holds for a swap during the .previous copy and the final rename
|
||||
And a swap of the temp file in the binary's directory before the rename is caught by the re-hash and ends as "failed" with the binary untouched
|
||||
|
||||
Scenario: Result and temp files are written without following links
|
||||
Given the service user placed a symlink at update-result.json or at a predictable temp name in the data directory
|
||||
When the helper writes its result
|
||||
Then it creates a temp file with create-exclusive and no-follow, then renames it over the result, and the link target is untouched
|
||||
|
||||
Scenario Outline: apply-update distrusts the marker
|
||||
Given a marker whose tag is <tag>
|
||||
When the helper runs
|
||||
Then it writes "failed", the binary is untouched, the service is not restarted and nothing outside <data>/updates is read
|
||||
|
||||
Examples:
|
||||
| tag |
|
||||
| ../../etc/passwd |
|
||||
| v2.3.0-beta/../../x |
|
||||
| an empty string |
|
||||
| v2.1.0-beta (older than the running version) |
|
||||
| not-a-version |
|
||||
|
||||
Scenario Outline: apply-update rolls back when the new version does not come up
|
||||
Given an update marker and <fault> after the new binary was installed and the service restarted
|
||||
When the helper runs
|
||||
Then within the 60 s window it restores <name>.previous over the binary atomically and restarts the service again
|
||||
And it polls until /healthz answers 200 and a NEW update-running.json holds the old version
|
||||
And it writes "rolled_back" with from_version and tag and removes the temp directory and the staged files
|
||||
|
||||
Examples:
|
||||
| fault |
|
||||
| /healthz never answers within 60 s |
|
||||
| /healthz answers but update-running.json stays old |
|
||||
| update-running.json holds another version |
|
||||
| the service restart command fails |
|
||||
|
||||
Scenario Outline: apply-update failures around the swap
|
||||
Given an update marker and <fault>
|
||||
Then <outcome>
|
||||
|
||||
Examples:
|
||||
| fault | outcome |
|
||||
| copying to .previous fails | the binary is untouched, the service not restarted, result "failed" |
|
||||
| the atomic install fails | .previous and the old binary are intact, no restart, result "failed" |
|
||||
| the rollback restore itself fails | result "failed", logged loudly, exit non-zero |
|
||||
| the old version never returns after rollback | result "failed" (not "rolled_back"), exit non-zero |
|
||||
|
||||
Scenario: The result is always written
|
||||
Given any marker and any outcome, including a panic in the helper
|
||||
Then update-result.json holds outcome, kind, tag, from_version, started_at and finished_at, written atomically
|
||||
And a "running" record exists from the moment the marker was read until the outcome replaces it
|
||||
|
||||
Scenario: Only the helper runs with privilege
|
||||
Then the app has no code that execs systemctl, writes outside the data directory or reads the units
|
||||
And the oneshot service and path unit contain no environment secrets
|
||||
|
||||
Scenario: Settings, owner, Restart buttons (route /settings)
|
||||
Given the owner and can_apply true
|
||||
Then with state "ready" the Restart button (power, primary) is enabled and opens the Install dialog
|
||||
And with state "idle" (Up to date or Check failed) the Restart button (power, secondary) is enabled and opens the Plain restart dialog
|
||||
And with state "downloading", "verifying" or "restarting" Restart is disabled or absent as the card draws it
|
||||
And with can_apply false (Not prepared) or the admin view no Restart is rendered
|
||||
And the slice 2 disabled Restart in Ready to install is now enabled and has a handler
|
||||
And the SPA sends {"kind":"update"} from the Install dialog and {"kind":"restart"} from the Plain restart dialog, always
|
||||
|
||||
Scenario: Settings, Restart: confirm (Install dialog)
|
||||
When the owner presses Restart in Ready to install
|
||||
Then a dialog titled "Restart to finish the update?" shows "RenewCMS will install version 2.3.0-beta and restart. Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first."
|
||||
And its buttons are "Restart later" and "Restart now", the confirm is neutral, not red
|
||||
And focus moves to the first button, Escape and "Restart later" close it and focus returns to Restart
|
||||
And no request is sent until "Restart now"
|
||||
|
||||
Scenario: Settings, Plain restart: confirm
|
||||
When the owner presses Restart with no update waiting
|
||||
Then a dialog titled "Restart the site?" shows "Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first."
|
||||
And its buttons are "Cancel" and "Restart site", with the same focus and Escape behaviour
|
||||
|
||||
Scenario: Settings, Restart: request failed
|
||||
Given the confirm button is pressed and POST /v1/system/update/restart answers 500 or never reaches the server
|
||||
Then the dialog stays open (install or plain) with the error "Couldn't start the restart. Nothing was changed and your site is still running. Try again in a moment."
|
||||
And the confirm button is enabled again, no overlay shows and nothing is stored in sessionStorage
|
||||
|
||||
Scenario: Settings, this tab remembers that it started the restart
|
||||
Given POST /v1/system/update/restart answers 202 with started_at "S"
|
||||
Then sessionStorage holds one entry with the kind and "S" (the server's started_at), and no other storage is written
|
||||
And the overlay shows
|
||||
|
||||
Scenario: Settings, Restarting to install
|
||||
Given POST /v1/system/update/restart answers 202 for an update
|
||||
Then a full-page region with role "status" shows, titled "Installing version 2.3.0-beta" with
|
||||
"Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back." and a moving bar
|
||||
And it is announced once as "Installing version 2.3.0-beta. Your site is restarting."
|
||||
And the overlay survives failing requests and the Offline banner state is ignored while it shows
|
||||
And it polls GET /healthz and GET /v1/system/update every second, tolerating network errors and non-200 answers
|
||||
|
||||
Scenario: Settings, Plain restart: restarting
|
||||
Given POST /v1/system/update/restart answers 202 for a plain restart
|
||||
Then the overlay shows "Restarting your site" / "This takes about 10 seconds. This page reloads on its own when the site is back."
|
||||
And it polls the same way
|
||||
|
||||
Scenario: Settings, Restarting, taking longer
|
||||
Given 60 seconds pass with no answer from /healthz or from GET /v1/system/update
|
||||
Then the overlay shows "Still restarting" / "This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now." and a "Reload page" button
|
||||
And the meta reads "Started at 09:51 · 1 minute ago" (clock-sensitive)
|
||||
And "Reload page" reloads the page, the overlay stays until the site answers, and the polling continues
|
||||
|
||||
Scenario: Settings, the overlay ends when the site answers
|
||||
Given the overlay shows and /healthz answers and GET /v1/system/update answers with a state other than "restarting"
|
||||
and finished_at later than the stored started_at
|
||||
Then the page reloads once
|
||||
And a GET answering "restarting", a GET whose finished_at is null or not later than the stored started_at, a /healthz answer without a GET
|
||||
answer, and a rejected GET all keep the overlay and do not reload
|
||||
|
||||
Scenario: Settings, Update done (the tab that started it)
|
||||
Given the page reloaded, sessionStorage holds {kind "update", started_at "S"} and GET answers state "succeeded" with finished_at later than "S"
|
||||
Then the entry is cleared, focus lands on the "Updates" heading (id="updates-h") with the ring shown
|
||||
And a success toast "Update installed" / "RenewCMS is now on version 2.3.0-beta." is announced
|
||||
And the Version card shows the new running version and the card reads "You're on version 2.3.0-beta" /
|
||||
"The update is installed and your site is running again." / "Updated today at 09:52" with a "Read the release notes" link (arrow-up-right)
|
||||
|
||||
Scenario: Settings, Update failed, rolled back (the tab that started it)
|
||||
Given the page reloaded, sessionStorage holds {kind "update", started_at "S"} and GET answers state "failed", error "rolled_back", finished_at later than "S", running "v2.2.0-beta"
|
||||
Then the entry is cleared and focus lands on "Updates"
|
||||
And an error toast (stays until dismissed) with icon circle-x "The update didn't install" / "Your site is back on v2.2.0-beta." shows
|
||||
And the card shows icon triangle-alert (warning) "The update didn't install" /
|
||||
"RenewCMS put the previous version back, so your site is running as before. Nothing was lost." /
|
||||
"What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update." and a "Try again" button that sends POST /v1/system/update/download
|
||||
And error "install" renders the same card and toast
|
||||
|
||||
Scenario: Settings, Plain restart: done (the tab that started it)
|
||||
Given the page reloaded, sessionStorage holds {kind "restart", started_at "S"} and GET answers state "idle" with finished_at later than "S"
|
||||
Then the entry is cleared, focus lands on "Updates" and a success toast "Site restarted" / "Your site is running again." is announced
|
||||
And the card is the normal Up to date card
|
||||
|
||||
Scenario Outline: A later visit shows the card with no toast and no focus move
|
||||
Given sessionStorage has no entry, or an entry whose started_at is not earlier than finished_at, and GET answers <result>
|
||||
Then the card renders for that state, no toast shows and focus does not move to "Updates"
|
||||
And nothing is written to sessionStorage
|
||||
|
||||
Examples:
|
||||
| result |
|
||||
| state "succeeded", finished_at set |
|
||||
| state "failed", error "rolled_back" |
|
||||
| state "failed", error "install" |
|
||||
| state "idle", finished_at set (plain restart) |
|
||||
|
||||
Scenario: Settings, another owner's tab never takes the toast
|
||||
Given owner B has /settings open, with no sessionStorage entry, while GET answers "restarting" and later "succeeded"
|
||||
Then owner B's page shows the overlay while "restarting" and the card afterwards, with no toast and no focus move
|
||||
And owner A's tab, which holds the entry, still gets the toast and the focus
|
||||
And an admin sees the admin view and no overlay
|
||||
|
||||
Scenario: Settings, a stale sessionStorage entry
|
||||
Given an entry left behind by a restart that never finished in this tab (the tab was closed and reopened by hand)
|
||||
When the page loads and GET answers a finished_at that is not later than the entry's started_at, or null
|
||||
Then no toast shows, focus does not move, the entry stays until a later finished_at consumes it, and a new restart overwrites it
|
||||
|
||||
Scenario: Settings, 409 on Restart
|
||||
Given POST /v1/system/update/restart answers 409
|
||||
Then the dialog closes, nothing is stored in sessionStorage and the card reloads
|
||||
And when the reload shows downloading, verifying or restarting an info toast "An update is already running" / "Another owner started it. Progress shows here." shows and the card or overlay switches to that run
|
||||
And when the reload shows can_apply false the card shows "Not prepared" and no toast
|
||||
And when the reload shows a different "Ready to install" or "idle" (the kind did not match) the card shows that state and no toast
|
||||
|
||||
Scenario: Settings, 400 on Restart
|
||||
Given POST /v1/system/update/restart answers 400
|
||||
Then the dialog shows the "Couldn't start the restart" text and nothing is stored in sessionStorage
|
||||
|
||||
Scenario: Settings, 403 role changed on Restart
|
||||
Given POST /v1/system/update/restart answers 403
|
||||
Then the dialog closes, an error toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." shows and the card reloads in the admin view
|
||||
|
||||
Scenario: Settings, 401 on Restart
|
||||
Given POST /v1/system/update/restart answers 401
|
||||
Then the global handler goes to /login?redirect=/settings&reason=expired and no local copy shows
|
||||
|
||||
Scenario: Home banner while restarting
|
||||
Given state "restarting"
|
||||
Then Home shows no update banner and does not poll
|
||||
|
||||
Scenario: The docs gain a "Browser updates" section
|
||||
Then docs/deployment.md has "Browser updates" with the one-time command "sudo renewcms enable-browser-updates", what it installs
|
||||
(two units, update-helper.json), how to undo it ("sudo renewcms disable-browser-updates"), and what is and is not supported
|
||||
And it lists: Linux with systemd only; not Windows, macOS, Docker or other init systems; the previous binary is kept as <name>.previous
|
||||
and a database backup in backups/; an update whose new version does not come up within 60 s is rolled back automatically
|
||||
And it names the files update-restart-request.json, update-result.json, update-helper.json and update-running.json
|
||||
And the "How to update" link of the Not prepared card points at that section
|
||||
And the sentence "the site does not update itself" in the "Update checks" section is replaced
|
||||
@@ -0,0 +1,187 @@
|
||||
# QA: Updates part 3 (restart, helper, rollback)
|
||||
|
||||
## Automated Go (`task test`, package `test`, black-box, no live systemd, no real SMTP, no network)
|
||||
|
||||
Files: `test/update_restart_http_test.go` (HTTP), `test/update_restart_usecase_test.go` (request and status use cases),
|
||||
`test/update_helper_test.go` (helper logic over fakes, including rollback and hardening), `test/update_helper_install_test.go`
|
||||
(enable and disable over fakes), `test/update_helper_files_test.go` (real file adapters in `t.TempDir()`),
|
||||
`test/update_dispatch_test.go` (built binary).
|
||||
|
||||
Fakes with unique names: `fakeRestartRequestStore`, `fakeResultStore`, `fakeRunningInfoStore` (scripted per poll: absent, corrupt, stale,
|
||||
new), `fakeHelperFS`, `fakeServiceControl` (records restart calls with the clock instant; can fail), `fakeHealthChecker` (scripted per poll),
|
||||
`fakeClock` (advances without sleeping), `fakeUnitWriter` (records unit contents, can fail the Nth write). Reuse `fakeJobStore`,
|
||||
`fakeHelperDetector`, `fakeUpdateStore`, `mockUserRepo` and the throwaway ed25519 signer from slices 1 and 2. Never read the committed `release.pub`.
|
||||
|
||||
`fakeHelperFS`: an in-memory tree of files, directories and symlinks with owners and modes; `lstat`, no-follow open, create-exclusive, copy,
|
||||
rename, remove and a fresh private temp directory are the only operations; every call is recorded in order with its path; an operation that
|
||||
would traverse a symlink without the no-follow flag follows it (so a test fails if the code forgets to refuse); it can fail the Nth
|
||||
call of an operation, and it has a hook `after(op, n, mutate)` that mutates the tree after a chosen call (used to swap the original
|
||||
staged file after the copy step). Tests assert the paths the helper touched stay inside the data directory, the binary directory and
|
||||
its own temp directory.
|
||||
|
||||
HTTP setup: `validator.InitValidator()`; `jwtauth.New("HS256", []byte("test-secret"), nil)`; a fresh `chi.NewRouter()` at `/v1/system`
|
||||
mirroring `NewSystemRouter` (Verifier, Authenticator, RequireCurrentToken, RequireVerifiedUser; the restart route also RequireOwner);
|
||||
cookies as in `test/stale_token_invalidation_http_test.go`. Marker, result and job files go in `t.TempDir()` through the real JSON adapters,
|
||||
plus the fakes where noted. Helper time is driven by `fakeClock`: no `time.Sleep`, so the 60 s window runs instantly.
|
||||
|
||||
### Tests the coder must update (they exist from slices 1 and 2 and will break)
|
||||
- Slice 1 tests that assert GET /v1/system/update has exactly 12 keys: now 13, with `finished_at` (null when no result file).
|
||||
- Slice 2 tests and Vitest specs that assert the Restart button in "Ready to install" is disabled and has no handler, that no restart
|
||||
endpoint, dialog or overlay exists, and that plain Restart is not rendered: replace them with the enabled behaviour below.
|
||||
- Slice 2 "Pending states for slice 3" visual entries: they become real setups.
|
||||
- Any slice 2 test that builds the status use case with a result store must accept the new `ResultStore` dependency.
|
||||
|
||||
### HTTP and use case (Go-testable)
|
||||
1. Restart, update: ready job, can_apply on. POST with no body and POST `{"kind":"update"}` give 202 with state "restarting" and
|
||||
`started_at` equal to the marker's `requested_at`; the marker has kind "update", the tag, requested_by equal to the owner id; the result file
|
||||
was deleted first; no other file changed; GET as an admin also reads "restarting".
|
||||
2. Plain restart: idle job. No body and `{"kind":"restart"}` give 202, marker kind "restart", empty tag. Also after a failed job and after a
|
||||
rolled-back result.
|
||||
3. Kind mismatch: `{"kind":"update"}` with no ready job (idle, failed) and `{"kind":"restart"}` with a ready job give 409; no marker, result and job untouched.
|
||||
"Restart site never installs": owner A's body `{"kind":"restart"}` after the fake job store turned "ready" gives 409, no marker, staged files untouched.
|
||||
4. Bad body: `{"kind":"upgrade"}`, `{"kind":""}`, `{"kind":7}`, truncated JSON, `not json` give 400 plain text, no marker. The struct uses
|
||||
`validate:"omitempty,oneof=update restart"` and goes through `validator.Validate.Struct`; an empty body and `{}` are accepted.
|
||||
5. Guards: admin 403 with `apperr.OwnerRequiredErrorMessage+"\n"`; no cookie 401; stale token 401; unverified 403; none writes a marker or deletes the result.
|
||||
Order: an admin with a bad body gets 403, an owner with a bad body and can_apply off gets 400, can_apply off and a kind mismatch gives 409.
|
||||
6. 409 table: can_apply off, downloading, verifying, marker pending, result "running": no second marker, existing files untouched.
|
||||
7. Concurrency (`-race`): two simultaneous POSTs give one 202, one 409, one marker.
|
||||
8. 500: a directory where the marker goes, and a read-only temp directory (`t.Skip` that one on Windows): 500, plain text without the path, no marker,
|
||||
job record unchanged.
|
||||
9. State derivation, one subtest per row of the feature table. Each row calls GET twice: the two bodies are byte-identical, `state`, `error` and
|
||||
`finished_at` match, and a snapshot of every file in the data directory (names, bytes, mtimes) is unchanged by the GETs (GET has no side effects).
|
||||
The 5-minute boundary uses `fakeClock`. Assert exactly the 12 slice 1 keys plus `finished_at`.
|
||||
10. The result lives until the next job: a "rolled_back" result, then POST download and a job reaching "ready": the result is gone,
|
||||
state "ready", error null, `finished_at` null. POST restart also deletes it before writing the marker.
|
||||
11. After success: result "succeeded" for the running tag gives `available` false, `current` the new version, `finished_at` set.
|
||||
12. Server startup file: with the real running-info adapter in `t.TempDir()` write twice; the file has `version`, `pid` and `started_at`, the second
|
||||
write replaces the first, it is written by a temp file plus rename, and a write into a missing directory returns an error that the startup code logs
|
||||
(use case or startup function returns it; it does not panic). The built binary (item 15) writes it before it answers `/healthz`.
|
||||
13. `/healthz` is unchanged: body "ok", no `X-RenewCMS-Version` header, public.
|
||||
14. A new download after "rolled_back" gives 202 and later a "ready" with error null.
|
||||
15. Dispatcher: build with `go build -tags nofrontend -ldflags "-X main.version=v9.9.9" ./cmd/server` into `t.TempDir()`; with an empty environment
|
||||
`--version` prints `v9.9.9`; an unknown subcommand exits non-zero with usage and does not listen; `apply-update` and `enable-browser-updates`
|
||||
run without `.env` and create no `data/` (on a non-Linux machine the latter exits non-zero with the Linux/systemd message, which covers the Windows refusal).
|
||||
|
||||
### Helper logic over fakes (Go-testable, no systemd)
|
||||
Fixture: fake FS with the binary `/opt/renewcms/renewcms` ("old"), staged `updates/v2.3.0-beta/` binary, `checksums.txt` and `checksums.txt.sig`
|
||||
signed with a throwaway key injected through the verifier constructor, a marker, running version v2.2.0-beta, `update-running.json` with pid 100 and
|
||||
started_at T0.
|
||||
|
||||
16. Plain restart: the marker is opened no-follow and deleted first, result "running" then "succeeded", one service restart, no write to the binary.
|
||||
Success needs `/healthz` 200 AND a running file that is NEW.
|
||||
17. Stale running info, one subtest per row: old pid and old started_at; target version but old pid and old started_at; absent; corrupt; old version with a new pid
|
||||
(for an update). Health answers 200 throughout. The helper keeps polling and is not declared succeeded or rolled back until the file turns new or the
|
||||
fake clock passes 60 s. Also: a file whose started_at is later than the restart instant counts as new even with the same pid.
|
||||
18. Update happy path, asserting the ORDER of fake calls: no-follow read and delete of the marker, "running", fresh 0700 temp directory, no-follow copy of the
|
||||
three staged files into it, signature check on the copy, SHA-256 of the copied binary, copy of the current binary to `.previous`, temp file in the
|
||||
binary's directory written from the verified copy, re-hash of that temp file, atomic rename, mode 0755, record running info, restart, polls,
|
||||
"succeeded", removal of the temp directory and `updates/<tag>/`. Final FS: binary equals the new bytes, `.previous` equals the old bytes.
|
||||
Success is declared on the first matching poll, not at 60 s.
|
||||
19. Re-verification, one subtest each: tampered binary, tampered checksums.txt, other-key signature, missing signature, no line for the asset, missing
|
||||
binary. Each: binary unchanged, no `.previous`, zero restarts, result "failed", staged dir and temp dir removed, reason in the injected logger only.
|
||||
20. Symlinks, one subtest each: marker; `updates`; `updates/<tag>`; the binary; checksums.txt; checksums.txt.sig; a link at the result path; a link at a
|
||||
predictable temp file name. Each: the FS records no read, write, copy or removal through the link (the targets, placed outside the allowed
|
||||
directories with sentinel bytes, are unchanged), binary untouched, no `.previous`, zero restarts, result "failed", the log names the link path.
|
||||
The symlinked marker case: the link itself is unlinked and the target is intact.
|
||||
21. TOCTOU: with the `after` hook, replace the original staged binary with other bytes immediately after the copy step; the installed bytes equal the
|
||||
verified copy's bytes. Repeat with the swap after the signature check, after the hash check, and after the `.previous` copy. A swap of the temp file
|
||||
in the binary's directory between write and rename is caught by the re-hash: result "failed", binary untouched.
|
||||
22. Result and temp writes: create-exclusive and no-follow, then rename; a pre-planted symlink at the result path or a temp name leaves the target intact.
|
||||
23. Hostile marker tags (traversal, traversal with valid prefix, empty, older version, malformed): result "failed", zero restarts, every touched path
|
||||
under the allowed directories.
|
||||
24. Rollback table: health never answers (60 s of fake clock, about 60 polls at 1 s), healthy but running file stays old, other version in the running file,
|
||||
restart error. Each: binary restored to "old" through an atomic rename, second restart issued, polled until a NEW running file holds the old version,
|
||||
result "rolled_back" with from_version and tag, temp directory and staged dir removed.
|
||||
25. Swap failures: `.previous` copy fails (binary untouched, no restart, "failed"); atomic install fails (old binary and `.previous` intact, "failed");
|
||||
restore fails ("failed", error returned, loud log); old version never returns after rollback ("failed", not "rolled_back").
|
||||
26. Result always written: a panic in the fake service control still leaves outcome "failed" with `finished_at`; the "running" record exists before the
|
||||
first service call; writes are atomic.
|
||||
27. Timestamps come from `fakeClock`; finished is not before started.
|
||||
28. Enable, over fake FS, unit writer and service control: refuses non-Linux, no systemd, not root, no unit and no flags, no data directory (exact
|
||||
messages); on success writes both units containing the service, binary and data directory from the parsed unit, the `PathExists=` marker line and
|
||||
the port flag (`--port` over `PORT` from the env file over 8080); the units never contain `JWT_SECRET` or any value from the env file (seed the
|
||||
fixture env file with `JWT_SECRET=sentinel-secret` and search both units); flags override the unit; the status file is written LAST; running it
|
||||
twice gives identical files and one unit pair; each failing step leaves no status file and removes the first unit.
|
||||
29. Disable: removes units and the status file, keeps marker, result, staged files and backups; idempotent; a no-op where it was never enabled;
|
||||
`can_apply` reads false afterwards through the real file detector.
|
||||
30. Real adapters on `t.TempDir()`: the JSON marker, result, status and running-info stores round trip; the atomic write replaces an existing file.
|
||||
The Linux-only no-follow adapter has a test file with `//go:build linux` (it runs on Linux CI machines and the user's WSL2, and is skipped on Windows).
|
||||
31. Review items, not Go tests: the app (handlers, use cases, `api/`) execs no `systemctl` and writes only inside the data directory;
|
||||
`internal/domain/update` imports only the stdlib; use cases import no `os/exec`, `net/http`, `gorm` or adapter; the handler imports no adapter;
|
||||
the real filesystem adapter is the only code that calls `syscall.O_NOFOLLOW`; no secret in the repo; no new env var; `go vet -tags nofrontend`
|
||||
and `gofmt` clean; no comments.
|
||||
|
||||
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||
|
||||
Mock `useApi.request` for `GET /v1/system/update`, `POST .../restart` and `POST .../download`; mock `fetch` for `GET /healthz`. Fake timers drive the
|
||||
1 s polls and the 60 s switch. Stub `window.location.reload` and use a fresh `sessionStorage` per test. No test freezes the system date and none asserts a
|
||||
relative date or "09:51". Sample data: running `v2.2.0-beta`, latest `v2.3.0-beta`, `started_at` and `finished_at` as plain strings.
|
||||
|
||||
One test per state:
|
||||
1. Restart button: ready gives primary enabled; idle gives secondary enabled; downloading, verifying, restarting give disabled; can_apply false and admin give none.
|
||||
2. Install dialog: exact title, text, buttons; focus on the first button; Escape and "Restart later" close it; focus returns to Restart; no request until
|
||||
"Restart now"; the confirm is neutral; the request body is `{"kind":"update"}`.
|
||||
3. Plain restart dialog: exact copy, "Cancel" / "Restart site", same behaviour; the request body is `{"kind":"restart"}`.
|
||||
4. Restart request failed: 500 and `NetworkError`, in both dialogs: dialog stays, the exact error text, confirm enabled again, no overlay, nothing in sessionStorage. A 400 gives the same.
|
||||
5. After 202, sessionStorage holds one entry with the kind and the response's `started_at`; no localStorage write.
|
||||
6. Restarting to install: overlay `role="status"`, title and text, announced once; stays mounted when `fetch` rejects; the offline banner state is ignored; polls
|
||||
/healthz and GET every second.
|
||||
7. Plain restart: restarting: "Restarting your site" copy.
|
||||
8. Taking longer: at 60 s "Still restarting", the text, "Reload page" present; pressing it calls reload; the overlay stays.
|
||||
9. Overlay end: reload once when /healthz is ok and GET gives a non-"restarting" state with `finished_at` later than the stored `started_at`; no reload on
|
||||
"restarting", on `finished_at` null, on `finished_at` not later, on a rejected GET, or without a GET answer; reload is not called twice.
|
||||
10. Update done (entry present, state "succeeded", later `finished_at`): entry cleared, focus on `#updates-h`, success toast "Update installed" / "RenewCMS is now on version 2.3.0-beta.", card text and the "Read the release notes" link.
|
||||
11. Rolled back (error "rolled_back" and "install"): entry cleared, focus on `#updates-h`, sticky error toast, card copy, "Try again" posts download.
|
||||
12. Plain restart done (state "idle", later `finished_at`, kind "restart"): toast "Site restarted" / "Your site is running again.", focus, Up to date card, entry cleared.
|
||||
13. No entry, or an entry not earlier than `finished_at`: for each of succeeded, rolled_back, install and plain-restart-idle results the card renders with no toast, no
|
||||
focus move and no sessionStorage write.
|
||||
14. Another owner's tab: no entry, GET "restarting" then "succeeded": overlay then card, no toast, no focus move. An owner tab with an entry still gets the toast. An admin sees the
|
||||
admin view, no overlay and no poll.
|
||||
15. Stale entry: `finished_at` null or earlier than the entry's `started_at` gives no toast and keeps the entry; a new restart overwrites it.
|
||||
16. 409: reload downloading gives the info toast and progress; reload restarting gives the toast and overlay; reload can_apply false gives Not prepared and no toast; reload "ready"
|
||||
or "idle" after a kind mismatch gives that card, no toast, nothing in sessionStorage.
|
||||
17. 403: error toast and the admin view; 401 shows no local copy (the global handler is mocked).
|
||||
18. Home: no banner or poll while "restarting".
|
||||
19. Regression: slice 2's disabled-Restart assertions are replaced; Not prepared and the admin view still have no Restart.
|
||||
|
||||
## Visual (`task visual:check -- settings`; desktop and mobile, light and dark; every capture within 10 %)
|
||||
|
||||
`web/visual/states.ts` setups are added later by the coder, with the board's sample data (v2.2.0-beta, v2.3.0-beta). Exact values come from
|
||||
`docs/design/source/AppFrame.dc.html` and the "Settings" group of the Screens board; describe layout as drawn (open the frame markup for the dialog, the overlay card
|
||||
and its 440 px width before judging).
|
||||
- [ ] Restart: confirm (install dialog)
|
||||
- [ ] Plain restart: confirm
|
||||
- [ ] Restart: request failed
|
||||
- [ ] Restarting to install
|
||||
- [ ] Plain restart: restarting
|
||||
- [ ] Update failed, rolled back (the toast only if the frame draws it)
|
||||
- [ ] `skip: 'clock-sensitive'`: Update done and Plain restart: done (meta "Updated today at 09:52"), Restarting, taking longer (meta "Started at 09:51 · 1 minute ago"); their copy is covered by Vitest
|
||||
- [ ] Slice 2 pending states are now real: re-run the other Settings states and confirm Ready to install with an enabled Restart is within budget
|
||||
- [ ] If a capture exceeds 10 %, stop and report; do not widen the budget or add an exception without the user's approval
|
||||
- [ ] Not covered by screenshots: keyboard and focus order in both dialogs, the ring on `#updates-h` after the result states, the one-time overlay announcement, the motion of the bar, the Offline banner being ignored
|
||||
|
||||
## Manual only (real systemd Linux: WSL2 with systemd enabled, or a VPS): CANNOT be verified automatically
|
||||
The user will run these. The helper's decision logic, ordering, symlink refusal, TOCTOU defence and rollback are unit-tested over fakes (items 16 to 27), but none of the following is covered:
|
||||
- [ ] On Windows or macOS `renewcms enable-browser-updates` refuses with the clear message.
|
||||
- [ ] On a VPS following docs/deployment.md (service user `renewcms`, `ProtectSystem=strict`, only `/var/lib/renewcms` writable): `sudo renewcms enable-browser-updates` reads the real unit, writes
|
||||
`renewcms-update.path` and `renewcms-update.service`, enables the path unit (`systemctl status` active) and writes `update-helper.json`; a second run changes nothing.
|
||||
- [ ] The Settings page shows the Update button (can_apply true) after a reload.
|
||||
- [ ] The path unit fires when the sandboxed app writes the marker, and the app (as `renewcms`) can write the marker and cannot write the binary, the units or anything outside the data directory.
|
||||
- [ ] The server writes `update-running.json` at startup (`cat` it: version, pid, started_at) and a restart replaces it.
|
||||
- [ ] Real update from a real signed release (real `release.pub` committed, `task release` signing): Update, Ready, Restart, overlay, reload on the new version, toast on the tab that started it,
|
||||
`.previous` next to the binary, `renewcms --version` equals the new tag, `journalctl -u renewcms-update` shows the helper log.
|
||||
- [ ] Real rollback: stage a signed release whose binary prints the right `--version` but crashes at boot; the old binary is restored within about 60 s, the card reads "The update didn't install", the toast stays.
|
||||
- [ ] Plain restart: overlay, about 10 s of downtime, reload with "Site restarted".
|
||||
- [ ] The real no-follow adapter on Linux: as the service user, replace `updates/<tag>` with a symlink to `/etc`, replace the staged binary with a symlink, replace the marker with a symlink, and swap the staged file during
|
||||
an update (a loop that rewrites it); the helper refuses or installs only verified bytes, and nothing outside the data directory is read or changed.
|
||||
- [ ] Planted symlink at `update-result.json` pointing at a root-only file: the helper does not write through it.
|
||||
- [ ] Binary directory ownership, SELinux and AppArmor do not block the atomic rename, and the temp file is on the same filesystem as the binary; the helper's private temp directory is root-owned 0700 and is removed.
|
||||
- [ ] A hand-written marker with another tag, as the service user: refused, binary untouched.
|
||||
- [ ] `sudo renewcms disable-browser-updates` removes the units and status file; the card returns to "Not prepared"; nothing else is deleted.
|
||||
- [ ] A reverse proxy (nginx or Caddy) returns 502 during the restart and the overlay survives it; `/healthz` is not cached.
|
||||
- [ ] Two owners in two browsers during a restart: both show the overlay; only the tab that started it gets the toast and focus.
|
||||
- [ ] Embedded SPA build (no `-tags nofrontend`) serves `/settings` with the new dialogs and overlay.
|
||||
- [ ] Journal and files contain no secret, and technical reasons are only in the journal.
|
||||
|
||||
## Final note
|
||||
Not verifiable automatically: the whole privileged path on a real systemd Linux machine (generated units, path-unit trigger from the sandboxed app, real service restart, atomic swap on a real filesystem, real rollback, O_NOFOLLOW behaviour, permissions, SELinux or AppArmor, reverse-proxy behaviour). It needs the manual test on WSL2 with systemd or a VPS, which the user will do.
|
||||
@@ -0,0 +1,115 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
const StateIdle = "idle"
|
||||
|
||||
var (
|
||||
ErrNoRelease = errors.New("no release found")
|
||||
ErrInvalidVersion = errors.New("invalid version")
|
||||
ErrFeedUnavailable = errors.New("release feed unavailable")
|
||||
)
|
||||
|
||||
type ReleaseNotes struct {
|
||||
Version string `json:"version"`
|
||||
ReleasedAt time.Time `json:"released_at"`
|
||||
Items []string `json:"items"`
|
||||
}
|
||||
|
||||
type Asset struct {
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
|
||||
type Release struct {
|
||||
Tag string
|
||||
URL string
|
||||
PublishedAt time.Time
|
||||
Notes ReleaseNotes
|
||||
Assets []Asset
|
||||
}
|
||||
|
||||
type CheckResult struct {
|
||||
Latest string `json:"latest"`
|
||||
ReleaseURL string `json:"release_url"`
|
||||
Notes ReleaseNotes `json:"notes"`
|
||||
Assets []Asset `json:"assets"`
|
||||
CheckedAt time.Time `json:"checked_at"`
|
||||
}
|
||||
|
||||
type Progress struct {
|
||||
Percent int `json:"percent"`
|
||||
DownloadedBytes int64 `json:"downloaded_bytes"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
}
|
||||
|
||||
type UpdateStatus struct {
|
||||
Current string `json:"current"`
|
||||
Latest string `json:"latest"`
|
||||
Available bool `json:"available"`
|
||||
ReleaseURL *string `json:"release_url"`
|
||||
Notes *ReleaseNotes `json:"notes"`
|
||||
CheckedAt *time.Time `json:"checked_at"`
|
||||
CanApply bool `json:"can_apply"`
|
||||
State string `json:"state"`
|
||||
Progress *Progress `json:"progress"`
|
||||
Error *string `json:"error"`
|
||||
StartedAt *time.Time `json:"started_at"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
}
|
||||
|
||||
func NewResult(release Release, checkedAt time.Time) CheckResult {
|
||||
return CheckResult{
|
||||
Latest: release.Tag,
|
||||
ReleaseURL: release.URL,
|
||||
Notes: release.Notes,
|
||||
Assets: release.Assets,
|
||||
CheckedAt: checkedAt.UTC(),
|
||||
}
|
||||
}
|
||||
|
||||
func NewStatus(current string, result *CheckResult) UpdateStatus {
|
||||
status := UpdateStatus{Current: current, State: StateIdle}
|
||||
if result == nil {
|
||||
return status
|
||||
}
|
||||
releaseURL := result.ReleaseURL
|
||||
notes := result.Notes
|
||||
notes.Items = nonNilItems(notes.Items)
|
||||
checkedAt := result.CheckedAt
|
||||
status.Latest = result.Latest
|
||||
status.Available = IsNewer(current, result.Latest)
|
||||
status.ReleaseURL = &releaseURL
|
||||
status.Notes = ¬es
|
||||
status.CheckedAt = &checkedAt
|
||||
return status
|
||||
}
|
||||
|
||||
func nonNilItems(items []string) []string {
|
||||
if items == nil {
|
||||
return []string{}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func Newest(releases []Release) (Release, error) {
|
||||
var newest Release
|
||||
found := false
|
||||
for _, release := range releases {
|
||||
if _, err := ParseVersion(release.Tag); err != nil {
|
||||
continue
|
||||
}
|
||||
if !found || IsNewer(newest.Tag, release.Tag) {
|
||||
newest = release
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return Release{}, ErrNoRelease
|
||||
}
|
||||
return newest, nil
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNeedsLinux = errors.New("Browser updates need Linux with systemd.")
|
||||
ErrNeedsSystemd = errors.New("Browser updates need systemd, which this machine is not running.")
|
||||
ErrNeedsRoot = errors.New("Run this command as root, for example with sudo.")
|
||||
ErrServiceNotFound = errors.New("Could not find the RenewCMS service. Pass --service, --binary and --data-dir.")
|
||||
ErrDataDirNotFound = errors.New("Could not find the data directory. Pass --data-dir.")
|
||||
ErrInvalidPort = errors.New("The port must be a number between 1 and 65535.")
|
||||
)
|
||||
|
||||
const (
|
||||
OSLinux = "linux"
|
||||
pathUnitDescription = "Watch for a RenewCMS restart request"
|
||||
)
|
||||
|
||||
type ServiceDescription struct {
|
||||
Name string
|
||||
BinaryPath string
|
||||
DataDir string
|
||||
EnvironmentFile string
|
||||
}
|
||||
|
||||
type InstallOptions struct {
|
||||
Service string
|
||||
Binary string
|
||||
DataDir string
|
||||
Port string
|
||||
}
|
||||
|
||||
type MachineProbe interface {
|
||||
OS() string
|
||||
SystemdRunning() bool
|
||||
IsRoot() bool
|
||||
}
|
||||
|
||||
type ServiceLocator interface {
|
||||
Locate(name string) (ServiceDescription, bool)
|
||||
PortFromEnvironmentFile(path string) (string, bool)
|
||||
}
|
||||
|
||||
type UnitWriter interface {
|
||||
Write(name string, content string) error
|
||||
Remove(name string) (bool, error)
|
||||
}
|
||||
|
||||
type UnitManager interface {
|
||||
DaemonReload() error
|
||||
EnableNow(unit string) error
|
||||
DisableNow(unit string) error
|
||||
}
|
||||
|
||||
type HelperStatusWriter interface {
|
||||
Write(dataDir string, status HelperStatus) error
|
||||
Remove(dataDir string) (bool, error)
|
||||
}
|
||||
|
||||
func CheckInstallEnvironment(probe MachineProbe) error {
|
||||
if probe.OS() != OSLinux {
|
||||
return ErrNeedsLinux
|
||||
}
|
||||
if !probe.SystemdRunning() {
|
||||
return ErrNeedsSystemd
|
||||
}
|
||||
if !probe.IsRoot() {
|
||||
return ErrNeedsRoot
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidatePort(port string) error {
|
||||
number, err := strconv.Atoi(port)
|
||||
if err != nil || number < 1 || number > 65535 {
|
||||
return ErrInvalidPort
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func RenderPathUnit(layout HelperLayout) string {
|
||||
lines := []string{
|
||||
"[Unit]",
|
||||
"Description=" + pathUnitDescription,
|
||||
"",
|
||||
"[Path]",
|
||||
"PathExists=" + layout.RestartRequestPath(),
|
||||
"Unit=" + ServiceUnitName,
|
||||
"",
|
||||
"[Install]",
|
||||
"WantedBy=multi-user.target",
|
||||
"",
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func RenderServiceUnit(options InstallOptions) string {
|
||||
command := []string{
|
||||
quoteUnitArgument(options.Binary),
|
||||
"apply-update",
|
||||
"--service", quoteUnitArgument(options.Service),
|
||||
"--binary", quoteUnitArgument(options.Binary),
|
||||
"--data-dir", quoteUnitArgument(options.DataDir),
|
||||
"--port", options.Port,
|
||||
}
|
||||
lines := []string{
|
||||
"[Unit]",
|
||||
"Description=RenewCMS update helper",
|
||||
"",
|
||||
"[Service]",
|
||||
"Type=oneshot",
|
||||
"User=root",
|
||||
"ExecStart=" + strings.Join(command, " "),
|
||||
"",
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
var unitArgumentEscaper = strings.NewReplacer(
|
||||
`\`, `\\`,
|
||||
`"`, `\"`,
|
||||
`%`, `%%`,
|
||||
`$`, `$$`,
|
||||
"\n", `\n`,
|
||||
"\r", `\r`,
|
||||
"\t", `\t`,
|
||||
)
|
||||
|
||||
func quoteUnitArgument(value string) string {
|
||||
if !strings.ContainsAny(value, " \t\r\n\"'\\%$;") {
|
||||
return value
|
||||
}
|
||||
return `"` + unitArgumentEscaper.Replace(value) + `"`
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
StateDownloading = "downloading"
|
||||
StateVerifying = "verifying"
|
||||
StateReady = "ready"
|
||||
StateFailed = "failed"
|
||||
|
||||
ErrorKindDownload = "download"
|
||||
ErrorKindVerification = "verification"
|
||||
|
||||
ChecksumsAssetName = "checksums.txt"
|
||||
SignatureAssetName = "checksums.txt.sig"
|
||||
|
||||
windowsOS = "windows"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotPrepared = errors.New("this server cannot apply updates")
|
||||
ErrJobInProgress = errors.New("an update job is already running or ready")
|
||||
ErrNothingToUpdate = errors.New("there is nothing to update")
|
||||
ErrPreflightRefused = errors.New("the update cannot be downloaded")
|
||||
)
|
||||
|
||||
type Platform struct {
|
||||
OS string
|
||||
Arch string
|
||||
}
|
||||
|
||||
type Job struct {
|
||||
Tag string `json:"tag"`
|
||||
State string `json:"state"`
|
||||
Error string `json:"error"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
DownloadedBytes int64 `json:"downloaded_bytes"`
|
||||
TotalBytes int64 `json:"total_bytes"`
|
||||
StagedBinary string `json:"staged_binary"`
|
||||
}
|
||||
|
||||
type ProgressFunc func(done int64, total int64)
|
||||
|
||||
type AssetFetcher interface {
|
||||
Fetch(asset Asset, destination string, report ProgressFunc) error
|
||||
}
|
||||
|
||||
type SignatureVerifier interface {
|
||||
Verify(checksumsPath string, signaturePath string) error
|
||||
}
|
||||
|
||||
type StagedBinaryRunner interface {
|
||||
Version(binaryPath string) (string, error)
|
||||
}
|
||||
|
||||
type DatabaseBackup interface {
|
||||
Backup() (string, error)
|
||||
}
|
||||
|
||||
type StagingArea interface {
|
||||
Prepare(tag string) error
|
||||
PathFor(tag string, name string) string
|
||||
Size(path string) (int64, error)
|
||||
ReadChecksums(path string) (string, error)
|
||||
MakeExecutable(path string) error
|
||||
Remove(tag string) error
|
||||
}
|
||||
|
||||
type HelperDetector interface {
|
||||
Installed() bool
|
||||
}
|
||||
|
||||
type JobStore interface {
|
||||
Load() (Job, bool)
|
||||
Save(job Job) error
|
||||
}
|
||||
|
||||
type Logger interface {
|
||||
Printf(format string, args ...any)
|
||||
}
|
||||
|
||||
func (j Job) IsRunning() bool {
|
||||
return j.State == StateDownloading || j.State == StateVerifying
|
||||
}
|
||||
|
||||
func (j Job) Occupies() bool {
|
||||
return j.IsRunning() || j.State == StateReady
|
||||
}
|
||||
|
||||
func (j Job) Progress() *Progress {
|
||||
if j.State != StateDownloading || j.TotalBytes <= 0 {
|
||||
return nil
|
||||
}
|
||||
return &Progress{
|
||||
Percent: int(j.DownloadedBytes * 100 / j.TotalBytes),
|
||||
DownloadedBytes: j.DownloadedBytes,
|
||||
TotalBytes: j.TotalBytes,
|
||||
}
|
||||
}
|
||||
|
||||
func (s UpdateStatus) WithJob(job Job) UpdateStatus {
|
||||
s.State = job.State
|
||||
s.Progress = job.Progress()
|
||||
s.Error = nil
|
||||
if job.Error != "" {
|
||||
kind := job.Error
|
||||
s.Error = &kind
|
||||
}
|
||||
startedAt := job.StartedAt
|
||||
s.StartedAt = &startedAt
|
||||
return s
|
||||
}
|
||||
|
||||
func AssetName(tag string, platform Platform) string {
|
||||
name := "renewcms_" + tag + "_" + platform.OS + "_" + platform.Arch
|
||||
if platform.OS == windowsOS {
|
||||
name += ".exe"
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func FindAsset(assets []Asset, name string) (Asset, bool) {
|
||||
for _, asset := range assets {
|
||||
if asset.Name == name {
|
||||
return asset, true
|
||||
}
|
||||
}
|
||||
return Asset{}, false
|
||||
}
|
||||
|
||||
func HostOf(rawURL string) string {
|
||||
parsed, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return parsed.Host
|
||||
}
|
||||
|
||||
func IsAllowedAssetURL(rawURL string, allowedHost string) bool {
|
||||
parsed, err := url.Parse(rawURL)
|
||||
if err != nil || parsed.Scheme != "https" {
|
||||
return false
|
||||
}
|
||||
return allowedHost != "" && parsed.Host == allowedHost
|
||||
}
|
||||
|
||||
func ChecksumFor(checksums string, assetName string) (string, bool) {
|
||||
for _, line := range strings.Split(checksums, "\n") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) == 2 && strings.TrimPrefix(fields[1], "*") == assetName {
|
||||
return strings.ToLower(fields[0]), true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func FileSHA256(path string) (string, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
hash := sha256.New()
|
||||
if _, err := io.Copy(hash, file); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(hash.Sum(nil)), nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"path"
|
||||
)
|
||||
|
||||
const (
|
||||
RestartRequestFileName = "update-restart-request.json"
|
||||
ResultFileName = "update-result.json"
|
||||
HelperStatusFileName = "update-helper.json"
|
||||
RunningInfoFileName = "update-running.json"
|
||||
UpdatesDirName = "updates"
|
||||
HelperStatusVersion = 1
|
||||
|
||||
PathUnitName = "renewcms-update.path"
|
||||
ServiceUnitName = "renewcms-update.service"
|
||||
DefaultService = "renewcms"
|
||||
DefaultPort = "8080"
|
||||
|
||||
PreviousSuffix = ".previous"
|
||||
PreviousTempSuffix = ".previous.tmp"
|
||||
InstallTempSuffix = ".new"
|
||||
RestoreTempSuffix = ".restore"
|
||||
ResultTempSuffix = ".tmp"
|
||||
ExecutableMode = 0o755
|
||||
PrivateFileMode = 0o600
|
||||
)
|
||||
|
||||
type HelperLayout struct {
|
||||
DataDir string
|
||||
BinaryPath string
|
||||
}
|
||||
|
||||
func (l HelperLayout) UpdatesDir() string {
|
||||
return path.Join(l.DataDir, UpdatesDirName)
|
||||
}
|
||||
|
||||
func (l HelperLayout) StagedDir(tag string) string {
|
||||
return path.Join(l.UpdatesDir(), tag)
|
||||
}
|
||||
|
||||
func (l HelperLayout) ResultPath() string {
|
||||
return path.Join(l.DataDir, ResultFileName)
|
||||
}
|
||||
|
||||
func (l HelperLayout) ResultTempPath() string {
|
||||
return l.ResultPath() + ResultTempSuffix
|
||||
}
|
||||
|
||||
func (l HelperLayout) RestartRequestPath() string {
|
||||
return path.Join(l.DataDir, RestartRequestFileName)
|
||||
}
|
||||
|
||||
func (l HelperLayout) PreviousPath() string {
|
||||
return l.BinaryPath + PreviousSuffix
|
||||
}
|
||||
|
||||
func SHA256Hex(content []byte) string {
|
||||
sum := sha256.Sum256(content)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
bulletLine = regexp.MustCompile(`^[-*+]\s+(.+)$`)
|
||||
markdownLink = regexp.MustCompile(`!?\[([^\]]*)\]\([^)]*\)`)
|
||||
boldText = regexp.MustCompile(`\*\*([^*]+)\*\*|__([^_]+)__`)
|
||||
italicText = regexp.MustCompile(`\*([^*\s][^*]*)\*`)
|
||||
inlineCode = regexp.MustCompile("`([^`]*)`")
|
||||
)
|
||||
|
||||
func BuildNotes(tag string, publishedAt time.Time, body string) ReleaseNotes {
|
||||
items := []string{}
|
||||
for _, line := range strings.Split(body, "\n") {
|
||||
match := bulletLine.FindStringSubmatch(strings.TrimSpace(line))
|
||||
if match == nil {
|
||||
continue
|
||||
}
|
||||
if item := plainText(match[1]); item != "" {
|
||||
items = append(items, item)
|
||||
}
|
||||
}
|
||||
return ReleaseNotes{Version: tag, ReleasedAt: publishedAt, Items: items}
|
||||
}
|
||||
|
||||
func plainText(markdown string) string {
|
||||
text := markdownLink.ReplaceAllString(markdown, "$1")
|
||||
text = boldText.ReplaceAllString(text, "$1$2")
|
||||
text = italicText.ReplaceAllString(text, "$1")
|
||||
text = inlineCode.ReplaceAllString(text, "$1")
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package update
|
||||
|
||||
type ReleaseFeed interface {
|
||||
Latest() (Release, error)
|
||||
}
|
||||
|
||||
type StatusStore interface {
|
||||
Load() (CheckResult, bool)
|
||||
Save(result CheckResult) error
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
StateRestarting = "restarting"
|
||||
StateSucceeded = "succeeded"
|
||||
|
||||
ErrorKindRolledBack = "rolled_back"
|
||||
ErrorKindInstall = "install"
|
||||
|
||||
RestartKindUpdate = "update"
|
||||
RestartKindRestart = "restart"
|
||||
|
||||
OutcomeRunning = "running"
|
||||
OutcomeSucceeded = "succeeded"
|
||||
OutcomeRolledBack = "rolled_back"
|
||||
OutcomeFailed = "failed"
|
||||
|
||||
RunningResultMaxAge = 5 * time.Minute
|
||||
)
|
||||
|
||||
var (
|
||||
ErrRestartPending = errors.New("a restart is already pending or running")
|
||||
ErrRestartKindMismatch = errors.New("the requested restart does not match the current state")
|
||||
ErrNoRestartRequest = errors.New("there is no restart request")
|
||||
ErrSymlinkRefused = errors.New("a symbolic link was found where a regular file is required")
|
||||
ErrInvalidRestartTag = errors.New("the restart request names an invalid version")
|
||||
ErrHelperUnsupported = errors.New("the privileged helper needs Linux")
|
||||
)
|
||||
|
||||
var restartTagPattern = regexp.MustCompile(`^v[0-9]+(\.[0-9]+)*(-[0-9A-Za-z.]+)?$`)
|
||||
|
||||
type RestartRequest struct {
|
||||
Kind string `json:"kind"`
|
||||
Tag string `json:"tag,omitempty"`
|
||||
RequestedAt time.Time `json:"requested_at"`
|
||||
RequestedBy uint32 `json:"requested_by"`
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Outcome string `json:"outcome"`
|
||||
Kind string `json:"kind"`
|
||||
Tag string `json:"tag"`
|
||||
FromVersion string `json:"from_version"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
FinishedAt *time.Time `json:"finished_at"`
|
||||
}
|
||||
|
||||
type RunningInfo struct {
|
||||
Version string `json:"version"`
|
||||
Pid int `json:"pid"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
}
|
||||
|
||||
type HelperStatus struct {
|
||||
Version int `json:"version"`
|
||||
Service string `json:"service"`
|
||||
Binary string `json:"binary"`
|
||||
DataDir string `json:"data_dir"`
|
||||
InstalledAt time.Time `json:"installed_at"`
|
||||
}
|
||||
|
||||
type FileInfo struct {
|
||||
IsSymlink bool
|
||||
IsDir bool
|
||||
IsRegular bool
|
||||
}
|
||||
|
||||
type RestartRequestStore interface {
|
||||
Write(request RestartRequest) error
|
||||
Read() (RestartRequest, error)
|
||||
Delete() error
|
||||
}
|
||||
|
||||
type ResultStore interface {
|
||||
Read() (Result, bool)
|
||||
Write(result Result) error
|
||||
Delete() error
|
||||
}
|
||||
|
||||
type RunningInfoStore interface {
|
||||
Write(info RunningInfo) error
|
||||
Read() (RunningInfo, bool)
|
||||
}
|
||||
|
||||
type HelperFilesystem interface {
|
||||
Lstat(path string) (FileInfo, error)
|
||||
ReadFile(path string) ([]byte, error)
|
||||
CreateExclusive(path string, content []byte, mode uint32) error
|
||||
Copy(source string, destination string, mode uint32) error
|
||||
Rename(oldPath string, newPath string) error
|
||||
Remove(path string) error
|
||||
RemoveAll(path string) error
|
||||
Chmod(path string, mode uint32) error
|
||||
MakePrivateTempDir() (string, error)
|
||||
}
|
||||
|
||||
type ServiceControl interface {
|
||||
Restart() error
|
||||
Status() (bool, error)
|
||||
}
|
||||
|
||||
type HealthChecker interface {
|
||||
Healthy() bool
|
||||
}
|
||||
|
||||
type Clock interface {
|
||||
Now() time.Time
|
||||
Sleep(duration time.Duration)
|
||||
}
|
||||
|
||||
func ValidateRestartTag(tag string, runningVersion string) error {
|
||||
if !restartTagPattern.MatchString(tag) {
|
||||
return ErrInvalidRestartTag
|
||||
}
|
||||
if _, err := ParseVersion(tag); err != nil || !IsNewer(runningVersion, tag) {
|
||||
return ErrInvalidRestartTag
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Result) IsRunning() bool {
|
||||
return r.Outcome == OutcomeRunning
|
||||
}
|
||||
|
||||
func (r Result) IsKnown() bool {
|
||||
switch r.Outcome {
|
||||
case OutcomeRunning, OutcomeSucceeded, OutcomeRolledBack, OutcomeFailed:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (i RunningInfo) IsNewerThan(previous RunningInfo, restartedAt time.Time) bool {
|
||||
return i.Pid != previous.Pid || i.StartedAt.After(restartedAt)
|
||||
}
|
||||
|
||||
const (
|
||||
RestartWindow = 60 * time.Second
|
||||
PollInterval = time.Second
|
||||
)
|
||||
|
||||
type SymlinkError struct {
|
||||
Path string
|
||||
}
|
||||
|
||||
func (e SymlinkError) Error() string {
|
||||
return e.Path + " is a symbolic link"
|
||||
}
|
||||
|
||||
func (e SymlinkError) Is(target error) bool {
|
||||
return target == ErrSymlinkRefused
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package update
|
||||
|
||||
import "time"
|
||||
|
||||
func (s UpdateStatus) WithRestartRequest(request RestartRequest) UpdateStatus {
|
||||
return s.settled(StateRestarting, "", request.RequestedAt)
|
||||
}
|
||||
|
||||
func (s UpdateStatus) WithResult(result Result, currentVersion string, now time.Time) UpdateStatus {
|
||||
if result.IsRunning() && now.Sub(result.StartedAt) < RunningResultMaxAge {
|
||||
return s.settled(StateRestarting, "", result.StartedAt)
|
||||
}
|
||||
if result.IsRunning() || result.Outcome == OutcomeFailed {
|
||||
return s.settled(StateFailed, ErrorKindInstall, result.StartedAt)
|
||||
}
|
||||
if result.Outcome == OutcomeRolledBack {
|
||||
return s.settled(StateFailed, ErrorKindRolledBack, result.StartedAt)
|
||||
}
|
||||
if result.Kind == RestartKindUpdate && result.Tag == currentVersion {
|
||||
return s.settled(StateSucceeded, "", result.StartedAt)
|
||||
}
|
||||
s.State = StateIdle
|
||||
s.Progress = nil
|
||||
s.Error = nil
|
||||
s.StartedAt = nil
|
||||
return s
|
||||
}
|
||||
|
||||
func (s UpdateStatus) settled(state string, errorKind string, startedAt time.Time) UpdateStatus {
|
||||
s.State = state
|
||||
s.Progress = nil
|
||||
s.Error = nil
|
||||
if errorKind != "" {
|
||||
s.Error = &errorKind
|
||||
}
|
||||
s.StartedAt = &startedAt
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Version struct {
|
||||
numbers []int
|
||||
pre []string
|
||||
}
|
||||
|
||||
func ParseVersion(raw string) (Version, error) {
|
||||
trimmed := strings.TrimPrefix(strings.TrimSpace(raw), "v")
|
||||
core, pre, hasPre := strings.Cut(trimmed, "-")
|
||||
if core == "" || (hasPre && pre == "") {
|
||||
return Version{}, ErrInvalidVersion
|
||||
}
|
||||
var version Version
|
||||
for _, segment := range strings.Split(core, ".") {
|
||||
number, err := strconv.Atoi(segment)
|
||||
if err != nil || number < 0 {
|
||||
return Version{}, ErrInvalidVersion
|
||||
}
|
||||
version.numbers = append(version.numbers, number)
|
||||
}
|
||||
if hasPre {
|
||||
version.pre = strings.Split(pre, ".")
|
||||
}
|
||||
return version, nil
|
||||
}
|
||||
|
||||
func IsNewer(current, latest string) bool {
|
||||
currentVersion, err := ParseVersion(current)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
latestVersion, err := ParseVersion(latest)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return compareVersions(latestVersion, currentVersion) > 0
|
||||
}
|
||||
|
||||
func compareVersions(a, b Version) int {
|
||||
if order := compareNumbers(a.numbers, b.numbers); order != 0 {
|
||||
return order
|
||||
}
|
||||
return comparePreRelease(a.pre, b.pre)
|
||||
}
|
||||
|
||||
func compareNumbers(a, b []int) int {
|
||||
for i := range max(len(a), len(b)) {
|
||||
if order := cmp.Compare(segmentAt(a, i), segmentAt(b, i)); order != 0 {
|
||||
return order
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func segmentAt(numbers []int, index int) int {
|
||||
if index < len(numbers) {
|
||||
return numbers[index]
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func comparePreRelease(a, b []string) int {
|
||||
if len(a) == 0 && len(b) == 0 {
|
||||
return 0
|
||||
}
|
||||
if len(a) == 0 {
|
||||
return 1
|
||||
}
|
||||
if len(b) == 0 {
|
||||
return -1
|
||||
}
|
||||
length := min(len(a), len(b))
|
||||
for i := 0; i < length; i++ {
|
||||
if order := compareIdentifiers(a[i], b[i]); order != 0 {
|
||||
return order
|
||||
}
|
||||
}
|
||||
return cmp.Compare(len(a), len(b))
|
||||
}
|
||||
|
||||
func compareIdentifiers(a, b string) int {
|
||||
numberA, errA := strconv.Atoi(a)
|
||||
numberB, errB := strconv.Atoi(b)
|
||||
if errA == nil && errB == nil {
|
||||
return cmp.Compare(numberA, numberB)
|
||||
}
|
||||
if errA == nil {
|
||||
return -1
|
||||
}
|
||||
if errB == nil {
|
||||
return 1
|
||||
}
|
||||
return strings.Compare(a, b)
|
||||
}
|
||||
@@ -32,6 +32,7 @@ type Settings struct {
|
||||
AuthRateLimit AuthRateLimitSettings
|
||||
TrustedProxies []string
|
||||
Version string
|
||||
UpdateFeedURL string
|
||||
}
|
||||
|
||||
func (s Settings) IsProduction() bool {
|
||||
@@ -74,6 +75,7 @@ func NewSettingsFromEnv() (Settings, error) {
|
||||
Window: time.Duration(authRateLimitWindowSeconds) * time.Second,
|
||||
},
|
||||
TrustedProxies: parseSemicolonSeparatedList(os.Getenv("TRUSTED_PROXIES")),
|
||||
UpdateFeedURL: os.Getenv("UPDATE_FEED_URL"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
)
|
||||
|
||||
const readableFilePermissions = 0o644
|
||||
|
||||
func writeFileAtomically(path string, content []byte, permissions os.FileMode) error {
|
||||
temporary := path + ".tmp"
|
||||
if err := os.WriteFile(temporary, content, permissions); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(temporary, path); err != nil {
|
||||
_ = os.Remove(temporary)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeJSONAtomically(path string, value any, permissions os.FileMode) error {
|
||||
content, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return writeFileAtomically(path, content, permissions)
|
||||
}
|
||||
|
||||
func removeFile(path string) (bool, error) {
|
||||
err := os.Remove(path)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func removeIfPresent(path string) error {
|
||||
_, err := removeFile(path)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
errSignatureEncoding = errors.New("the signature is not a base64 encoded ed25519 signature")
|
||||
errSignatureMismatch = errors.New("the signature does not match the checksums file")
|
||||
)
|
||||
|
||||
type Ed25519SignatureVerifier struct {
|
||||
key ed25519.PublicKey
|
||||
}
|
||||
|
||||
var _ domain.SignatureVerifier = &Ed25519SignatureVerifier{}
|
||||
|
||||
func NewEd25519SignatureVerifier(key ed25519.PublicKey) *Ed25519SignatureVerifier {
|
||||
return &Ed25519SignatureVerifier{key: key}
|
||||
}
|
||||
|
||||
func (v *Ed25519SignatureVerifier) Verify(checksumsPath string, signaturePath string) error {
|
||||
content, err := os.ReadFile(checksumsPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rawSignature, err := os.ReadFile(signaturePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
signature, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(rawSignature)))
|
||||
if err != nil || len(signature) != ed25519.SignatureSize {
|
||||
return errSignatureEncoding
|
||||
}
|
||||
if len(v.key) != ed25519.PublicKeySize || !ed25519.Verify(v.key, content, signature) {
|
||||
return errSignatureMismatch
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"context"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const stagedBinaryRunTimeout = 15 * time.Second
|
||||
|
||||
type ExecStagedBinaryRunner struct{}
|
||||
|
||||
var _ domain.StagedBinaryRunner = &ExecStagedBinaryRunner{}
|
||||
|
||||
func NewExecStagedBinaryRunner() *ExecStagedBinaryRunner {
|
||||
return &ExecStagedBinaryRunner{}
|
||||
}
|
||||
|
||||
func (r *ExecStagedBinaryRunner) Version(binaryPath string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), stagedBinaryRunTimeout)
|
||||
defer cancel()
|
||||
output, err := exec.CommandContext(ctx, binaryPath, "--version").Output()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(string(output)), nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"os"
|
||||
)
|
||||
|
||||
type FileHelperDetector struct {
|
||||
statusPath string
|
||||
}
|
||||
|
||||
var _ domain.HelperDetector = &FileHelperDetector{}
|
||||
|
||||
func NewFileHelperDetector(statusPath string) *FileHelperDetector {
|
||||
return &FileHelperDetector{statusPath: statusPath}
|
||||
}
|
||||
|
||||
func (d *FileHelperDetector) Installed() bool {
|
||||
content, err := os.ReadFile(d.statusPath)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
var status map[string]any
|
||||
return json.Unmarshal(content, &status) == nil && status != nil
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
)
|
||||
|
||||
type FSRestartRequestStore struct {
|
||||
files domain.HelperFilesystem
|
||||
path string
|
||||
}
|
||||
|
||||
var _ domain.RestartRequestStore = &FSRestartRequestStore{}
|
||||
|
||||
func NewFSRestartRequestStore(files domain.HelperFilesystem, path string) *FSRestartRequestStore {
|
||||
return &FSRestartRequestStore{files: files, path: path}
|
||||
}
|
||||
|
||||
func (s *FSRestartRequestStore) Write(request domain.RestartRequest) error {
|
||||
return writeJSONThroughTemporary(s.files, s.path, request, statusFilePermissions)
|
||||
}
|
||||
|
||||
func (s *FSRestartRequestStore) Read() (domain.RestartRequest, error) {
|
||||
info, err := s.files.Lstat(s.path)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return domain.RestartRequest{}, domain.ErrNoRestartRequest
|
||||
}
|
||||
if err != nil {
|
||||
return domain.RestartRequest{}, err
|
||||
}
|
||||
if info.IsSymlink {
|
||||
return domain.RestartRequest{}, domain.SymlinkError{Path: s.path}
|
||||
}
|
||||
if !info.IsRegular {
|
||||
return domain.RestartRequest{}, fmt.Errorf("%s is not a regular file", s.path)
|
||||
}
|
||||
content, err := s.files.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.RestartRequest{}, err
|
||||
}
|
||||
var request domain.RestartRequest
|
||||
return request, json.Unmarshal(content, &request)
|
||||
}
|
||||
|
||||
func (s *FSRestartRequestStore) Delete() error {
|
||||
return removeThrough(s.files, s.path)
|
||||
}
|
||||
|
||||
func removeThrough(files domain.HelperFilesystem, path string) error {
|
||||
if err := files.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeJSONThroughTemporary(files domain.HelperFilesystem, path string, value any, mode uint32) error {
|
||||
content, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return writeThroughTemporary(files, path, content, mode)
|
||||
}
|
||||
|
||||
func writeThroughTemporary(files domain.HelperFilesystem, path string, content []byte, mode uint32) error {
|
||||
temporary := path + domain.ResultTempSuffix
|
||||
if _, err := files.Lstat(temporary); err == nil {
|
||||
if err := files.Remove(temporary); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := files.CreateExclusive(temporary, content, mode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := files.Rename(temporary, path); err != nil {
|
||||
_ = files.Remove(temporary)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
)
|
||||
|
||||
type FSResultStore struct {
|
||||
files domain.HelperFilesystem
|
||||
path string
|
||||
}
|
||||
|
||||
var _ domain.ResultStore = &FSResultStore{}
|
||||
|
||||
func NewFSResultStore(files domain.HelperFilesystem, path string) *FSResultStore {
|
||||
return &FSResultStore{files: files, path: path}
|
||||
}
|
||||
|
||||
func (s *FSResultStore) Read() (domain.Result, bool) {
|
||||
info, err := s.files.Lstat(s.path)
|
||||
if err != nil || !info.IsRegular {
|
||||
return domain.Result{}, false
|
||||
}
|
||||
content, err := s.files.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.Result{}, false
|
||||
}
|
||||
return decodeResult(content)
|
||||
}
|
||||
|
||||
func (s *FSResultStore) Write(result domain.Result) error {
|
||||
return writeJSONThroughTemporary(s.files, s.path, result, readableFilePermissions)
|
||||
}
|
||||
|
||||
func (s *FSResultStore) Delete() error {
|
||||
return removeThrough(s.files, s.path)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
releasesPath = "/api/v1/repos/fsylvain/RenewCMS/releases"
|
||||
feedRequestTimeout = 10 * time.Second
|
||||
maxFeedBodyBytes = 4 << 20
|
||||
)
|
||||
|
||||
type GiteaReleaseFeed struct {
|
||||
baseURL string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
var _ domain.ReleaseFeed = &GiteaReleaseFeed{}
|
||||
|
||||
type giteaRelease struct {
|
||||
TagName string `json:"tag_name"`
|
||||
HTMLURL string `json:"html_url"`
|
||||
Body string `json:"body"`
|
||||
Draft bool `json:"draft"`
|
||||
PublishedAt time.Time `json:"published_at"`
|
||||
Assets []giteaAsset `json:"assets"`
|
||||
}
|
||||
|
||||
type giteaAsset struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
DownloadURL string `json:"browser_download_url"`
|
||||
}
|
||||
|
||||
func NewGiteaReleaseFeed(baseURL string) *GiteaReleaseFeed {
|
||||
return &GiteaReleaseFeed{
|
||||
baseURL: strings.TrimRight(baseURL, "/"),
|
||||
client: &http.Client{Timeout: feedRequestTimeout},
|
||||
}
|
||||
}
|
||||
|
||||
func (g *GiteaReleaseFeed) Latest() (domain.Release, error) {
|
||||
releases, err := g.fetch()
|
||||
if err != nil {
|
||||
return domain.Release{}, err
|
||||
}
|
||||
return domain.Newest(releases)
|
||||
}
|
||||
|
||||
func (g *GiteaReleaseFeed) fetch() ([]domain.Release, error) {
|
||||
response, err := g.client.Get(g.baseURL + releasesPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", domain.ErrFeedUnavailable, err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("%w: status %d", domain.ErrFeedUnavailable, response.StatusCode)
|
||||
}
|
||||
var raw []giteaRelease
|
||||
if err := json.NewDecoder(io.LimitReader(response.Body, maxFeedBodyBytes)).Decode(&raw); err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", domain.ErrFeedUnavailable, err)
|
||||
}
|
||||
return toReleases(raw), nil
|
||||
}
|
||||
|
||||
func toReleases(raw []giteaRelease) []domain.Release {
|
||||
releases := make([]domain.Release, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
if item.Draft {
|
||||
continue
|
||||
}
|
||||
releases = append(releases, domain.Release{
|
||||
Tag: item.TagName,
|
||||
URL: item.HTMLURL,
|
||||
PublishedAt: item.PublishedAt,
|
||||
Notes: domain.BuildNotes(item.TagName, item.PublishedAt, item.Body),
|
||||
Assets: toAssets(item.Assets),
|
||||
})
|
||||
}
|
||||
return releases
|
||||
}
|
||||
|
||||
func toAssets(raw []giteaAsset) []domain.Asset {
|
||||
assets := make([]domain.Asset, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
assets = append(assets, domain.Asset{Name: item.Name, URL: item.DownloadURL, Size: item.Size})
|
||||
}
|
||||
return assets
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
maxBinaryBytes int64 = 200 << 20
|
||||
maxChecksumsBytes int64 = 64 << 10
|
||||
maxSignatureBytes int64 = 1 << 10
|
||||
assetDownloadTimeout = 10 * time.Minute
|
||||
maxAssetRedirects = 5
|
||||
assetFilePermission = 0o644
|
||||
signatureSuffix = ".sig"
|
||||
)
|
||||
|
||||
var (
|
||||
errAssetURLRefused = errors.New("the asset url is not https on the release feed host")
|
||||
errAssetStatus = errors.New("the asset server answered with an error status")
|
||||
errAssetTooLarge = errors.New("the asset is larger than its size cap")
|
||||
errTooManyRedirects = errors.New("the asset url redirected too many times")
|
||||
)
|
||||
|
||||
type FileOpener func(path string) (io.WriteCloser, error)
|
||||
|
||||
type HTTPAssetFetcher struct {
|
||||
allowedHost string
|
||||
allowInsecure bool
|
||||
sizeCap int64
|
||||
timeout time.Duration
|
||||
transport http.RoundTripper
|
||||
openFile FileOpener
|
||||
}
|
||||
|
||||
var _ domain.AssetFetcher = &HTTPAssetFetcher{}
|
||||
|
||||
type FetcherOption func(*HTTPAssetFetcher)
|
||||
|
||||
func WithInsecureScheme() FetcherOption {
|
||||
return func(f *HTTPAssetFetcher) { f.allowInsecure = true }
|
||||
}
|
||||
|
||||
func WithSizeCap(bytes int64) FetcherOption {
|
||||
return func(f *HTTPAssetFetcher) { f.sizeCap = bytes }
|
||||
}
|
||||
|
||||
func WithTimeout(timeout time.Duration) FetcherOption {
|
||||
return func(f *HTTPAssetFetcher) { f.timeout = timeout }
|
||||
}
|
||||
|
||||
func WithTransport(transport http.RoundTripper) FetcherOption {
|
||||
return func(f *HTTPAssetFetcher) { f.transport = transport }
|
||||
}
|
||||
|
||||
func WithFileOpener(opener FileOpener) FetcherOption {
|
||||
return func(f *HTTPAssetFetcher) { f.openFile = opener }
|
||||
}
|
||||
|
||||
func NewHTTPAssetFetcher(feedURL string, options ...FetcherOption) *HTTPAssetFetcher {
|
||||
fetcher := &HTTPAssetFetcher{
|
||||
allowedHost: domain.HostOf(feedURL),
|
||||
timeout: assetDownloadTimeout,
|
||||
openFile: createAssetFile,
|
||||
}
|
||||
for _, option := range options {
|
||||
option(fetcher)
|
||||
}
|
||||
return fetcher
|
||||
}
|
||||
|
||||
func (f *HTTPAssetFetcher) Fetch(asset domain.Asset, destination string, report domain.ProgressFunc) error {
|
||||
if !f.isAllowed(asset.URL) {
|
||||
return errAssetURLRefused
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), f.timeout)
|
||||
defer cancel()
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, asset.URL, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
response, err := f.client().Do(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("%w: %d", errAssetStatus, response.StatusCode)
|
||||
}
|
||||
limit := f.capFor(asset.Name)
|
||||
if response.ContentLength > limit {
|
||||
return errAssetTooLarge
|
||||
}
|
||||
if err := f.writeBody(response.Body, destination, limit, asset.Size, report); err != nil {
|
||||
_ = os.Remove(destination)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *HTTPAssetFetcher) writeBody(body io.Reader, destination string, limit int64, declaredSize int64, report domain.ProgressFunc) error {
|
||||
file, err := f.openFile(destination)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
counter := &progressWriter{destination: file, total: declaredSize, report: report}
|
||||
written, copyErr := io.Copy(counter, io.LimitReader(body, limit+1))
|
||||
closeErr := file.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
if written > limit {
|
||||
return errAssetTooLarge
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *HTTPAssetFetcher) isAllowed(rawURL string) bool {
|
||||
parsed, err := url.Parse(rawURL)
|
||||
if err != nil || f.allowedHost == "" || parsed.Host != f.allowedHost {
|
||||
return false
|
||||
}
|
||||
return parsed.Scheme == "https" || (f.allowInsecure && parsed.Scheme == "http")
|
||||
}
|
||||
|
||||
func (f *HTTPAssetFetcher) client() *http.Client {
|
||||
return &http.Client{
|
||||
Transport: f.transport,
|
||||
CheckRedirect: func(next *http.Request, via []*http.Request) error {
|
||||
if len(via) >= maxAssetRedirects {
|
||||
return errTooManyRedirects
|
||||
}
|
||||
if !f.isAllowed(next.URL.String()) {
|
||||
return errAssetURLRefused
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (f *HTTPAssetFetcher) capFor(name string) int64 {
|
||||
if f.sizeCap > 0 {
|
||||
return f.sizeCap
|
||||
}
|
||||
if name == domain.ChecksumsAssetName {
|
||||
return maxChecksumsBytes
|
||||
}
|
||||
if strings.HasSuffix(name, signatureSuffix) {
|
||||
return maxSignatureBytes
|
||||
}
|
||||
return maxBinaryBytes
|
||||
}
|
||||
|
||||
type progressWriter struct {
|
||||
destination io.Writer
|
||||
total int64
|
||||
done int64
|
||||
report domain.ProgressFunc
|
||||
}
|
||||
|
||||
func (w *progressWriter) Write(chunk []byte) (int, error) {
|
||||
written, err := w.destination.Write(chunk)
|
||||
w.done += int64(written)
|
||||
w.report(w.done, w.total)
|
||||
return written, err
|
||||
}
|
||||
|
||||
func createAssetFile(path string) (io.WriteCloser, error) {
|
||||
if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, assetFilePermission)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const healthCheckTimeout = 2 * time.Second
|
||||
|
||||
type HTTPHealthChecker struct {
|
||||
url string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
var _ domain.HealthChecker = &HTTPHealthChecker{}
|
||||
|
||||
func NewHTTPHealthChecker(port string) *HTTPHealthChecker {
|
||||
return &HTTPHealthChecker{
|
||||
url: "http://127.0.0.1:" + port + "/healthz",
|
||||
client: &http.Client{Timeout: healthCheckTimeout},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *HTTPHealthChecker) Healthy() bool {
|
||||
response, err := c.client.Get(c.url)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer response.Body.Close()
|
||||
return response.StatusCode == http.StatusOK
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type JSONHelperStatusWriter struct{}
|
||||
|
||||
var _ domain.HelperStatusWriter = &JSONHelperStatusWriter{}
|
||||
|
||||
func NewJSONHelperStatusWriter() *JSONHelperStatusWriter {
|
||||
return &JSONHelperStatusWriter{}
|
||||
}
|
||||
|
||||
func (w *JSONHelperStatusWriter) Write(dataDir string, status domain.HelperStatus) error {
|
||||
return writeJSONAtomically(filepath.Join(dataDir, domain.HelperStatusFileName), status, readableFilePermissions)
|
||||
}
|
||||
|
||||
func (w *JSONHelperStatusWriter) Remove(dataDir string) (bool, error) {
|
||||
return removeFile(filepath.Join(dataDir, domain.HelperStatusFileName))
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type JSONJobStore struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
var _ domain.JobStore = &JSONJobStore{}
|
||||
|
||||
func NewJSONJobStore(path string) *JSONJobStore {
|
||||
store := &JSONJobStore{path: path}
|
||||
store.failInterruptedJob()
|
||||
return store
|
||||
}
|
||||
|
||||
func (s *JSONJobStore) failInterruptedJob() {
|
||||
job, found := s.read()
|
||||
if !found || !job.IsRunning() {
|
||||
return
|
||||
}
|
||||
job.State = domain.StateFailed
|
||||
job.Error = domain.ErrorKindDownload
|
||||
job.DownloadedBytes = 0
|
||||
job.TotalBytes = 0
|
||||
_ = s.write(job)
|
||||
}
|
||||
|
||||
func (s *JSONJobStore) Load() (domain.Job, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
job, found := s.read()
|
||||
if !found {
|
||||
return domain.Job{}, false
|
||||
}
|
||||
if job.State == domain.StateReady && !fileExists(job.StagedBinary) {
|
||||
return domain.Job{}, false
|
||||
}
|
||||
return job, true
|
||||
}
|
||||
|
||||
func (s *JSONJobStore) Save(job domain.Job) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return s.write(job)
|
||||
}
|
||||
|
||||
func (s *JSONJobStore) read() (domain.Job, bool) {
|
||||
content, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.Job{}, false
|
||||
}
|
||||
var job domain.Job
|
||||
if err := json.Unmarshal(content, &job); err != nil || job.State == "" {
|
||||
return domain.Job{}, false
|
||||
}
|
||||
return job, true
|
||||
}
|
||||
|
||||
func (s *JSONJobStore) write(job domain.Job) error {
|
||||
content, err := json.Marshal(job)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(s.path), os.ModePerm); err != nil {
|
||||
return err
|
||||
}
|
||||
temporary := s.path + ".tmp"
|
||||
if err := os.WriteFile(temporary, content, statusFilePermissions); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(temporary, s.path)
|
||||
}
|
||||
|
||||
func fileExists(path string) bool {
|
||||
if path == "" {
|
||||
return false
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
return err == nil && !info.IsDir()
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type JSONRestartRequestStore struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
var _ domain.RestartRequestStore = &JSONRestartRequestStore{}
|
||||
|
||||
func NewJSONRestartRequestStore(path string) *JSONRestartRequestStore {
|
||||
return &JSONRestartRequestStore{path: path}
|
||||
}
|
||||
|
||||
func (s *JSONRestartRequestStore) Write(request domain.RestartRequest) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return writeJSONAtomically(s.path, request, statusFilePermissions)
|
||||
}
|
||||
|
||||
func (s *JSONRestartRequestStore) Read() (domain.RestartRequest, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
info, err := os.Lstat(s.path)
|
||||
if errors.Is(err, fs.ErrNotExist) || (err == nil && info.IsDir()) {
|
||||
return domain.RestartRequest{}, domain.ErrNoRestartRequest
|
||||
}
|
||||
if err != nil {
|
||||
return domain.RestartRequest{}, err
|
||||
}
|
||||
content, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.RestartRequest{}, err
|
||||
}
|
||||
var request domain.RestartRequest
|
||||
return request, json.Unmarshal(content, &request)
|
||||
}
|
||||
|
||||
func (s *JSONRestartRequestStore) Delete() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return removeIfPresent(s.path)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type JSONResultStore struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
var _ domain.ResultStore = &JSONResultStore{}
|
||||
|
||||
func NewJSONResultStore(path string) *JSONResultStore {
|
||||
return &JSONResultStore{path: path}
|
||||
}
|
||||
|
||||
func (s *JSONResultStore) Read() (domain.Result, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
content, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.Result{}, false
|
||||
}
|
||||
return decodeResult(content)
|
||||
}
|
||||
|
||||
func (s *JSONResultStore) Write(result domain.Result) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return writeJSONAtomically(s.path, result, readableFilePermissions)
|
||||
}
|
||||
|
||||
func (s *JSONResultStore) Delete() error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return removeIfPresent(s.path)
|
||||
}
|
||||
|
||||
func decodeResult(content []byte) (domain.Result, bool) {
|
||||
var result domain.Result
|
||||
if err := json.Unmarshal(content, &result); err != nil || !result.IsKnown() {
|
||||
return domain.Result{}, false
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type JSONRunningInfoStore struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
var _ domain.RunningInfoStore = &JSONRunningInfoStore{}
|
||||
|
||||
func NewJSONRunningInfoStore(path string) *JSONRunningInfoStore {
|
||||
return &JSONRunningInfoStore{path: path}
|
||||
}
|
||||
|
||||
func (s *JSONRunningInfoStore) Write(info domain.RunningInfo) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return writeJSONAtomically(s.path, info, readableFilePermissions)
|
||||
}
|
||||
|
||||
func (s *JSONRunningInfoStore) Read() (domain.RunningInfo, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
linkInfo, err := os.Lstat(s.path)
|
||||
if err != nil || !linkInfo.Mode().IsRegular() {
|
||||
return domain.RunningInfo{}, false
|
||||
}
|
||||
content, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.RunningInfo{}, false
|
||||
}
|
||||
var info domain.RunningInfo
|
||||
if err := json.Unmarshal(content, &info); err != nil || info.Version == "" || info.Pid == 0 {
|
||||
return domain.RunningInfo{}, false
|
||||
}
|
||||
return info, true
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
)
|
||||
|
||||
const statusFilePermissions = 0o600
|
||||
|
||||
type JSONStatusStore struct {
|
||||
path string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
var _ domain.StatusStore = &JSONStatusStore{}
|
||||
|
||||
func NewJSONStatusStore(path string) *JSONStatusStore {
|
||||
return &JSONStatusStore{path: path}
|
||||
}
|
||||
|
||||
func (s *JSONStatusStore) Load() (domain.CheckResult, bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
content, err := os.ReadFile(s.path)
|
||||
if err != nil {
|
||||
return domain.CheckResult{}, false
|
||||
}
|
||||
var result domain.CheckResult
|
||||
if err := json.Unmarshal(content, &result); err != nil || result.CheckedAt.IsZero() {
|
||||
return domain.CheckResult{}, false
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
|
||||
func (s *JSONStatusStore) Save(result domain.CheckResult) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
content, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(s.path), os.ModePerm); err != nil {
|
||||
return err
|
||||
}
|
||||
temporary := s.path + ".tmp"
|
||||
if err := os.WriteFile(temporary, content, statusFilePermissions); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(temporary, s.path)
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//go:build linux
|
||||
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
const (
|
||||
privateTempDirPrefix = "renewcms-update-"
|
||||
readNoFollowFlags = os.O_RDONLY | syscall.O_NOFOLLOW | syscall.O_NONBLOCK
|
||||
createNoFollowFlags = os.O_WRONLY | os.O_CREATE | os.O_EXCL | syscall.O_NOFOLLOW
|
||||
directoryFlags = os.O_RDONLY | syscall.O_NOFOLLOW | syscall.O_DIRECTORY
|
||||
)
|
||||
|
||||
var errNotRegularFile = errors.New("not a regular file")
|
||||
|
||||
type NoFollowFilesystem struct{}
|
||||
|
||||
var _ domain.HelperFilesystem = &NoFollowFilesystem{}
|
||||
|
||||
func NewNoFollowFilesystem() *NoFollowFilesystem {
|
||||
return &NoFollowFilesystem{}
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Lstat(path string) (domain.FileInfo, error) {
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return domain.FileInfo{}, err
|
||||
}
|
||||
mode := info.Mode()
|
||||
return domain.FileInfo{
|
||||
IsSymlink: mode&fs.ModeSymlink != 0,
|
||||
IsDir: mode.IsDir(),
|
||||
IsRegular: mode.IsRegular(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) ReadFile(path string) ([]byte, error) {
|
||||
file, err := openRegularNoFollow(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
return io.ReadAll(file)
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) CreateExclusive(path string, content []byte, mode uint32) error {
|
||||
file, err := os.OpenFile(path, createNoFollowFlags, fs.FileMode(mode))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := file.Write(content); err != nil {
|
||||
file.Close()
|
||||
return err
|
||||
}
|
||||
return finishWrite(file, mode)
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Copy(source string, destination string, mode uint32) error {
|
||||
input, err := openRegularNoFollow(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer input.Close()
|
||||
output, err := os.OpenFile(destination, createNoFollowFlags, fs.FileMode(mode))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := io.Copy(output, input); err != nil {
|
||||
output.Close()
|
||||
return err
|
||||
}
|
||||
return finishWrite(output, mode)
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Rename(oldPath string, newPath string) error {
|
||||
return os.Rename(oldPath, newPath)
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Remove(path string) error {
|
||||
return os.Remove(path)
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) RemoveAll(path string) error {
|
||||
info, err := os.Lstat(path)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return os.Remove(path)
|
||||
}
|
||||
names, err := readDirectoryNames(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, name := range names {
|
||||
if err := f.RemoveAll(filepath.Join(path, name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return os.Remove(path)
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Chmod(path string, mode uint32) error {
|
||||
file, err := os.OpenFile(path, readNoFollowFlags, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
return file.Chmod(fs.FileMode(mode))
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) MakePrivateTempDir() (string, error) {
|
||||
return os.MkdirTemp("", privateTempDirPrefix)
|
||||
}
|
||||
|
||||
func openRegularNoFollow(path string) (*os.File, error) {
|
||||
file, err := os.OpenFile(path, readNoFollowFlags, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
file.Close()
|
||||
return nil, err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
file.Close()
|
||||
return nil, errNotRegularFile
|
||||
}
|
||||
return file, nil
|
||||
}
|
||||
|
||||
func finishWrite(file *os.File, mode uint32) error {
|
||||
if err := file.Chmod(fs.FileMode(mode)); err != nil {
|
||||
file.Close()
|
||||
return err
|
||||
}
|
||||
if err := file.Sync(); err != nil {
|
||||
file.Close()
|
||||
return err
|
||||
}
|
||||
return file.Close()
|
||||
}
|
||||
|
||||
func readDirectoryNames(path string) ([]string, error) {
|
||||
directory, err := os.OpenFile(path, directoryFlags, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer directory.Close()
|
||||
return directory.Readdirnames(-1)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
//go:build !linux
|
||||
|
||||
package update
|
||||
|
||||
import domain "RenewCMS/internal/domain/update"
|
||||
|
||||
type NoFollowFilesystem struct{}
|
||||
|
||||
var _ domain.HelperFilesystem = &NoFollowFilesystem{}
|
||||
|
||||
func NewNoFollowFilesystem() *NoFollowFilesystem {
|
||||
return &NoFollowFilesystem{}
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Lstat(string) (domain.FileInfo, error) {
|
||||
return domain.FileInfo{}, domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) ReadFile(string) ([]byte, error) {
|
||||
return nil, domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) CreateExclusive(string, []byte, uint32) error {
|
||||
return domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Copy(string, string, uint32) error {
|
||||
return domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Rename(string, string) error {
|
||||
return domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Remove(string) error {
|
||||
return domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) RemoveAll(string) error {
|
||||
return domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) Chmod(string, uint32) error {
|
||||
return domain.ErrHelperUnsupported
|
||||
}
|
||||
|
||||
func (f *NoFollowFilesystem) MakePrivateTempDir() (string, error) {
|
||||
return "", domain.ErrHelperUnsupported
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const (
|
||||
stagedDirectoryPermissions = 0o755
|
||||
stagedBinaryPermissions = 0o755
|
||||
)
|
||||
|
||||
type OSStagingArea struct {
|
||||
root string
|
||||
}
|
||||
|
||||
var _ update.StagingArea = &OSStagingArea{}
|
||||
|
||||
func NewOSStagingArea(root string) *OSStagingArea {
|
||||
return &OSStagingArea{root: root}
|
||||
}
|
||||
|
||||
func (a *OSStagingArea) Prepare(tag string) error {
|
||||
directory := filepath.Join(a.root, tag)
|
||||
if err := os.RemoveAll(directory); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.MkdirAll(directory, stagedDirectoryPermissions)
|
||||
}
|
||||
|
||||
func (a *OSStagingArea) PathFor(tag string, name string) string {
|
||||
return filepath.Join(a.root, tag, name)
|
||||
}
|
||||
|
||||
func (a *OSStagingArea) Size(path string) (int64, error) {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return info.Size(), nil
|
||||
}
|
||||
|
||||
func (a *OSStagingArea) ReadChecksums(path string) (string, error) {
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(content), nil
|
||||
}
|
||||
|
||||
func (a *OSStagingArea) MakeExecutable(path string) error {
|
||||
return os.Chmod(path, stagedBinaryPermissions)
|
||||
}
|
||||
|
||||
func (a *OSStagingArea) Remove(tag string) error {
|
||||
return os.RemoveAll(filepath.Join(a.root, tag))
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
_ "embed"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed release.pub
|
||||
var embeddedPublicKey string
|
||||
|
||||
var (
|
||||
ErrPublicKeyFormat = errors.New("the public key is not a base64 encoded 32 byte ed25519 key")
|
||||
ErrPlaceholderPublicKey = errors.New("the placeholder public key has not been replaced: run task release:keygen and commit the real key as internal/infrastructure/update/release.pub")
|
||||
)
|
||||
|
||||
func EmbeddedPublicKey() (ed25519.PublicKey, error) {
|
||||
return ParsePublicKey(embeddedPublicKey)
|
||||
}
|
||||
|
||||
func ParsePublicKey(text string) (ed25519.PublicKey, error) {
|
||||
decoded, err := base64.StdEncoding.DecodeString(strings.TrimSpace(text))
|
||||
if err != nil || len(decoded) != ed25519.PublicKeySize {
|
||||
return nil, ErrPublicKeyFormat
|
||||
}
|
||||
return ed25519.PublicKey(decoded), nil
|
||||
}
|
||||
|
||||
func IsPlaceholderPublicKey(key ed25519.PublicKey) bool {
|
||||
return bytes.Equal(key, make([]byte, ed25519.PublicKeySize))
|
||||
}
|
||||
|
||||
func EncodePublicKey(key ed25519.PublicKey) string {
|
||||
return base64.StdEncoding.EncodeToString(key)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
cuIg/xm6NmUEi3WtUTO3Rrjo8QoUyKzU315g0HtiVcI=
|
||||
@@ -0,0 +1,292 @@
|
||||
package releasesign
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/infrastructure/update"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
exitOK = 0
|
||||
exitFailure = 1
|
||||
exitUsage = 2
|
||||
|
||||
signingKeyEnvVar = "RELEASE_SIGNING_KEY"
|
||||
signatureSuffix = ".sig"
|
||||
privateKeyFileMode = 0o600
|
||||
publicFileMode = 0o644
|
||||
repositoryMarker = ".git"
|
||||
checksumsFileName = "checksums.txt"
|
||||
usageText = "usage: releasesign keygen <private-key-path> [--pub-out <path>] | sign <file> [--key <path>] [--pub <path>] | verify <file> [--pub <path>] | checksums <dir> [--match <glob>]"
|
||||
publicKeyCommitHint = "commit the public key as internal/infrastructure/update/release.pub"
|
||||
)
|
||||
|
||||
var (
|
||||
errInsideRepository = errors.New("the private key path is inside the repository work tree, choose a path outside it")
|
||||
errKeyMismatch = errors.New("the private key does not match the public key in use")
|
||||
errPrivateKeyFormat = errors.New("the private key file is not a base64 encoded ed25519 private key")
|
||||
errSignatureFormat = errors.New("the signature file is not a base64 encoded ed25519 signature")
|
||||
errBadSignature = errors.New("the signature does not match the file: it was changed or signed with another key")
|
||||
errNoKeyPath = errors.New("no private key given: pass --key or set RELEASE_SIGNING_KEY")
|
||||
)
|
||||
|
||||
func Run(args []string, stdout, stderr io.Writer) int {
|
||||
if len(args) == 0 {
|
||||
fmt.Fprintln(stderr, usageText)
|
||||
return exitUsage
|
||||
}
|
||||
commands := map[string]func([]string, io.Writer) error{
|
||||
"keygen": keygen,
|
||||
"sign": sign,
|
||||
"verify": verify,
|
||||
"checksums": checksums,
|
||||
}
|
||||
command, known := commands[args[0]]
|
||||
if !known {
|
||||
fmt.Fprintln(stderr, usageText)
|
||||
return exitUsage
|
||||
}
|
||||
if err := command(args[1:], stdout); err != nil {
|
||||
fmt.Fprintln(stderr, "releasesign:", err)
|
||||
return exitFailure
|
||||
}
|
||||
return exitOK
|
||||
}
|
||||
|
||||
func parseArguments(name string, args []string, define func(*flag.FlagSet)) (string, error) {
|
||||
set := flag.NewFlagSet(name, flag.ContinueOnError)
|
||||
set.SetOutput(io.Discard)
|
||||
define(set)
|
||||
positional, flags := splitArguments(args)
|
||||
if err := set.Parse(flags); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(positional) != 1 {
|
||||
return "", errors.New(usageText)
|
||||
}
|
||||
return positional[0], nil
|
||||
}
|
||||
|
||||
func splitArguments(args []string) ([]string, []string) {
|
||||
var positional, flags []string
|
||||
for i := 0; i < len(args); i++ {
|
||||
if strings.HasPrefix(args[i], "--") {
|
||||
flags = append(flags, args[i])
|
||||
if !strings.Contains(args[i], "=") && i+1 < len(args) {
|
||||
i++
|
||||
flags = append(flags, args[i])
|
||||
}
|
||||
continue
|
||||
}
|
||||
positional = append(positional, args[i])
|
||||
}
|
||||
return positional, flags
|
||||
}
|
||||
|
||||
func keygen(args []string, stdout io.Writer) error {
|
||||
var pubOut string
|
||||
keyPath, err := parseArguments("keygen", args, func(set *flag.FlagSet) { set.StringVar(&pubOut, "pub-out", "", "") })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := refuseInsideRepository(keyPath); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := os.Stat(keyPath); err == nil {
|
||||
return fmt.Errorf("%s already exists, it is not overwritten", keyPath)
|
||||
}
|
||||
publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
encodedPrivate := base64.StdEncoding.EncodeToString(privateKey) + "\n"
|
||||
if err := os.WriteFile(keyPath, []byte(encodedPrivate), privateKeyFileMode); err != nil {
|
||||
return err
|
||||
}
|
||||
encodedPublic := update.EncodePublicKey(publicKey)
|
||||
if pubOut != "" {
|
||||
if err := os.WriteFile(pubOut, []byte(encodedPublic+"\n"), publicFileMode); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(stdout, "private key written to %s: keep it outside the repository and never share it\n", keyPath)
|
||||
fmt.Fprintf(stdout, "public key: %s\n%s\n", encodedPublic, publicKeyCommitHint)
|
||||
return nil
|
||||
}
|
||||
|
||||
func refuseInsideRepository(path string) error {
|
||||
absolute, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for directory := filepath.Dir(absolute); ; directory = filepath.Dir(directory) {
|
||||
if _, err := os.Stat(filepath.Join(directory, repositoryMarker)); err == nil {
|
||||
return fmt.Errorf("%w (%s)", errInsideRepository, directory)
|
||||
}
|
||||
if directory == filepath.Dir(directory) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func sign(args []string, stdout io.Writer) error {
|
||||
var keyPath, pubPath string
|
||||
file, err := parseArguments("sign", args, func(set *flag.FlagSet) {
|
||||
set.StringVar(&keyPath, "key", "", "")
|
||||
set.StringVar(&pubPath, "pub", "", "")
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
publicKey, err := loadPublicKey(pubPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
privateKey, err := loadPrivateKey(keyPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !publicKeyOf(privateKey).Equal(publicKey) {
|
||||
return errKeyMismatch
|
||||
}
|
||||
content, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
signature := base64.StdEncoding.EncodeToString(ed25519.Sign(privateKey, content))
|
||||
if err := os.WriteFile(file+signatureSuffix, []byte(signature+"\n"), publicFileMode); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintf(stdout, "signed %s into %s\n", file, file+signatureSuffix)
|
||||
return nil
|
||||
}
|
||||
|
||||
func verify(args []string, stdout io.Writer) error {
|
||||
var pubPath string
|
||||
file, err := parseArguments("verify", args, func(set *flag.FlagSet) { set.StringVar(&pubPath, "pub", "", "") })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
publicKey, err := loadPublicKey(pubPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
content, err := os.ReadFile(file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rawSignature, err := os.ReadFile(file + signatureSuffix)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
signature, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(rawSignature)))
|
||||
if err != nil || len(signature) != ed25519.SignatureSize {
|
||||
return errSignatureFormat
|
||||
}
|
||||
if !ed25519.Verify(publicKey, content, signature) {
|
||||
return errBadSignature
|
||||
}
|
||||
fmt.Fprintf(stdout, "%s is signed by the release key\n", file)
|
||||
return nil
|
||||
}
|
||||
|
||||
func checksums(args []string, stdout io.Writer) error {
|
||||
match := "*"
|
||||
dir, err := parseArguments("checksums", args, func(set *flag.FlagSet) { set.StringVar(&match, "match", "*", "") })
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
paths, err := filepath.Glob(filepath.Join(dir, match))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sort.Strings(paths)
|
||||
var lines strings.Builder
|
||||
for _, path := range paths {
|
||||
line, err := checksumLine(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
lines.WriteString(line)
|
||||
}
|
||||
if lines.Len() == 0 {
|
||||
return fmt.Errorf("no file in %s matches %s", dir, match)
|
||||
}
|
||||
target := filepath.Join(dir, checksumsFileName)
|
||||
if err := os.WriteFile(target, []byte(lines.String()), publicFileMode); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Fprintln(stdout, "wrote", target)
|
||||
return nil
|
||||
}
|
||||
|
||||
func checksumLine(path string) (string, error) {
|
||||
name := filepath.Base(path)
|
||||
if name == checksumsFileName || strings.HasSuffix(name, signatureSuffix) {
|
||||
return "", nil
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || info.IsDir() {
|
||||
return "", err
|
||||
}
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := sha256.Sum256(content)
|
||||
return fmt.Sprintf("%s %s\n", hex.EncodeToString(sum[:]), name), nil
|
||||
}
|
||||
|
||||
func loadPublicKey(pubPath string) (ed25519.PublicKey, error) {
|
||||
var key ed25519.PublicKey
|
||||
var err error
|
||||
if pubPath == "" {
|
||||
key, err = update.EmbeddedPublicKey()
|
||||
} else {
|
||||
var content []byte
|
||||
content, err = os.ReadFile(pubPath)
|
||||
if err == nil {
|
||||
key, err = update.ParsePublicKey(string(content))
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if update.IsPlaceholderPublicKey(key) {
|
||||
return nil, update.ErrPlaceholderPublicKey
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
func loadPrivateKey(keyPath string) (ed25519.PrivateKey, error) {
|
||||
if keyPath == "" {
|
||||
keyPath = os.Getenv(signingKeyEnvVar)
|
||||
}
|
||||
if keyPath == "" {
|
||||
return nil, errNoKeyPath
|
||||
}
|
||||
content, err := os.ReadFile(keyPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(content)))
|
||||
if err != nil || len(decoded) != ed25519.PrivateKeySize {
|
||||
return nil, errPrivateKeyFormat
|
||||
}
|
||||
return ed25519.PrivateKey(decoded), nil
|
||||
}
|
||||
|
||||
func publicKeyOf(privateKey ed25519.PrivateKey) ed25519.PublicKey {
|
||||
return privateKey.Public().(ed25519.PublicKey)
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var errBackupExists = errors.New("a backup with this name already exists")
|
||||
|
||||
const (
|
||||
backupsToKeep = 3
|
||||
backupFileExtension = ".db"
|
||||
backupFilePrefix = "renewcms-"
|
||||
backupTimeLayout = "20060102T150405.000000000Z"
|
||||
)
|
||||
|
||||
type SQLiteDatabaseBackup struct {
|
||||
db *gorm.DB
|
||||
directory string
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
var _ domain.DatabaseBackup = &SQLiteDatabaseBackup{}
|
||||
|
||||
func NewSQLiteDatabaseBackup(db *gorm.DB, directory string, now func() time.Time) *SQLiteDatabaseBackup {
|
||||
return &SQLiteDatabaseBackup{db: db, directory: directory, now: now}
|
||||
}
|
||||
|
||||
func (b *SQLiteDatabaseBackup) Backup() (string, error) {
|
||||
if err := os.MkdirAll(b.directory, os.ModePerm); err != nil {
|
||||
return "", err
|
||||
}
|
||||
target := filepath.Join(b.directory, backupFilePrefix+b.now().UTC().Format(backupTimeLayout)+backupFileExtension)
|
||||
if _, err := os.Stat(target); err == nil {
|
||||
return "", errBackupExists
|
||||
}
|
||||
if err := b.db.Exec("VACUUM INTO ?", target).Error; err != nil {
|
||||
_ = os.Remove(target)
|
||||
return "", err
|
||||
}
|
||||
if err := b.prune(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
type backupFile struct {
|
||||
path string
|
||||
modified time.Time
|
||||
}
|
||||
|
||||
func (b *SQLiteDatabaseBackup) prune() error {
|
||||
entries, err := os.ReadDir(b.directory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
files := make([]backupFile, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), backupFileExtension) {
|
||||
continue
|
||||
}
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
files = append(files, backupFile{path: filepath.Join(b.directory, entry.Name()), modified: info.ModTime()})
|
||||
}
|
||||
sort.Slice(files, func(i, j int) bool {
|
||||
if files[i].modified.Equal(files[j].modified) {
|
||||
return files[i].path > files[j].path
|
||||
}
|
||||
return files[i].modified.After(files[j].modified)
|
||||
})
|
||||
for _, stale := range files[min(backupsToKeep, len(files)):] {
|
||||
if err := os.Remove(stale.path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"time"
|
||||
)
|
||||
|
||||
type SystemClock struct{}
|
||||
|
||||
var _ domain.Clock = &SystemClock{}
|
||||
|
||||
func NewSystemClock() *SystemClock {
|
||||
return &SystemClock{}
|
||||
}
|
||||
|
||||
func (c *SystemClock) Now() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
func (c *SystemClock) Sleep(duration time.Duration) {
|
||||
time.Sleep(duration)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"os"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
const systemdRuntimeDirectory = "/run/systemd/system"
|
||||
|
||||
type SystemMachineProbe struct{}
|
||||
|
||||
var _ domain.MachineProbe = &SystemMachineProbe{}
|
||||
|
||||
func NewSystemMachineProbe() *SystemMachineProbe {
|
||||
return &SystemMachineProbe{}
|
||||
}
|
||||
|
||||
func (p *SystemMachineProbe) OS() string {
|
||||
return runtime.GOOS
|
||||
}
|
||||
|
||||
func (p *SystemMachineProbe) SystemdRunning() bool {
|
||||
info, err := os.Stat(systemdRuntimeDirectory)
|
||||
return err == nil && info.IsDir()
|
||||
}
|
||||
|
||||
func (p *SystemMachineProbe) IsRoot() bool {
|
||||
return os.Geteuid() == 0
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const systemctlCommand = "systemctl"
|
||||
|
||||
type SystemctlControl struct {
|
||||
service string
|
||||
}
|
||||
|
||||
var (
|
||||
_ domain.ServiceControl = &SystemctlControl{}
|
||||
_ domain.UnitManager = &SystemctlControl{}
|
||||
)
|
||||
|
||||
func NewSystemctlControl(service string) *SystemctlControl {
|
||||
return &SystemctlControl{service: service}
|
||||
}
|
||||
|
||||
func (c *SystemctlControl) Restart() error {
|
||||
return runSystemctl("restart", c.service)
|
||||
}
|
||||
|
||||
func (c *SystemctlControl) Status() (bool, error) {
|
||||
err := exec.Command(systemctlCommand, "is-active", "--quiet", c.service).Run()
|
||||
var exitErr *exec.ExitError
|
||||
if errors.As(err, &exitErr) {
|
||||
return false, nil
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
func (c *SystemctlControl) DaemonReload() error {
|
||||
return runSystemctl("daemon-reload")
|
||||
}
|
||||
|
||||
func (c *SystemctlControl) EnableNow(unit string) error {
|
||||
return runSystemctl("enable", "--now", unit)
|
||||
}
|
||||
|
||||
func (c *SystemctlControl) DisableNow(unit string) error {
|
||||
return runSystemctl("disable", "--now", unit)
|
||||
}
|
||||
|
||||
func runSystemctl(arguments ...string) error {
|
||||
output, err := exec.Command(systemctlCommand, arguments...).CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("systemctl %s: %w: %s", strings.Join(arguments, " "), err, strings.TrimSpace(string(output)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
domain "RenewCMS/internal/domain/update"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
systemUnitDirectory = "/etc/systemd/system"
|
||||
unitFilePermissions = 0o644
|
||||
unitFileSuffix = ".service"
|
||||
)
|
||||
|
||||
type SystemdUnits struct {
|
||||
directory string
|
||||
}
|
||||
|
||||
var (
|
||||
_ domain.UnitWriter = &SystemdUnits{}
|
||||
_ domain.ServiceLocator = &SystemdUnits{}
|
||||
)
|
||||
|
||||
func NewSystemdUnits() *SystemdUnits {
|
||||
return NewSystemdUnitsIn(systemUnitDirectory)
|
||||
}
|
||||
|
||||
func NewSystemdUnitsIn(directory string) *SystemdUnits {
|
||||
return &SystemdUnits{directory: directory}
|
||||
}
|
||||
|
||||
func (u *SystemdUnits) Write(name string, content string) error {
|
||||
return os.WriteFile(filepath.Join(u.directory, name), []byte(content), unitFilePermissions)
|
||||
}
|
||||
|
||||
func (u *SystemdUnits) Remove(name string) (bool, error) {
|
||||
return removeFile(filepath.Join(u.directory, name))
|
||||
}
|
||||
|
||||
func (u *SystemdUnits) Locate(name string) (domain.ServiceDescription, bool) {
|
||||
content, err := os.ReadFile(filepath.Join(u.directory, name+unitFileSuffix))
|
||||
if err != nil {
|
||||
return domain.ServiceDescription{}, false
|
||||
}
|
||||
description := ParseServiceUnit(string(content))
|
||||
description.Name = name
|
||||
return description, true
|
||||
}
|
||||
|
||||
func (u *SystemdUnits) PortFromEnvironmentFile(path string) (string, bool) {
|
||||
if path == "" {
|
||||
return "", false
|
||||
}
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
return portFromEnvironment(string(content))
|
||||
}
|
||||
|
||||
func ParseServiceUnit(content string) domain.ServiceDescription {
|
||||
var description domain.ServiceDescription
|
||||
for _, line := range strings.Split(content, "\n") {
|
||||
key, value, found := strings.Cut(strings.TrimSpace(line), "=")
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
switch key {
|
||||
case "ExecStart":
|
||||
description.BinaryPath = firstUnitPath(value, "@-:+!")
|
||||
case "EnvironmentFile":
|
||||
description.EnvironmentFile = firstUnitPath(value, "-")
|
||||
case "ReadWritePaths":
|
||||
if description.DataDir == "" {
|
||||
description.DataDir = firstUnitPath(value, "-+!")
|
||||
}
|
||||
}
|
||||
}
|
||||
return description
|
||||
}
|
||||
|
||||
func firstUnitPath(value string, prefixes string) string {
|
||||
fields := strings.Fields(value)
|
||||
if len(fields) == 0 {
|
||||
return ""
|
||||
}
|
||||
return strings.Trim(strings.TrimLeft(fields[0], prefixes), `"`)
|
||||
}
|
||||
|
||||
func portFromEnvironment(content string) (string, bool) {
|
||||
for _, line := range strings.Split(content, "\n") {
|
||||
key, value, found := strings.Cut(strings.TrimSpace(line), "=")
|
||||
if !found || strings.TrimSpace(key) != "PORT" {
|
||||
continue
|
||||
}
|
||||
port := strings.Trim(strings.TrimSpace(value), `"'`)
|
||||
if _, err := strconv.Atoi(port); err == nil {
|
||||
return port, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ApplyRestartRequestUseCase struct {
|
||||
requests update.RestartRequestStore
|
||||
results update.ResultStore
|
||||
running update.RunningInfoStore
|
||||
files update.HelperFilesystem
|
||||
service update.ServiceControl
|
||||
health update.HealthChecker
|
||||
verifier update.SignatureVerifier
|
||||
clock update.Clock
|
||||
logger update.Logger
|
||||
layout update.HelperLayout
|
||||
platform update.Platform
|
||||
}
|
||||
|
||||
type ApplyRestartRequestDependencies struct {
|
||||
Requests update.RestartRequestStore
|
||||
Results update.ResultStore
|
||||
Running update.RunningInfoStore
|
||||
Files update.HelperFilesystem
|
||||
Service update.ServiceControl
|
||||
Health update.HealthChecker
|
||||
Verifier update.SignatureVerifier
|
||||
Clock update.Clock
|
||||
Logger update.Logger
|
||||
Layout update.HelperLayout
|
||||
Platform update.Platform
|
||||
}
|
||||
|
||||
func NewApplyRestartRequestUseCase(dependencies ApplyRestartRequestDependencies) *ApplyRestartRequestUseCase {
|
||||
return &ApplyRestartRequestUseCase{
|
||||
requests: dependencies.Requests,
|
||||
results: dependencies.Results,
|
||||
running: dependencies.Running,
|
||||
files: dependencies.Files,
|
||||
service: dependencies.Service,
|
||||
health: dependencies.Health,
|
||||
verifier: dependencies.Verifier,
|
||||
clock: dependencies.Clock,
|
||||
logger: dependencies.Logger,
|
||||
layout: dependencies.Layout,
|
||||
platform: dependencies.Platform,
|
||||
}
|
||||
}
|
||||
|
||||
type helperRun struct {
|
||||
apply *ApplyRestartRequestUseCase
|
||||
result update.Result
|
||||
tempDir string
|
||||
stagedTag string
|
||||
}
|
||||
|
||||
type verifiedCopy struct {
|
||||
binaryPath string
|
||||
checksum string
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) Apply() (err error) {
|
||||
request, readErr := a.requests.Read()
|
||||
if errors.Is(readErr, update.ErrNoRestartRequest) {
|
||||
a.logger.Printf("no restart request found, nothing to do")
|
||||
return nil
|
||||
}
|
||||
run := &helperRun{apply: a, result: update.Result{
|
||||
Outcome: update.OutcomeRunning,
|
||||
Kind: request.Kind,
|
||||
Tag: request.Tag,
|
||||
StartedAt: a.clock.Now().UTC(),
|
||||
}}
|
||||
defer run.recoverPanic(&err)
|
||||
|
||||
deleteErr := a.requests.Delete()
|
||||
symlinkErr := a.symlinkedDataFile()
|
||||
if info, found := a.running.Read(); found {
|
||||
run.result.FromVersion = info.Version
|
||||
}
|
||||
run.record()
|
||||
|
||||
for _, refusal := range []error{readErr, deleteErr, symlinkErr} {
|
||||
if refusal != nil {
|
||||
return run.fail(refusal)
|
||||
}
|
||||
}
|
||||
return run.dispatch()
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) symlinkedDataFile() error {
|
||||
for _, candidate := range []string{a.layout.ResultPath(), a.layout.ResultTempPath()} {
|
||||
if info, err := a.files.Lstat(candidate); err == nil && info.IsSymlink {
|
||||
return update.SymlinkError{Path: candidate}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *helperRun) dispatch() error {
|
||||
switch r.result.Kind {
|
||||
case update.RestartKindRestart:
|
||||
return r.plainRestart()
|
||||
case update.RestartKindUpdate:
|
||||
return r.installUpdate()
|
||||
}
|
||||
return r.fail(fmt.Errorf("unknown restart kind %q", r.result.Kind))
|
||||
}
|
||||
|
||||
func (r *helperRun) plainRestart() error {
|
||||
if !r.apply.restartAndAwait("") {
|
||||
return r.failLoudly(errors.New("the site did not come back after the restart"))
|
||||
}
|
||||
return r.finish(update.OutcomeSucceeded)
|
||||
}
|
||||
|
||||
func (r *helperRun) installUpdate() error {
|
||||
a := r.apply
|
||||
tag := r.result.Tag
|
||||
if r.result.FromVersion == "" {
|
||||
return r.fail(errors.New("the running version could not be read from update-running.json"))
|
||||
}
|
||||
if err := update.ValidateRestartTag(tag, r.result.FromVersion); err != nil {
|
||||
return r.fail(fmt.Errorf("tag %q: %w", tag, err))
|
||||
}
|
||||
r.stagedTag = tag
|
||||
|
||||
assetName := update.AssetName(tag, a.platform)
|
||||
if err := a.requireStagedFiles(tag, assetName); err != nil {
|
||||
return r.fail(err)
|
||||
}
|
||||
verified, err := r.copyAndVerify(tag, assetName)
|
||||
if err != nil {
|
||||
return r.fail(err)
|
||||
}
|
||||
if err := a.swapBinary(verified); err != nil {
|
||||
return r.fail(err)
|
||||
}
|
||||
if a.restartAndAwait(tag) {
|
||||
return r.finish(update.OutcomeSucceeded)
|
||||
}
|
||||
return r.rollBack()
|
||||
}
|
||||
|
||||
func (r *helperRun) copyAndVerify(tag string, assetName string) (verifiedCopy, error) {
|
||||
a := r.apply
|
||||
tempDir, err := a.files.MakePrivateTempDir()
|
||||
if err != nil {
|
||||
return verifiedCopy{}, err
|
||||
}
|
||||
r.tempDir = tempDir
|
||||
stagedDir := a.layout.StagedDir(tag)
|
||||
for _, name := range []string{assetName, update.ChecksumsAssetName, update.SignatureAssetName} {
|
||||
original := path.Join(stagedDir, name)
|
||||
if err := a.files.Copy(original, path.Join(tempDir, name), update.PrivateFileMode); err != nil {
|
||||
return verifiedCopy{}, fmt.Errorf("copying %s: %w", original, err)
|
||||
}
|
||||
}
|
||||
return a.verifyCopy(tempDir, assetName)
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) verifyCopy(tempDir string, assetName string) (verifiedCopy, error) {
|
||||
checksumsPath := path.Join(tempDir, update.ChecksumsAssetName)
|
||||
if err := a.verifier.Verify(checksumsPath, path.Join(tempDir, update.SignatureAssetName)); err != nil {
|
||||
return verifiedCopy{}, fmt.Errorf("signature check: %w", err)
|
||||
}
|
||||
checksums, err := a.files.ReadFile(checksumsPath)
|
||||
if err != nil {
|
||||
return verifiedCopy{}, err
|
||||
}
|
||||
expected, found := update.ChecksumFor(string(checksums), assetName)
|
||||
if !found {
|
||||
return verifiedCopy{}, fmt.Errorf("checksums.txt has no line for %q", assetName)
|
||||
}
|
||||
binaryPath := path.Join(tempDir, assetName)
|
||||
content, err := a.files.ReadFile(binaryPath)
|
||||
if err != nil {
|
||||
return verifiedCopy{}, err
|
||||
}
|
||||
if update.SHA256Hex(content) != expected {
|
||||
return verifiedCopy{}, fmt.Errorf("sha-256 mismatch for the staged %q", assetName)
|
||||
}
|
||||
return verifiedCopy{binaryPath: binaryPath, checksum: expected}, nil
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) requireStagedFiles(tag string, assetName string) error {
|
||||
for _, directory := range []string{a.layout.UpdatesDir(), a.layout.StagedDir(tag)} {
|
||||
if err := a.requireDirectory(directory); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, name := range []string{assetName, update.ChecksumsAssetName, update.SignatureAssetName} {
|
||||
if err := a.requireRegularFile(path.Join(a.layout.StagedDir(tag), name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) requireDirectory(target string) error {
|
||||
return a.requireEntry(target, "a directory", func(info update.FileInfo) bool { return info.IsDir })
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) requireRegularFile(target string) error {
|
||||
return a.requireEntry(target, "a regular file", func(info update.FileInfo) bool { return info.IsRegular })
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) requireEntry(target string, description string, matches func(update.FileInfo) bool) error {
|
||||
info, err := a.files.Lstat(target)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: %w", target, err)
|
||||
}
|
||||
if info.IsSymlink {
|
||||
return update.SymlinkError{Path: target}
|
||||
}
|
||||
if !matches(info) {
|
||||
return fmt.Errorf("%s is not %s", target, description)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) swapBinary(verified verifiedCopy) error {
|
||||
binary := a.layout.BinaryPath
|
||||
if err := a.replaceViaTemp(binary, a.layout.PreviousPath(), binary+update.PreviousTempSuffix); err != nil {
|
||||
return fmt.Errorf("keeping the previous binary: %w", err)
|
||||
}
|
||||
installTemp := binary + update.InstallTempSuffix
|
||||
a.removeQuietly(installTemp)
|
||||
if err := a.files.Copy(verified.binaryPath, installTemp, update.ExecutableMode); err != nil {
|
||||
a.removeQuietly(installTemp)
|
||||
return fmt.Errorf("writing the new binary: %w", err)
|
||||
}
|
||||
if err := a.installIfUnchanged(installTemp, verified.checksum); err != nil {
|
||||
a.removeQuietly(installTemp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) installIfUnchanged(installTemp string, checksum string) error {
|
||||
content, err := a.files.ReadFile(installTemp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if update.SHA256Hex(content) != checksum {
|
||||
return fmt.Errorf("%s changed after it was verified", installTemp)
|
||||
}
|
||||
if err := a.files.Chmod(installTemp, update.ExecutableMode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.files.Rename(installTemp, a.layout.BinaryPath); err != nil {
|
||||
return fmt.Errorf("installing the new binary: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) replaceViaTemp(source string, destination string, temporary string) error {
|
||||
a.removeQuietly(temporary)
|
||||
if err := a.files.Copy(source, temporary, update.ExecutableMode); err != nil {
|
||||
a.removeQuietly(temporary)
|
||||
return err
|
||||
}
|
||||
if err := a.files.Rename(temporary, destination); err != nil {
|
||||
a.removeQuietly(temporary)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *helperRun) rollBack() error {
|
||||
a := r.apply
|
||||
a.logger.Printf("version %s did not come up, restoring %s", r.result.Tag, a.layout.PreviousPath())
|
||||
restoreTemp := a.layout.BinaryPath + update.RestoreTempSuffix
|
||||
if err := a.replaceViaTemp(a.layout.PreviousPath(), a.layout.BinaryPath, restoreTemp); err != nil {
|
||||
return r.failLoudly(fmt.Errorf("the previous binary could not be restored, the site may be down: %w", err))
|
||||
}
|
||||
if !a.restartAndAwait(r.result.FromVersion) {
|
||||
return r.failLoudly(errors.New("the previous version did not come back after the rollback"))
|
||||
}
|
||||
return r.finish(update.OutcomeRolledBack)
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) restartAndAwait(expectedVersion string) bool {
|
||||
baseline, _ := a.running.Read()
|
||||
restartedAt := a.clock.Now()
|
||||
if err := a.service.Restart(); err != nil {
|
||||
a.logger.Printf("restarting the service failed: %v", err)
|
||||
return false
|
||||
}
|
||||
for a.clock.Now().Sub(restartedAt) < update.RestartWindow {
|
||||
if a.isBackUp(baseline, restartedAt, expectedVersion) {
|
||||
return true
|
||||
}
|
||||
a.clock.Sleep(update.PollInterval)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) isBackUp(baseline update.RunningInfo, restartedAt time.Time, expectedVersion string) bool {
|
||||
if !a.health.Healthy() {
|
||||
return false
|
||||
}
|
||||
info, found := a.running.Read()
|
||||
if !found || !info.IsNewerThan(baseline, restartedAt) {
|
||||
return false
|
||||
}
|
||||
return expectedVersion == "" || info.Version == expectedVersion
|
||||
}
|
||||
|
||||
func (r *helperRun) record() {
|
||||
if err := r.apply.results.Write(r.result); err != nil {
|
||||
r.apply.logger.Printf("update-result.json could not be written: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *helperRun) finish(outcome string) error {
|
||||
finishedAt := r.apply.clock.Now().UTC()
|
||||
r.result.Outcome = outcome
|
||||
r.result.FinishedAt = &finishedAt
|
||||
r.record()
|
||||
r.cleanUp()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *helperRun) fail(reason error) error {
|
||||
r.apply.logger.Printf("restart request refused or failed: %v", reason)
|
||||
return r.finish(update.OutcomeFailed)
|
||||
}
|
||||
|
||||
func (r *helperRun) failLoudly(reason error) error {
|
||||
r.apply.logger.Printf("restart request failed: %v", reason)
|
||||
_ = r.finish(update.OutcomeFailed)
|
||||
return reason
|
||||
}
|
||||
|
||||
func (r *helperRun) recoverPanic(err *error) {
|
||||
if recovered := recover(); recovered != nil {
|
||||
*err = r.failLoudly(fmt.Errorf("panic: %v", recovered))
|
||||
}
|
||||
}
|
||||
|
||||
func (r *helperRun) cleanUp() {
|
||||
a := r.apply
|
||||
if r.tempDir != "" {
|
||||
a.removeTreeQuietly(r.tempDir)
|
||||
}
|
||||
if r.stagedTag != "" {
|
||||
a.removeStaged(r.stagedTag)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) removeStaged(tag string) {
|
||||
if err := a.requireDirectory(a.layout.UpdatesDir()); err != nil {
|
||||
a.logger.Printf("staged files left in place: %v", err)
|
||||
return
|
||||
}
|
||||
staged := a.layout.StagedDir(tag)
|
||||
info, err := a.files.Lstat(staged)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if info.IsSymlink {
|
||||
a.removeQuietly(staged)
|
||||
return
|
||||
}
|
||||
a.removeTreeQuietly(staged)
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) removeQuietly(target string) {
|
||||
_ = a.files.Remove(target)
|
||||
}
|
||||
|
||||
func (a *ApplyRestartRequestUseCase) removeTreeQuietly(target string) {
|
||||
if err := a.files.RemoveAll(target); err != nil {
|
||||
a.logger.Printf("could not remove %s: %v", target, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
"time"
|
||||
)
|
||||
|
||||
type CheckForUpdateUseCase struct {
|
||||
feed update.ReleaseFeed
|
||||
store update.StatusStore
|
||||
currentVersion string
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewCheckForUpdateUseCase(feed update.ReleaseFeed, store update.StatusStore, currentVersion string, now func() time.Time) *CheckForUpdateUseCase {
|
||||
return &CheckForUpdateUseCase{feed: feed, store: store, currentVersion: currentVersion, now: now}
|
||||
}
|
||||
|
||||
func (c *CheckForUpdateUseCase) Check() (update.UpdateStatus, error) {
|
||||
release, err := c.feed.Latest()
|
||||
if err != nil {
|
||||
return update.UpdateStatus{}, err
|
||||
}
|
||||
result := update.NewResult(release, c.now())
|
||||
if err := c.store.Save(result); err != nil {
|
||||
return update.UpdateStatus{}, err
|
||||
}
|
||||
return update.NewStatus(c.currentVersion, &result), nil
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
"time"
|
||||
)
|
||||
|
||||
type GetUpdateStatusUseCase struct {
|
||||
status updateStatusBuilder
|
||||
helper update.HelperDetector
|
||||
}
|
||||
|
||||
func NewGetUpdateStatusUseCase(store update.StatusStore, jobs update.JobStore, helper update.HelperDetector, results update.ResultStore, requests update.RestartRequestStore, currentVersion string, now func() time.Time) *GetUpdateStatusUseCase {
|
||||
return &GetUpdateStatusUseCase{
|
||||
status: updateStatusBuilder{store: store, jobs: jobs, results: results, requests: requests, currentVersion: currentVersion, now: now},
|
||||
helper: helper,
|
||||
}
|
||||
}
|
||||
|
||||
func (g *GetUpdateStatusUseCase) GetStatus(isOwner bool) update.UpdateStatus {
|
||||
return g.status.build(isOwner && g.helper.Installed())
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ManageBrowserUpdatesDependencies struct {
|
||||
Probe update.MachineProbe
|
||||
Locator update.ServiceLocator
|
||||
Units update.UnitWriter
|
||||
Manager update.UnitManager
|
||||
Status update.HelperStatusWriter
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
type EnableBrowserUpdatesUseCase struct {
|
||||
dependencies ManageBrowserUpdatesDependencies
|
||||
}
|
||||
|
||||
type DisableBrowserUpdatesUseCase struct {
|
||||
dependencies ManageBrowserUpdatesDependencies
|
||||
}
|
||||
|
||||
func NewEnableBrowserUpdatesUseCase(dependencies ManageBrowserUpdatesDependencies) *EnableBrowserUpdatesUseCase {
|
||||
return &EnableBrowserUpdatesUseCase{dependencies: dependencies}
|
||||
}
|
||||
|
||||
func NewDisableBrowserUpdatesUseCase(dependencies ManageBrowserUpdatesDependencies) *DisableBrowserUpdatesUseCase {
|
||||
return &DisableBrowserUpdatesUseCase{dependencies: dependencies}
|
||||
}
|
||||
|
||||
func (e *EnableBrowserUpdatesUseCase) Enable(options update.InstallOptions) (string, error) {
|
||||
d := e.dependencies
|
||||
if err := update.CheckInstallEnvironment(d.Probe); err != nil {
|
||||
return "", err
|
||||
}
|
||||
resolved, err := e.resolve(options)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := e.install(resolved); err != nil {
|
||||
e.undo()
|
||||
return "", err
|
||||
}
|
||||
status := update.HelperStatus{
|
||||
Version: update.HelperStatusVersion,
|
||||
Service: resolved.Service,
|
||||
Binary: resolved.Binary,
|
||||
DataDir: resolved.DataDir,
|
||||
InstalledAt: d.Now().UTC(),
|
||||
}
|
||||
if err := d.Status.Write(resolved.DataDir, status); err != nil {
|
||||
e.undo()
|
||||
return "", err
|
||||
}
|
||||
return enabledMessage(resolved), nil
|
||||
}
|
||||
|
||||
func (e *EnableBrowserUpdatesUseCase) resolve(options update.InstallOptions) (update.InstallOptions, error) {
|
||||
service := firstNonEmpty(options.Service, update.DefaultService)
|
||||
description, found := e.dependencies.Locator.Locate(service)
|
||||
resolved := update.InstallOptions{
|
||||
Service: service,
|
||||
Binary: firstNonEmpty(options.Binary, description.BinaryPath),
|
||||
DataDir: firstNonEmpty(options.DataDir, description.DataDir),
|
||||
}
|
||||
if resolved.Binary == "" || (resolved.DataDir == "" && !found) {
|
||||
return resolved, update.ErrServiceNotFound
|
||||
}
|
||||
if resolved.DataDir == "" {
|
||||
return resolved, update.ErrDataDirNotFound
|
||||
}
|
||||
resolved.Port = e.port(options.Port, description)
|
||||
return resolved, update.ValidatePort(resolved.Port)
|
||||
}
|
||||
|
||||
func (e *EnableBrowserUpdatesUseCase) port(flag string, description update.ServiceDescription) string {
|
||||
if flag != "" {
|
||||
return flag
|
||||
}
|
||||
if port, found := e.dependencies.Locator.PortFromEnvironmentFile(description.EnvironmentFile); found {
|
||||
return port
|
||||
}
|
||||
return update.DefaultPort
|
||||
}
|
||||
|
||||
func (e *EnableBrowserUpdatesUseCase) install(options update.InstallOptions) error {
|
||||
d := e.dependencies
|
||||
layout := update.HelperLayout{DataDir: options.DataDir, BinaryPath: options.Binary}
|
||||
if err := d.Units.Write(update.ServiceUnitName, update.RenderServiceUnit(options)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Units.Write(update.PathUnitName, update.RenderPathUnit(layout)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Manager.DaemonReload(); err != nil {
|
||||
return err
|
||||
}
|
||||
return d.Manager.EnableNow(update.PathUnitName)
|
||||
}
|
||||
|
||||
func (e *EnableBrowserUpdatesUseCase) undo() {
|
||||
d := e.dependencies
|
||||
_ = d.Manager.DisableNow(update.PathUnitName)
|
||||
_, _ = d.Units.Remove(update.ServiceUnitName)
|
||||
_, _ = d.Units.Remove(update.PathUnitName)
|
||||
_ = d.Manager.DaemonReload()
|
||||
}
|
||||
|
||||
func enabledMessage(options update.InstallOptions) string {
|
||||
lines := []string{
|
||||
"Browser updates are enabled for " + options.Service + ".",
|
||||
"Installed " + update.PathUnitName + " and " + update.ServiceUnitName + " (port " + options.Port + ") and wrote " + update.HelperStatusFileName + " in " + options.DataDir + ".",
|
||||
"To undo it, run: renewcms disable-browser-updates",
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func (u *DisableBrowserUpdatesUseCase) Disable(options update.InstallOptions) (string, error) {
|
||||
d := u.dependencies
|
||||
if d.Probe.OS() != update.OSLinux || !d.Probe.SystemdRunning() {
|
||||
return notEnabledMessage, nil
|
||||
}
|
||||
if err := update.CheckInstallEnvironment(d.Probe); err != nil {
|
||||
return "", err
|
||||
}
|
||||
dataDir := firstNonEmpty(options.DataDir, u.locatedDataDir(options.Service))
|
||||
|
||||
_ = d.Manager.DisableNow(update.PathUnitName)
|
||||
removed := u.removeUnits()
|
||||
if dataDir == "" {
|
||||
return "", update.ErrDataDirNotFound
|
||||
}
|
||||
statusRemoved, err := d.Status.Remove(dataDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !removed && !statusRemoved {
|
||||
return notEnabledMessage, nil
|
||||
}
|
||||
if err := d.Manager.DaemonReload(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return disabledMessage, nil
|
||||
}
|
||||
|
||||
func (u *DisableBrowserUpdatesUseCase) locatedDataDir(service string) string {
|
||||
description, _ := u.dependencies.Locator.Locate(firstNonEmpty(service, update.DefaultService))
|
||||
return description.DataDir
|
||||
}
|
||||
|
||||
func (u *DisableBrowserUpdatesUseCase) removeUnits() bool {
|
||||
removedAny := false
|
||||
for _, name := range []string{update.PathUnitName, update.ServiceUnitName} {
|
||||
removed, err := u.dependencies.Units.Remove(name)
|
||||
removedAny = removedAny || (removed && err == nil)
|
||||
}
|
||||
return removedAny
|
||||
}
|
||||
|
||||
const (
|
||||
notEnabledMessage = "Browser updates were not enabled, nothing to remove."
|
||||
disabledMessage = "Browser updates are disabled. The restart request, the result, the staged files and the backups were left in place."
|
||||
)
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
"time"
|
||||
)
|
||||
|
||||
type RecordRunningInfoUseCase struct {
|
||||
store update.RunningInfoStore
|
||||
version string
|
||||
pid int
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewRecordRunningInfoUseCase(store update.RunningInfoStore, version string, pid int, now func() time.Time) *RecordRunningInfoUseCase {
|
||||
return &RecordRunningInfoUseCase{store: store, version: version, pid: pid, now: now}
|
||||
}
|
||||
|
||||
func (r *RecordRunningInfoUseCase) Record() error {
|
||||
return r.store.Write(update.RunningInfo{Version: r.version, Pid: r.pid, StartedAt: r.now().UTC()})
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type RequestRestartUseCase struct {
|
||||
jobs update.JobStore
|
||||
helper update.HelperDetector
|
||||
results update.ResultStore
|
||||
requests update.RestartRequestStore
|
||||
status updateStatusBuilder
|
||||
now func() time.Time
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewRequestRestartUseCase(store update.StatusStore, jobs update.JobStore, helper update.HelperDetector, results update.ResultStore, requests update.RestartRequestStore, currentVersion string, now func() time.Time) *RequestRestartUseCase {
|
||||
return &RequestRestartUseCase{
|
||||
jobs: jobs,
|
||||
helper: helper,
|
||||
results: results,
|
||||
requests: requests,
|
||||
status: updateStatusBuilder{store: store, jobs: jobs, results: results, requests: requests, currentVersion: currentVersion, now: now},
|
||||
now: now,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RequestRestartUseCase) Request(userId uint32, kind string) (update.UpdateStatus, error) {
|
||||
if !r.helper.Installed() {
|
||||
return update.UpdateStatus{}, update.ErrNotPrepared
|
||||
}
|
||||
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
current := r.status.build(true)
|
||||
if err := refuseWhileBusy(current); err != nil {
|
||||
return update.UpdateStatus{}, err
|
||||
}
|
||||
request, err := r.requestFor(kind, userId)
|
||||
if err != nil {
|
||||
return update.UpdateStatus{}, err
|
||||
}
|
||||
if err := r.results.Delete(); err != nil {
|
||||
return update.UpdateStatus{}, err
|
||||
}
|
||||
if err := r.requests.Write(request); err != nil {
|
||||
return update.UpdateStatus{}, err
|
||||
}
|
||||
return r.status.build(true), nil
|
||||
}
|
||||
|
||||
func refuseWhileBusy(status update.UpdateStatus) error {
|
||||
switch status.State {
|
||||
case update.StateDownloading, update.StateVerifying:
|
||||
return update.ErrJobInProgress
|
||||
case update.StateRestarting:
|
||||
return update.ErrRestartPending
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RequestRestartUseCase) requestFor(kind string, userId uint32) (update.RestartRequest, error) {
|
||||
request := update.RestartRequest{
|
||||
Kind: update.RestartKindRestart,
|
||||
RequestedAt: r.now().UTC(),
|
||||
RequestedBy: userId,
|
||||
}
|
||||
if job, found := r.jobs.Load(); found && job.State == update.StateReady {
|
||||
request.Kind = update.RestartKindUpdate
|
||||
request.Tag = job.Tag
|
||||
}
|
||||
if kind != "" && kind != request.Kind {
|
||||
return update.RestartRequest{}, update.ErrRestartKindMismatch
|
||||
}
|
||||
return request, nil
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type StartUpdateDownloadUseCase struct {
|
||||
store update.StatusStore
|
||||
jobs update.JobStore
|
||||
helper update.HelperDetector
|
||||
results update.ResultStore
|
||||
status updateStatusBuilder
|
||||
fetcher update.AssetFetcher
|
||||
verifier update.SignatureVerifier
|
||||
runner update.StagedBinaryRunner
|
||||
backup update.DatabaseBackup
|
||||
staging update.StagingArea
|
||||
logger update.Logger
|
||||
currentVersion string
|
||||
platform update.Platform
|
||||
feedHost string
|
||||
now func() time.Time
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
type StartUpdateDownloadDependencies struct {
|
||||
Store update.StatusStore
|
||||
Jobs update.JobStore
|
||||
Helper update.HelperDetector
|
||||
Results update.ResultStore
|
||||
Requests update.RestartRequestStore
|
||||
Fetcher update.AssetFetcher
|
||||
Verifier update.SignatureVerifier
|
||||
Runner update.StagedBinaryRunner
|
||||
Backup update.DatabaseBackup
|
||||
Staging update.StagingArea
|
||||
Logger update.Logger
|
||||
CurrentVersion string
|
||||
Platform update.Platform
|
||||
FeedURL string
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
type jobFailure struct {
|
||||
kind string
|
||||
reason error
|
||||
}
|
||||
|
||||
func (f jobFailure) Error() string {
|
||||
return f.reason.Error()
|
||||
}
|
||||
|
||||
func NewStartUpdateDownloadUseCase(dependencies StartUpdateDownloadDependencies) *StartUpdateDownloadUseCase {
|
||||
return &StartUpdateDownloadUseCase{
|
||||
store: dependencies.Store,
|
||||
jobs: dependencies.Jobs,
|
||||
helper: dependencies.Helper,
|
||||
results: dependencies.Results,
|
||||
status: updateStatusBuilder{
|
||||
store: dependencies.Store,
|
||||
jobs: dependencies.Jobs,
|
||||
results: dependencies.Results,
|
||||
requests: dependencies.Requests,
|
||||
currentVersion: dependencies.CurrentVersion,
|
||||
now: dependencies.Now,
|
||||
},
|
||||
fetcher: dependencies.Fetcher,
|
||||
verifier: dependencies.Verifier,
|
||||
runner: dependencies.Runner,
|
||||
backup: dependencies.Backup,
|
||||
staging: dependencies.Staging,
|
||||
logger: dependencies.Logger,
|
||||
currentVersion: dependencies.CurrentVersion,
|
||||
platform: dependencies.Platform,
|
||||
feedHost: update.HostOf(dependencies.FeedURL),
|
||||
now: dependencies.Now,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) Start() (update.UpdateStatus, error) {
|
||||
if !s.helper.Installed() {
|
||||
return update.UpdateStatus{}, update.ErrNotPrepared
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if job, found := s.jobs.Load(); found && job.Occupies() {
|
||||
return update.UpdateStatus{}, update.ErrJobInProgress
|
||||
}
|
||||
if s.status.build(true).State == update.StateRestarting {
|
||||
return update.UpdateStatus{}, update.ErrRestartPending
|
||||
}
|
||||
result, found := s.store.Load()
|
||||
if !found || !update.IsNewer(s.currentVersion, result.Latest) {
|
||||
return update.UpdateStatus{}, update.ErrNothingToUpdate
|
||||
}
|
||||
binary, checksums, signature, err := s.preflight(result)
|
||||
if err != nil {
|
||||
s.logger.Printf("update download refused: %v", err)
|
||||
return update.UpdateStatus{}, update.ErrPreflightRefused
|
||||
}
|
||||
|
||||
job := update.Job{
|
||||
Tag: result.Latest,
|
||||
State: update.StateDownloading,
|
||||
StartedAt: s.now().UTC(),
|
||||
TotalBytes: binary.Size,
|
||||
}
|
||||
if err := s.results.Delete(); err != nil {
|
||||
return update.UpdateStatus{}, err
|
||||
}
|
||||
if err := s.jobs.Save(job); err != nil {
|
||||
return update.UpdateStatus{}, err
|
||||
}
|
||||
status := s.status.build(true)
|
||||
go s.run(job, binary, checksums, signature)
|
||||
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) preflight(result update.CheckResult) (binary, checksums, signature update.Asset, err error) {
|
||||
names := []string{update.AssetName(result.Latest, s.platform), update.ChecksumsAssetName, update.SignatureAssetName}
|
||||
found := make([]update.Asset, 0, len(names))
|
||||
for _, name := range names {
|
||||
asset, ok := update.FindAsset(result.Assets, name)
|
||||
if !ok {
|
||||
return binary, checksums, signature, fmt.Errorf("asset %q is not listed for %s", name, result.Latest)
|
||||
}
|
||||
if !update.IsAllowedAssetURL(asset.URL, s.feedHost) {
|
||||
return binary, checksums, signature, fmt.Errorf("asset %q has a url outside the feed host or without https", name)
|
||||
}
|
||||
found = append(found, asset)
|
||||
}
|
||||
return found[0], found[1], found[2], nil
|
||||
}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) run(job update.Job, binary, checksums, signature update.Asset) {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
s.fail(job, downloadFailure(fmt.Errorf("panic: %v", recovered)))
|
||||
}
|
||||
}()
|
||||
if err := s.execute(&job, binary, checksums, signature); err != nil {
|
||||
s.fail(job, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) execute(job *update.Job, binary, checksums, signature update.Asset) error {
|
||||
binaryPath := s.staging.PathFor(job.Tag, binary.Name)
|
||||
checksumsPath := s.staging.PathFor(job.Tag, checksums.Name)
|
||||
signaturePath := s.staging.PathFor(job.Tag, signature.Name)
|
||||
|
||||
if err := s.staging.Prepare(job.Tag); err != nil {
|
||||
return downloadFailure(err)
|
||||
}
|
||||
if err := s.fetchSmall(checksums, checksumsPath); err != nil {
|
||||
return downloadFailure(err)
|
||||
}
|
||||
if err := s.fetchSmall(signature, signaturePath); err != nil {
|
||||
return downloadFailure(err)
|
||||
}
|
||||
if err := s.fetchBinary(job, binary, binaryPath); err != nil {
|
||||
return downloadFailure(err)
|
||||
}
|
||||
|
||||
job.State = update.StateVerifying
|
||||
if err := s.jobs.Save(*job); err != nil {
|
||||
return downloadFailure(err)
|
||||
}
|
||||
if err := s.verify(job.Tag, binary.Name, binaryPath, checksumsPath, signaturePath); err != nil {
|
||||
return jobFailure{kind: update.ErrorKindVerification, reason: err}
|
||||
}
|
||||
if _, err := s.backup.Backup(); err != nil {
|
||||
return downloadFailure(err)
|
||||
}
|
||||
|
||||
job.State = update.StateReady
|
||||
job.StagedBinary = binaryPath
|
||||
job.DownloadedBytes = 0
|
||||
job.TotalBytes = 0
|
||||
return s.jobs.Save(*job)
|
||||
}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) fetchSmall(asset update.Asset, destination string) error {
|
||||
if err := s.fetcher.Fetch(asset, destination, ignoreProgress); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.assertDeclaredSize(asset, destination)
|
||||
}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) fetchBinary(job *update.Job, asset update.Asset, destination string) error {
|
||||
lastPercent := -1
|
||||
report := func(done int64, _ int64) {
|
||||
current := *job
|
||||
current.DownloadedBytes = done
|
||||
percent := 0
|
||||
if progress := current.Progress(); progress != nil {
|
||||
percent = progress.Percent
|
||||
}
|
||||
if percent == lastPercent && done < asset.Size {
|
||||
return
|
||||
}
|
||||
lastPercent = percent
|
||||
_ = s.jobs.Save(current)
|
||||
}
|
||||
if err := s.fetcher.Fetch(asset, destination, report); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.assertDeclaredSize(asset, destination)
|
||||
}
|
||||
|
||||
func ignoreProgress(int64, int64) {}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) assertDeclaredSize(asset update.Asset, path string) error {
|
||||
size, err := s.staging.Size(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if asset.Size > 0 && size != asset.Size {
|
||||
return fmt.Errorf("received %d bytes for %q, the release declares %d", size, asset.Name, asset.Size)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) verify(tag, assetName, binaryPath, checksumsPath, signaturePath string) error {
|
||||
if err := s.verifier.Verify(checksumsPath, signaturePath); err != nil {
|
||||
return fmt.Errorf("signature check: %w", err)
|
||||
}
|
||||
content, err := s.staging.ReadChecksums(checksumsPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
expected, found := update.ChecksumFor(content, assetName)
|
||||
if !found {
|
||||
return fmt.Errorf("checksums.txt has no line for %q", assetName)
|
||||
}
|
||||
actual, err := update.FileSHA256(binaryPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if actual != expected {
|
||||
return fmt.Errorf("sha-256 mismatch for %q", assetName)
|
||||
}
|
||||
if err := s.staging.MakeExecutable(binaryPath); err != nil {
|
||||
return err
|
||||
}
|
||||
output, err := s.runner.Version(binaryPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("running the staged binary: %w", err)
|
||||
}
|
||||
if output != tag {
|
||||
return fmt.Errorf("the staged binary reports version %q, expected %q", output, tag)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func downloadFailure(err error) error {
|
||||
return jobFailure{kind: update.ErrorKindDownload, reason: err}
|
||||
}
|
||||
|
||||
func (s *StartUpdateDownloadUseCase) fail(job update.Job, err error) {
|
||||
kind := update.ErrorKindDownload
|
||||
var failure jobFailure
|
||||
if errors.As(err, &failure) {
|
||||
kind = failure.kind
|
||||
}
|
||||
s.logger.Printf("update to %s failed (%s): %v", job.Tag, kind, err)
|
||||
_ = s.staging.Remove(job.Tag)
|
||||
job.State = update.StateFailed
|
||||
job.Error = kind
|
||||
job.DownloadedBytes = 0
|
||||
job.TotalBytes = 0
|
||||
job.StagedBinary = ""
|
||||
if saveErr := s.jobs.Save(job); saveErr != nil {
|
||||
s.logger.Printf("update job record could not be saved: %v", saveErr)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package useCases
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type updateStatusBuilder struct {
|
||||
store update.StatusStore
|
||||
jobs update.JobStore
|
||||
results update.ResultStore
|
||||
requests update.RestartRequestStore
|
||||
currentVersion string
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func (b updateStatusBuilder) build(canApply bool) update.UpdateStatus {
|
||||
status := b.baseStatus()
|
||||
if job, found := b.jobs.Load(); found {
|
||||
status = status.WithJob(job)
|
||||
}
|
||||
status.CanApply = canApply
|
||||
|
||||
request, requestErr := b.requests.Read()
|
||||
result, hasResult := b.results.Read()
|
||||
if hasResult {
|
||||
status.FinishedAt = result.FinishedAt
|
||||
}
|
||||
switch {
|
||||
case !errors.Is(requestErr, update.ErrNoRestartRequest):
|
||||
return status.WithRestartRequest(request)
|
||||
case hasResult:
|
||||
return status.WithResult(result, b.currentVersion, b.now())
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func (b updateStatusBuilder) baseStatus() update.UpdateStatus {
|
||||
if result, found := b.store.Load(); found {
|
||||
return update.NewStatus(b.currentVersion, &result)
|
||||
}
|
||||
return update.NewStatus(b.currentVersion, nil)
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/infrastructure/update/releasesign"
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const placeholderPublicKey = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
|
||||
|
||||
type signingKeyPair struct {
|
||||
privatePath string
|
||||
publicPath string
|
||||
}
|
||||
|
||||
func runReleaseSign(args ...string) (int, string) {
|
||||
var stdout, stderr bytes.Buffer
|
||||
code := releasesign.Run(args, &stdout, &stderr)
|
||||
return code, stdout.String() + stderr.String()
|
||||
}
|
||||
|
||||
func newSigningKeyPair(t *testing.T, dir string) signingKeyPair {
|
||||
t.Helper()
|
||||
pair := signingKeyPair{privatePath: filepath.Join(dir, "release.key"), publicPath: filepath.Join(dir, "release.pub")}
|
||||
if code, output := runReleaseSign("keygen", pair.privatePath, "--pub-out", pair.publicPath); code != 0 {
|
||||
t.Fatalf("keygen failed: %s", output)
|
||||
}
|
||||
return pair
|
||||
}
|
||||
|
||||
func writeChecksums(t *testing.T, dir string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(dir, "checksums.txt")
|
||||
if err := os.WriteFile(path, []byte("abc renewcms_v1_linux_amd64\ndef renewcms_v1_darwin_arm64\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestReleaseSigningRoundTrip(t *testing.T) {
|
||||
t.Run("Release signing round trip with a throwaway key", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
pair := newSigningKeyPair(t, dir)
|
||||
file := writeChecksums(t, dir)
|
||||
|
||||
if code, output := runReleaseSign("sign", file, "--key", pair.privatePath, "--pub", pair.publicPath); code != 0 {
|
||||
t.Fatalf("sign failed: %s", output)
|
||||
}
|
||||
if code, output := runReleaseSign("verify", file, "--pub", pair.publicPath); code != 0 {
|
||||
t.Fatalf("verify failed: %s", output)
|
||||
}
|
||||
|
||||
content, _ := os.ReadFile(file)
|
||||
content[0] ^= 0x01
|
||||
if err := os.WriteFile(file, content, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, output := runReleaseSign("verify", file, "--pub", pair.publicPath)
|
||||
if code == 0 || !strings.Contains(output, "signature does not match") {
|
||||
t.Errorf("a changed file must fail verify with a clear message: %d %q", code, output)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("verify with a different public key fails", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
pair := newSigningKeyPair(t, dir)
|
||||
other := newSigningKeyPair(t, t.TempDir())
|
||||
file := writeChecksums(t, dir)
|
||||
runReleaseSign("sign", file, "--key", pair.privatePath, "--pub", pair.publicPath)
|
||||
|
||||
if code, _ := runReleaseSign("verify", file, "--pub", other.publicPath); code == 0 {
|
||||
t.Error("verify with another public key must fail")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("sign takes the private key from RELEASE_SIGNING_KEY", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
pair := newSigningKeyPair(t, dir)
|
||||
file := writeChecksums(t, dir)
|
||||
t.Setenv("RELEASE_SIGNING_KEY", pair.privatePath)
|
||||
|
||||
if code, output := runReleaseSign("sign", file, "--pub", pair.publicPath); code != 0 {
|
||||
t.Fatalf("sign failed: %s", output)
|
||||
}
|
||||
if code, output := runReleaseSign("verify", file, "--pub", pair.publicPath); code != 0 {
|
||||
t.Fatalf("verify failed: %s", output)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("sign without any key says so", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
pair := newSigningKeyPair(t, dir)
|
||||
t.Setenv("RELEASE_SIGNING_KEY", "")
|
||||
code, output := runReleaseSign("sign", writeChecksums(t, dir), "--pub", pair.publicPath)
|
||||
if code == 0 || !strings.Contains(output, "RELEASE_SIGNING_KEY") {
|
||||
t.Errorf("code = %d output = %q", code, output)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("sign with a missing key file names the path", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
pair := newSigningKeyPair(t, dir)
|
||||
missing := filepath.Join(dir, "missing.key")
|
||||
code, output := runReleaseSign("sign", writeChecksums(t, dir), "--key", missing, "--pub", pair.publicPath)
|
||||
if code == 0 || !strings.Contains(output, missing) {
|
||||
t.Errorf("code = %d output = %q", code, output)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestReleaseSignKeygen(t *testing.T) {
|
||||
t.Run("keygen refuses a path inside the repository", func(t *testing.T) {
|
||||
repoRoot, err := filepath.Abs("..")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inside := filepath.Join(repoRoot, "tmp", "releasesign-test.key")
|
||||
t.Cleanup(func() { os.Remove(inside) })
|
||||
|
||||
code, output := runReleaseSign("keygen", inside)
|
||||
|
||||
if code == 0 || !strings.Contains(output, "inside the repository") {
|
||||
t.Errorf("code = %d output = %q", code, output)
|
||||
}
|
||||
if _, err := os.Stat(inside); err == nil {
|
||||
t.Error("nothing may be written inside the repository")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("keygen never overwrites an existing key", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
pair := newSigningKeyPair(t, dir)
|
||||
before, _ := os.ReadFile(pair.privatePath)
|
||||
|
||||
code, _ := runReleaseSign("keygen", pair.privatePath)
|
||||
|
||||
after, _ := os.ReadFile(pair.privatePath)
|
||||
if code == 0 || !bytes.Equal(before, after) {
|
||||
t.Errorf("code = %d, key changed = %v", code, !bytes.Equal(before, after))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("keygen prints the public key and where to commit it", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
code, output := runReleaseSign("keygen", filepath.Join(dir, "k"))
|
||||
if code != 0 || !strings.Contains(output, "internal/infrastructure/update/release.pub") {
|
||||
t.Errorf("code = %d output = %q", code, output)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestReleaseSignPlaceholderKey(t *testing.T) {
|
||||
t.Run("The placeholder public key is refused", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
pair := newSigningKeyPair(t, dir)
|
||||
placeholder := filepath.Join(dir, "placeholder.pub")
|
||||
if err := os.WriteFile(placeholder, []byte(placeholderPublicKey+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file := writeChecksums(t, dir)
|
||||
|
||||
signCode, signOutput := runReleaseSign("sign", file, "--key", pair.privatePath, "--pub", placeholder)
|
||||
verifyCode, verifyOutput := runReleaseSign("verify", file, "--pub", placeholder)
|
||||
|
||||
for _, output := range []string{signOutput, verifyOutput} {
|
||||
if !strings.Contains(output, "placeholder public key has not been replaced") {
|
||||
t.Errorf("output = %q", output)
|
||||
}
|
||||
}
|
||||
if signCode == 0 || verifyCode == 0 {
|
||||
t.Errorf("sign = %d verify = %d", signCode, verifyCode)
|
||||
}
|
||||
if _, err := os.Stat(file + ".sig"); err == nil {
|
||||
t.Error("no .sig may be written")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a malformed public key is refused", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
bad := filepath.Join(dir, "bad.pub")
|
||||
_ = os.WriteFile(bad, []byte("not base64!"), 0o600)
|
||||
if code, _ := runReleaseSign("verify", writeChecksums(t, dir), "--pub", bad); code == 0 {
|
||||
t.Error("a malformed key must fail")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestReleaseSignKeyMismatch(t *testing.T) {
|
||||
t.Run("sign refuses a private key that does not match the public key", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
signer := newSigningKeyPair(t, dir)
|
||||
other := newSigningKeyPair(t, t.TempDir())
|
||||
file := writeChecksums(t, dir)
|
||||
|
||||
code, output := runReleaseSign("sign", file, "--key", signer.privatePath, "--pub", other.publicPath)
|
||||
|
||||
if code == 0 || !strings.Contains(output, "does not match") {
|
||||
t.Errorf("code = %d output = %q", code, output)
|
||||
}
|
||||
if _, err := os.Stat(file + ".sig"); err == nil {
|
||||
t.Error("no .sig may be written")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestReleaseSignUsage(t *testing.T) {
|
||||
for name, args := range map[string][]string{
|
||||
"no command": nil,
|
||||
"unknown command": {"explode"},
|
||||
"missing file": {"verify"},
|
||||
"unknown flag": {"verify", "x", "--nope", "1"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if code, _ := runReleaseSign(args...); code == 0 {
|
||||
t.Error("expected a non-zero exit")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReleaseSignChecksums(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for name, content := range map[string]string{
|
||||
"renewcms_v2.5.0_linux_amd64": "linux",
|
||||
"renewcms_v2.5.0_windows_amd64.exe": "windows",
|
||||
"renewcms_v2.4.0_linux_amd64": "old",
|
||||
} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("writes the SHA-256 of the matching binaries only", func(t *testing.T) {
|
||||
code, output := runReleaseSign("checksums", dir, "--match", "renewcms_v2.5.0_*")
|
||||
if code != 0 {
|
||||
t.Fatalf("checksums failed: %s", output)
|
||||
}
|
||||
content, err := os.ReadFile(filepath.Join(dir, "checksums.txt"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lines := strings.Split(strings.TrimSpace(string(content)), "\n")
|
||||
if len(lines) != 2 || !strings.HasSuffix(lines[0], " renewcms_v2.5.0_linux_amd64") || !strings.HasSuffix(lines[1], " renewcms_v2.5.0_windows_amd64.exe") {
|
||||
t.Fatalf("checksums.txt = %q", content)
|
||||
}
|
||||
sum := sha256.Sum256([]byte("linux"))
|
||||
if want := hex.EncodeToString(sum[:]) + " renewcms_v2.5.0_linux_amd64"; lines[0] != want {
|
||||
t.Errorf("line = %q, want %q", lines[0], want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a second run does not list checksums.txt or its signature", func(t *testing.T) {
|
||||
runReleaseSign("checksums", dir, "--match", "*")
|
||||
content, _ := os.ReadFile(filepath.Join(dir, "checksums.txt"))
|
||||
if strings.Contains(string(content), "checksums.txt") {
|
||||
t.Errorf("checksums.txt lists itself: %q", content)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no match is an error", func(t *testing.T) {
|
||||
if code, _ := runReleaseSign("checksums", dir, "--match", "nothing_*"); code == 0 {
|
||||
t.Error("expected a non-zero exit")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestReleaseSignFailsOnUnwritableOutputs(t *testing.T) {
|
||||
t.Run("keygen reports a public key that cannot be written", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
code, _ := runReleaseSign("keygen", filepath.Join(dir, "release.key"), "--pub-out", filepath.Join(dir, "missing", "release.pub"))
|
||||
if code == 0 {
|
||||
t.Fatal("keygen exited 0 although the public key could not be written")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("keygen reports a trailing flag with no value without panicking", func(t *testing.T) {
|
||||
code, _ := runReleaseSign("keygen", filepath.Join(t.TempDir(), "release.key"), "--pub-out")
|
||||
if code == 0 {
|
||||
t.Fatal("keygen exited 0 for a flag with no value")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("sign reports a signature that cannot be written", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
pair := newSigningKeyPair(t, dir)
|
||||
file := writeChecksums(t, dir)
|
||||
if err := os.Mkdir(file+".sig", 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, _ := runReleaseSign("sign", file, "--key", pair.privatePath, "--pub", pair.publicPath); code == 0 {
|
||||
t.Fatal("sign exited 0 although the signature could not be written")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("checksums reports a checksums file that cannot be written", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "a.bin"), []byte("a"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(filepath.Join(dir, "checksums.txt"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code, _ := runReleaseSign("checksums", dir, "--match", "*.bin"); code == 0 {
|
||||
t.Fatal("checksums exited 0 although checksums.txt could not be written")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
infraUpdate "RenewCMS/internal/infrastructure/update"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func buildServerBinary(t *testing.T, ldflags string) string {
|
||||
t.Helper()
|
||||
if _, err := exec.LookPath("go"); err != nil {
|
||||
t.Skip("the go tool is not on PATH")
|
||||
}
|
||||
name := "server"
|
||||
if runtime.GOOS == "windows" {
|
||||
name += ".exe"
|
||||
}
|
||||
output := filepath.Join(t.TempDir(), name)
|
||||
arguments := []string{"build", "-tags", "nofrontend"}
|
||||
if ldflags != "" {
|
||||
arguments = append(arguments, "-ldflags", ldflags)
|
||||
}
|
||||
arguments = append(arguments, "-o", output, "RenewCMS/cmd/server")
|
||||
build := exec.Command("go", arguments...)
|
||||
build.Env = append(os.Environ(), "CGO_ENABLED=0")
|
||||
if combined, err := build.CombinedOutput(); err != nil {
|
||||
t.Fatalf("build failed: %v\n%s", err, combined)
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
func emptyEnvironment() []string {
|
||||
if runtime.GOOS == "windows" {
|
||||
return []string{"SystemRoot=" + os.Getenv("SystemRoot")}
|
||||
}
|
||||
return []string{}
|
||||
}
|
||||
|
||||
func TestServerVersionFlag(t *testing.T) {
|
||||
t.Run("it prints the build version and exits 0 without reading .env or the database", func(t *testing.T) {
|
||||
binary := buildServerBinary(t, "-X main.version=v9.9.9")
|
||||
workDir := t.TempDir()
|
||||
command := exec.Command(binary, "--version")
|
||||
command.Dir = workDir
|
||||
command.Env = emptyEnvironment()
|
||||
|
||||
output, err := command.Output()
|
||||
|
||||
if err != nil || strings.TrimSpace(string(output)) != "v9.9.9" {
|
||||
t.Fatalf("output = %q, err = %v", output, err)
|
||||
}
|
||||
if entries, _ := os.ReadDir(workDir); len(entries) != 0 {
|
||||
t.Errorf("the working directory must stay empty, got %d entries", len(entries))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("with no ldflags version it prints dev", func(t *testing.T) {
|
||||
binary := buildServerBinary(t, "")
|
||||
command := exec.Command(binary, "--version")
|
||||
command.Dir = t.TempDir()
|
||||
command.Env = emptyEnvironment()
|
||||
|
||||
output, err := command.Output()
|
||||
|
||||
if err != nil || strings.TrimSpace(string(output)) != "dev" {
|
||||
t.Errorf("output = %q, err = %v", output, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the staged binary runner returns what the binary prints", func(t *testing.T) {
|
||||
binary := buildServerBinary(t, "-X main.version=v9.9.9")
|
||||
|
||||
version, err := infraUpdate.NewExecStagedBinaryRunner().Version(binary)
|
||||
|
||||
if err != nil || version != "v9.9.9" {
|
||||
t.Errorf("version = %q, err = %v", version, err)
|
||||
}
|
||||
if _, err := infraUpdate.NewExecStagedBinaryRunner().Version(filepath.Join(t.TempDir(), "missing")); err == nil {
|
||||
t.Error("a binary that cannot be run must be an error")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
infraUpdate "RenewCMS/internal/infrastructure/update"
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var errAssetDisk = errors.New("write failed: no space left on device")
|
||||
|
||||
type failingWriteCloser struct {
|
||||
file *os.File
|
||||
allowed int
|
||||
}
|
||||
|
||||
func (f *failingWriteCloser) Write(chunk []byte) (int, error) {
|
||||
if f.allowed <= 0 {
|
||||
return 0, errAssetDisk
|
||||
}
|
||||
if len(chunk) > f.allowed {
|
||||
written, _ := f.file.Write(chunk[:f.allowed])
|
||||
f.allowed = 0
|
||||
return written, errAssetDisk
|
||||
}
|
||||
f.allowed -= len(chunk)
|
||||
return f.file.Write(chunk)
|
||||
}
|
||||
|
||||
func (f *failingWriteCloser) Close() error {
|
||||
return f.file.Close()
|
||||
}
|
||||
|
||||
func assetOf(server *httptest.Server, name string, size int64) update.Asset {
|
||||
return update.Asset{Name: name, URL: server.URL + "/" + name, Size: size}
|
||||
}
|
||||
|
||||
func fetchTarget(t *testing.T) string {
|
||||
t.Helper()
|
||||
return filepath.Join(t.TempDir(), "staged", "asset")
|
||||
}
|
||||
|
||||
func noProgress(int64, int64) {}
|
||||
|
||||
func TestHTTPAssetFetcherDownloads(t *testing.T) {
|
||||
payload := bytes.Repeat([]byte("renewcms"), 512)
|
||||
|
||||
t.Run("writes the body and reports bytes done and total", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(payload) }))
|
||||
defer server.Close()
|
||||
fetcher := infraUpdate.NewHTTPAssetFetcher(server.URL, infraUpdate.WithInsecureScheme())
|
||||
target := fetchTarget(t)
|
||||
var lastDone, lastTotal int64
|
||||
|
||||
err := fetcher.Fetch(assetOf(server, "binary", int64(len(payload))), target, func(done, total int64) { lastDone, lastTotal = done, total })
|
||||
|
||||
written, readErr := os.ReadFile(target)
|
||||
if err != nil || readErr != nil || !bytes.Equal(written, payload) {
|
||||
t.Fatalf("err = %v, read = %v", err, readErr)
|
||||
}
|
||||
if lastDone != int64(len(payload)) || lastTotal != int64(len(payload)) {
|
||||
t.Errorf("progress = %d of %d", lastDone, lastTotal)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a truncated body is an error and leaves no file", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Length", "4096")
|
||||
_, _ = w.Write(payload[:2048])
|
||||
w.(http.Flusher).Flush()
|
||||
panic(http.ErrAbortHandler)
|
||||
}))
|
||||
defer server.Close()
|
||||
target := fetchTarget(t)
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(server.URL, infraUpdate.WithInsecureScheme()).Fetch(assetOf(server, "binary", 4096), target, noProgress)
|
||||
|
||||
if err == nil {
|
||||
t.Error("a truncated download must fail")
|
||||
}
|
||||
if _, statErr := os.Stat(target); !os.IsNotExist(statErr) {
|
||||
t.Error("the partial file must be removed")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a file over its size cap is refused", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Transfer-Encoding", "chunked")
|
||||
_, _ = w.Write(payload)
|
||||
}))
|
||||
defer server.Close()
|
||||
target := fetchTarget(t)
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(server.URL, infraUpdate.WithInsecureScheme(), infraUpdate.WithSizeCap(100)).Fetch(assetOf(server, "binary", 100), target, noProgress)
|
||||
|
||||
if err == nil {
|
||||
t.Error("the size cap must stop the download")
|
||||
}
|
||||
if _, statErr := os.Stat(target); !os.IsNotExist(statErr) {
|
||||
t.Error("the oversized file must be removed")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the production caps are 64 KiB for checksums and 1 KiB for the signature", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write(bytes.Repeat([]byte("a"), 2048))
|
||||
}))
|
||||
defer server.Close()
|
||||
fetcher := infraUpdate.NewHTTPAssetFetcher(server.URL, infraUpdate.WithInsecureScheme())
|
||||
|
||||
if err := fetcher.Fetch(assetOf(server, "checksums.txt.sig", 2048), fetchTarget(t), noProgress); err == nil {
|
||||
t.Error("a 2 KiB signature must exceed the 1 KiB cap")
|
||||
}
|
||||
if err := fetcher.Fetch(assetOf(server, "checksums.txt", 2048), fetchTarget(t), noProgress); err != nil {
|
||||
t.Errorf("2 KiB of checksums is within the cap: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a stalled server hits the overall timeout", func(t *testing.T) {
|
||||
release := make(chan struct{})
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Length", "4096")
|
||||
_, _ = w.Write(payload[:10])
|
||||
w.(http.Flusher).Flush()
|
||||
select {
|
||||
case <-release:
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
defer close(release)
|
||||
started := time.Now()
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(server.URL, infraUpdate.WithInsecureScheme(), infraUpdate.WithTimeout(150*time.Millisecond)).Fetch(assetOf(server, "binary", 4096), fetchTarget(t), noProgress)
|
||||
|
||||
if err == nil || time.Since(started) > 3*time.Second {
|
||||
t.Errorf("err = %v after %v", err, time.Since(started))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a 404 or 500 is an error", func(t *testing.T) {
|
||||
for _, status := range []int{http.StatusNotFound, http.StatusInternalServerError} {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(status) }))
|
||||
target := fetchTarget(t)
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(server.URL, infraUpdate.WithInsecureScheme()).Fetch(assetOf(server, "binary", 1), target, noProgress)
|
||||
server.Close()
|
||||
|
||||
if err == nil {
|
||||
t.Errorf("status %d must fail", status)
|
||||
}
|
||||
if _, statErr := os.Stat(target); !os.IsNotExist(statErr) {
|
||||
t.Errorf("status %d left a file", status)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the disk filling during the write is an error and leaves no file", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(payload) }))
|
||||
defer server.Close()
|
||||
opener := func(path string) (io.WriteCloser, error) {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
file, err := os.Create(path)
|
||||
return &failingWriteCloser{file: file, allowed: 100}, err
|
||||
}
|
||||
target := fetchTarget(t)
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(server.URL, infraUpdate.WithInsecureScheme(), infraUpdate.WithFileOpener(opener)).Fetch(assetOf(server, "binary", int64(len(payload))), target, noProgress)
|
||||
|
||||
if !errors.Is(err, errAssetDisk) {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
if _, statErr := os.Stat(target); !os.IsNotExist(statErr) {
|
||||
t.Error("the partial file must be removed")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestHTTPAssetFetcherProductionPolicy(t *testing.T) {
|
||||
payload := []byte("signed release asset")
|
||||
|
||||
t.Run("an http URL is refused", func(t *testing.T) {
|
||||
var requests atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
requests.Add(1)
|
||||
_, _ = w.Write(payload)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(server.URL).Fetch(assetOf(server, "binary", int64(len(payload))), fetchTarget(t), noProgress)
|
||||
|
||||
if err == nil || requests.Load() != 0 {
|
||||
t.Errorf("err = %v, requests = %d", err, requests.Load())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an https URL on another host is refused", func(t *testing.T) {
|
||||
var requests atomic.Int32
|
||||
other := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { requests.Add(1) }))
|
||||
defer other.Close()
|
||||
allowed := httptest.NewTLSServer(http.NotFoundHandler())
|
||||
defer allowed.Close()
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(allowed.URL, infraUpdate.WithTransport(other.Client().Transport)).Fetch(assetOf(other, "binary", 1), fetchTarget(t), noProgress)
|
||||
|
||||
if err == nil || requests.Load() != 0 {
|
||||
t.Errorf("err = %v, requests = %d", err, requests.Load())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a redirect to another host is refused", func(t *testing.T) {
|
||||
var reached atomic.Int32
|
||||
second := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
reached.Add(1)
|
||||
_, _ = w.Write(payload)
|
||||
}))
|
||||
defer second.Close()
|
||||
first := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, second.URL+"/binary", http.StatusFound)
|
||||
}))
|
||||
defer first.Close()
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(first.URL, infraUpdate.WithTransport(first.Client().Transport)).Fetch(assetOf(first, "binary", 1), fetchTarget(t), noProgress)
|
||||
|
||||
if err == nil || reached.Load() != 0 {
|
||||
t.Errorf("err = %v, second server reached %d times", err, reached.Load())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a redirect to http is refused", func(t *testing.T) {
|
||||
var reached atomic.Int32
|
||||
plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
reached.Add(1)
|
||||
_, _ = w.Write(payload)
|
||||
}))
|
||||
defer plain.Close()
|
||||
secure := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, strings.Replace(r.URL.Path, "/", plain.URL+"/", 1), http.StatusFound)
|
||||
}))
|
||||
defer secure.Close()
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(secure.URL, infraUpdate.WithTransport(secure.Client().Transport)).Fetch(assetOf(secure, "binary", 1), fetchTarget(t), noProgress)
|
||||
|
||||
if err == nil || reached.Load() != 0 {
|
||||
t.Errorf("err = %v, plain server reached %d times", err, reached.Load())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an https URL on the allowed host is accepted, also after a same host redirect", func(t *testing.T) {
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/binary" {
|
||||
http.Redirect(w, r, "/final", http.StatusFound)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(payload)
|
||||
}))
|
||||
defer server.Close()
|
||||
target := fetchTarget(t)
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(server.URL, infraUpdate.WithTransport(server.Client().Transport)).Fetch(assetOf(server, "binary", int64(len(payload))), target, noProgress)
|
||||
|
||||
written, _ := os.ReadFile(target)
|
||||
if err != nil || !bytes.Equal(written, payload) {
|
||||
t.Errorf("err = %v, body = %q", err, written)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestHTTPAssetFetcherBoundaries(t *testing.T) {
|
||||
exact := bytes.Repeat([]byte("x"), 100)
|
||||
|
||||
t.Run("a body exactly at the cap is accepted with a content length", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(exact) }))
|
||||
defer server.Close()
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(server.URL, infraUpdate.WithInsecureScheme(), infraUpdate.WithSizeCap(100)).Fetch(assetOf(server, "binary", 100), fetchTarget(t), noProgress)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a chunked body exactly at the cap is accepted", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Transfer-Encoding", "chunked")
|
||||
_, _ = w.Write(exact)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(server.URL, infraUpdate.WithInsecureScheme(), infraUpdate.WithSizeCap(100)).Fetch(assetOf(server, "binary", 100), fetchTarget(t), noProgress)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("checksums over 64 KiB are refused without a custom cap", func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write(bytes.Repeat([]byte("a"), 64<<10+1))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(server.URL, infraUpdate.WithInsecureScheme()).Fetch(assetOf(server, "checksums.txt", 0), fetchTarget(t), noProgress)
|
||||
|
||||
if err == nil {
|
||||
t.Error("65 KiB of checksums must exceed the cap")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("redirects are followed up to four hops and the fifth is refused", func(t *testing.T) {
|
||||
for _, hops := range []int{4, 5} {
|
||||
var served atomic.Int32
|
||||
var server *httptest.Server
|
||||
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if int(served.Add(1)) <= hops {
|
||||
http.Redirect(w, r, server.URL+"/next", http.StatusFound)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(exact)
|
||||
}))
|
||||
|
||||
err := infraUpdate.NewHTTPAssetFetcher(server.URL, infraUpdate.WithInsecureScheme()).Fetch(assetOf(server, "binary", 100), fetchTarget(t), noProgress)
|
||||
server.Close()
|
||||
|
||||
if hops == 4 && err != nil {
|
||||
t.Errorf("%d redirects: err = %v", hops, err)
|
||||
}
|
||||
if hops == 5 && err == nil {
|
||||
t.Errorf("%d redirects must be refused", hops)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func runBinary(t *testing.T, binary string, workDir string, args ...string) (string, string, int) {
|
||||
t.Helper()
|
||||
command := exec.Command(binary, args...)
|
||||
command.Dir = workDir
|
||||
command.Env = emptyEnvironment()
|
||||
var stdout, stderr bytes.Buffer
|
||||
command.Stdout, command.Stderr = &stdout, &stderr
|
||||
err := command.Run()
|
||||
code := 0
|
||||
if exitErr, ok := err.(*exec.ExitError); ok {
|
||||
code = exitErr.ExitCode()
|
||||
} else if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return stdout.String(), stderr.String(), code
|
||||
}
|
||||
|
||||
func assertEmptyDirectory(t *testing.T, directory string) {
|
||||
t.Helper()
|
||||
if entries, _ := os.ReadDir(directory); len(entries) != 0 {
|
||||
t.Errorf("the working directory must stay empty, got %d entries", len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandDispatcher(t *testing.T) {
|
||||
binary := buildServerBinary(t, "-X main.version=v9.9.9")
|
||||
|
||||
t.Run("--version prints the version and exits 0", func(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
|
||||
stdout, _, code := runBinary(t, binary, workDir, "--version")
|
||||
|
||||
if code != 0 || strings.TrimSpace(stdout) != "v9.9.9" {
|
||||
t.Errorf("code = %d, stdout = %q", code, stdout)
|
||||
}
|
||||
assertEmptyDirectory(t, workDir)
|
||||
})
|
||||
|
||||
t.Run("an unknown subcommand prints a usage message and does not start the server", func(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
|
||||
stdout, stderr, code := runBinary(t, binary, workDir, "frobnicate")
|
||||
|
||||
if code == 0 || !strings.Contains(stderr, "usage:") || stdout != "" {
|
||||
t.Errorf("code = %d, stdout = %q, stderr = %q", code, stdout, stderr)
|
||||
}
|
||||
assertEmptyDirectory(t, workDir)
|
||||
})
|
||||
|
||||
t.Run("apply-update runs without .env and creates no data directory", func(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
|
||||
_, stderr, code := runBinary(t, binary, workDir, "apply-update")
|
||||
|
||||
if code == 0 || strings.Contains(stderr, "PUBLIC_URL") || strings.Contains(stderr, ".env") {
|
||||
t.Errorf("code = %d, stderr = %q", code, stderr)
|
||||
}
|
||||
assertEmptyDirectory(t, workDir)
|
||||
})
|
||||
|
||||
t.Run("apply-update with its flags never reads .env or opens the database", func(t *testing.T) {
|
||||
if runtime.GOOS == "linux" {
|
||||
t.Skip("on Linux the helper would act on the machine")
|
||||
}
|
||||
workDir := t.TempDir()
|
||||
|
||||
_, stderr, _ := runBinary(t, binary, workDir, "apply-update", "--binary", filepath.Join(workDir, "bin"), "--data-dir", filepath.Join(workDir, "data"))
|
||||
|
||||
if strings.Contains(stderr, "PUBLIC_URL") {
|
||||
t.Errorf("stderr = %q", stderr)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(workDir, "data")); err == nil {
|
||||
t.Error("no data directory may be created")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("enable-browser-updates and disable-browser-updates refuse off Linux", func(t *testing.T) {
|
||||
if runtime.GOOS == "linux" {
|
||||
t.Skip("on Linux these commands would act on the machine's systemd")
|
||||
}
|
||||
workDir := t.TempDir()
|
||||
|
||||
_, stderr, code := runBinary(t, binary, workDir, "enable-browser-updates")
|
||||
stdout, _, disableCode := runBinary(t, binary, workDir, "disable-browser-updates")
|
||||
|
||||
if code == 0 || strings.TrimSpace(stderr) != update.ErrNeedsLinux.Error() {
|
||||
t.Errorf("enable: code = %d, stderr = %q", code, stderr)
|
||||
}
|
||||
if disableCode != 0 || !strings.Contains(stdout, "not enabled") {
|
||||
t.Errorf("disable: code = %d, stdout = %q", disableCode, stdout)
|
||||
}
|
||||
assertEmptyDirectory(t, workDir)
|
||||
})
|
||||
|
||||
t.Run("no arguments is the normal server start", func(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
|
||||
_, stderr, code := runBinary(t, binary, workDir)
|
||||
|
||||
if code == 0 || !strings.Contains(stderr, "PUBLIC_URL") {
|
||||
t.Errorf("code = %d, stderr = %q", code, stderr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func freeTCPPort(t *testing.T) string {
|
||||
t.Helper()
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
return fmt.Sprint(listener.Addr().(*net.TCPAddr).Port)
|
||||
}
|
||||
|
||||
func TestServerWritesRunningInfoBeforeServing(t *testing.T) {
|
||||
if os.Getenv("RENEWCMS_TEST_SPAWN_SERVER") == "" {
|
||||
t.Skip("spawns the real server, which triggers Windows firewall prompts; set RENEWCMS_TEST_SPAWN_SERVER=1 to run")
|
||||
}
|
||||
binary := buildServerBinary(t, "-X main.version=v9.9.9")
|
||||
workDir := t.TempDir()
|
||||
dataDir := filepath.Join(workDir, "data")
|
||||
port := freeTCPPort(t)
|
||||
command := exec.Command(binary)
|
||||
command.Dir = workDir
|
||||
command.Env = append(emptyEnvironment(),
|
||||
"ENVIRONMENT=development", "PORT="+port, "PUBLIC_URL=http://localhost", "JWT_SECRET=test-secret-for-dispatch",
|
||||
"SMTP_LOGIN=a@example.com", "SMTP_SENDER=a@example.com", "SMTP_PASSWORD=x", "SMTP_HOST=localhost", "SMTP_PORT=2525",
|
||||
"DB_FILE="+filepath.Join(dataDir, "renewcms.db"), "UPLOAD_DIR="+filepath.Join(dataDir, "uploads"),
|
||||
"UPDATE_FEED_URL=https://git.example")
|
||||
var stderr bytes.Buffer
|
||||
command.Stderr = &stderr
|
||||
started := time.Now()
|
||||
if err := command.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
_ = command.Process.Kill()
|
||||
_, _ = command.Process.Wait()
|
||||
}()
|
||||
|
||||
healthy := false
|
||||
for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
|
||||
response, err := http.Get("http://127.0.0.1:" + port + "/healthz")
|
||||
if err == nil {
|
||||
response.Body.Close()
|
||||
healthy = response.StatusCode == http.StatusOK
|
||||
if healthy {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if !healthy {
|
||||
t.Fatalf("the server never answered /healthz: %s", stderr.String())
|
||||
}
|
||||
|
||||
content, err := os.ReadFile(filepath.Join(dataDir, update.RunningInfoFileName))
|
||||
if err != nil {
|
||||
t.Fatalf("update-running.json must exist as soon as /healthz answers: %v", err)
|
||||
}
|
||||
var info update.RunningInfo
|
||||
if err := json.Unmarshal(content, &info); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Version != "v9.9.9" || info.Pid != command.Process.Pid || info.StartedAt.Before(started.Add(-2*time.Second)) || info.StartedAt.After(time.Now()) {
|
||||
t.Errorf("info = %+v, pid = %d", info, command.Process.Pid)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,704 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/api"
|
||||
"RenewCMS/api/middleware"
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
"RenewCMS/internal/domain/update"
|
||||
infraUpdate "RenewCMS/internal/infrastructure/update"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
)
|
||||
|
||||
const downloadPath = "/update/download"
|
||||
|
||||
func newDownloadHTTP(t *testing.T, rig *downloadRig) *updateHarness {
|
||||
t.Helper()
|
||||
validator.InitValidator()
|
||||
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||
users := newUpdateUserRepo()
|
||||
feed := &fakeReleaseFeed{}
|
||||
now := func() time.Time { return updateTestCheckedAt }
|
||||
container := &api.UseCases{
|
||||
Token: token,
|
||||
GetUserUseCase: useCases.NewGetUserUseCase(users),
|
||||
GetUpdateStatusUseCase: rig.status,
|
||||
CheckForUpdateUseCase: useCases.NewCheckForUpdateUseCase(feed, rig.store, updateRunning, now),
|
||||
StartUpdateDownloadUseCase: rig.start,
|
||||
}
|
||||
return &updateHarness{router: api.NewSystemRouter(container), token: token, feed: feed, store: rig.store}
|
||||
}
|
||||
|
||||
func waitForHTTPState(t *testing.T, h *updateHarness, states ...string) map[string]any {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
var body map[string]any
|
||||
for time.Now().Before(deadline) {
|
||||
body = decodeUpdateBody(t, h.sendAs(t, http.MethodGet, "/update", updateOwnerId))
|
||||
for _, state := range states {
|
||||
if body["state"] == state {
|
||||
return body
|
||||
}
|
||||
}
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("state never reached %v, last body %v", states, body)
|
||||
return nil
|
||||
}
|
||||
|
||||
type pausedDownload struct {
|
||||
reached chan struct{}
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func pauseBinaryAt(rig *downloadRig, done int64, total int64) *pausedDownload {
|
||||
pause := &pausedDownload{reached: make(chan struct{}), release: make(chan struct{})}
|
||||
var once sync.Once
|
||||
rig.fetcher.during = func(name string, report update.ProgressFunc) {
|
||||
if name != rig.assetName {
|
||||
return
|
||||
}
|
||||
once.Do(func() {
|
||||
report(done, total)
|
||||
close(pause.reached)
|
||||
})
|
||||
<-pause.release
|
||||
}
|
||||
return pause
|
||||
}
|
||||
|
||||
func newBoardSizedRig(t *testing.T) *downloadRig {
|
||||
t.Helper()
|
||||
return newDownloadRigFor(t, update.Platform{OS: "linux", Arch: "amd64"}, make([]byte, boardTotalBytes))
|
||||
}
|
||||
|
||||
func TestStartUpdateDownloadHTTP(t *testing.T) {
|
||||
t.Run("Start the update, happy path", func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
h := newDownloadHTTP(t, rig)
|
||||
gate := make(chan struct{})
|
||||
rig.fetcher.during = func(name string, _ update.ProgressFunc) {
|
||||
if name == rig.assetName {
|
||||
<-gate
|
||||
}
|
||||
}
|
||||
|
||||
rec := h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId)
|
||||
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
body := decodeUpdateBody(t, rec)
|
||||
assertUpdateKeys(t, body)
|
||||
if body["state"] != "downloading" || body["started_at"] == nil || body["error"] != nil || body["can_apply"] != true {
|
||||
t.Errorf("body = %v", body)
|
||||
}
|
||||
during := decodeUpdateBody(t, h.sendAs(t, http.MethodGet, "/update", updateOwnerId))
|
||||
progress, _ := during["progress"].(map[string]any)
|
||||
if during["state"] != "downloading" || progress == nil || progress["total_bytes"] != float64(len(rig.fetcher.files[rig.assetName])) {
|
||||
t.Errorf("during = %v", during)
|
||||
}
|
||||
close(gate)
|
||||
|
||||
ready := waitForHTTPState(t, h, "ready", "failed")
|
||||
|
||||
if ready["state"] != "ready" || ready["error"] != nil || ready["progress"] != nil || ready["latest"] != downloadTag {
|
||||
t.Fatalf("ready = %v, log: %s", ready, rig.logger.text())
|
||||
}
|
||||
for _, name := range []string{rig.assetName, "checksums.txt", "checksums.txt.sig"} {
|
||||
if _, err := os.Stat(filepath.Join(rig.updatesDir, downloadTag, name)); err != nil {
|
||||
t.Errorf("staged %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
if rig.backup.callCount() != 1 || rig.backup.seen[0] != update.StateVerifying {
|
||||
t.Errorf("backup calls = %d, state seen = %v", rig.backup.callCount(), rig.backup.seen)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(rig.dataDir, "renewcms.db")); err == nil {
|
||||
t.Error("the database file must not be touched")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Progress is reported in bytes", func(t *testing.T) {
|
||||
rig := newBoardSizedRig(t)
|
||||
h := newDownloadHTTP(t, rig)
|
||||
pause := pauseBinaryAt(rig, boardDoneBytes, boardTotalBytes)
|
||||
h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId)
|
||||
<-pause.reached
|
||||
|
||||
body := decodeUpdateBody(t, h.sendAs(t, http.MethodGet, "/update", updateAdminId))
|
||||
close(pause.release)
|
||||
waitForHTTPState(t, h, "ready", "failed")
|
||||
|
||||
progress, _ := body["progress"].(map[string]any)
|
||||
if body["state"] != "downloading" || progress == nil || progress["percent"] != float64(42) || progress["downloaded_bytes"] != float64(boardDoneBytes) || progress["total_bytes"] != float64(boardTotalBytes) {
|
||||
t.Errorf("body = %v", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Every owner sees the same job", func(t *testing.T) {
|
||||
rig := newBoardSizedRig(t)
|
||||
h := newDownloadHTTP(t, rig)
|
||||
pause := pauseBinaryAt(rig, boardDoneBytes, boardTotalBytes)
|
||||
h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId)
|
||||
<-pause.reached
|
||||
|
||||
owner := decodeUpdateBody(t, h.sendAs(t, http.MethodGet, "/update", updateSecondOwner))
|
||||
admin := decodeUpdateBody(t, h.sendAs(t, http.MethodGet, "/update", updateAdminId))
|
||||
close(pause.release)
|
||||
waitForHTTPState(t, h, "ready", "failed")
|
||||
|
||||
if owner["state"] != "downloading" || admin["state"] != "downloading" || owner["started_at"] != admin["started_at"] || owner["started_at"] == nil {
|
||||
t.Errorf("owner = %v admin = %v", owner, admin)
|
||||
}
|
||||
ownerProgress, _ := owner["progress"].(map[string]any)
|
||||
adminProgress, _ := admin["progress"].(map[string]any)
|
||||
if ownerProgress == nil || adminProgress == nil || ownerProgress["percent"] != adminProgress["percent"] || ownerProgress["downloaded_bytes"] != adminProgress["downloaded_bytes"] {
|
||||
t.Errorf("progress differs: %v vs %v", ownerProgress, adminProgress)
|
||||
}
|
||||
if owner["can_apply"] != true || admin["can_apply"] != false {
|
||||
t.Errorf("can_apply owner = %v admin = %v", owner["can_apply"], admin["can_apply"])
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Only the owner", func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
h := newDownloadHTTP(t, rig)
|
||||
|
||||
rec := h.sendAs(t, http.MethodPost, downloadPath, updateAdminId)
|
||||
|
||||
if rec.Code != http.StatusForbidden || rec.Body.String() != apperr.OwnerRequiredErrorMessage+"\n" {
|
||||
t.Errorf("status = %d body = %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, found := rig.jobs.Load(); found || rig.fetcher.totalCalls() != 0 {
|
||||
t.Error("no job may start and the fetcher must not be called")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("POST is guarded like the other system routes", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
userId uint32
|
||||
tokenVersion uint32
|
||||
status int
|
||||
}{
|
||||
{"no jwt cookie", 0, 0, http.StatusUnauthorized},
|
||||
{"a stale token version", updateOwnerId, 1, http.StatusUnauthorized},
|
||||
{"an unverified owner", updateUnverifiedOwner, 0, http.StatusForbidden},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
h := newDownloadHTTP(t, rig)
|
||||
|
||||
rec := h.send(t, http.MethodPost, downloadPath, c.userId, c.tokenVersion)
|
||||
|
||||
if rec.Code != c.status {
|
||||
t.Errorf("status = %d, want %d", rec.Code, c.status)
|
||||
}
|
||||
if _, found := rig.jobs.Load(); found || rig.fetcher.totalCalls() != 0 {
|
||||
t.Error("no job may start")
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Nothing to update", func(t *testing.T) {
|
||||
t.Run("available false", func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
rig.store.result.Latest = updateRunning
|
||||
h := newDownloadHTTP(t, rig)
|
||||
assertNothingStarted(t, rig, h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId), http.StatusBadRequest)
|
||||
})
|
||||
t.Run("no stored result", func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
rig.store.found = false
|
||||
h := newDownloadHTTP(t, rig)
|
||||
assertNothingStarted(t, rig, h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId), http.StatusBadRequest)
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("The server is not prepared", func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
rig.helper.installed = false
|
||||
h := newDownloadHTTP(t, rig)
|
||||
|
||||
assertNothingStarted(t, rig, h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId), http.StatusConflict)
|
||||
if body := decodeUpdateBody(t, h.sendAs(t, http.MethodGet, "/update", updateOwnerId)); body["can_apply"] != false {
|
||||
t.Errorf("can_apply = %v", body["can_apply"])
|
||||
}
|
||||
|
||||
rig.store.result.Latest = updateRunning
|
||||
assertNothingStarted(t, rig, h.sendAs(t, http.MethodPost, downloadPath, updateSecondOwner), http.StatusConflict)
|
||||
})
|
||||
|
||||
t.Run("A second start while a job exists", func(t *testing.T) {
|
||||
for _, state := range []string{update.StateDownloading, update.StateVerifying, update.StateReady} {
|
||||
t.Run(state, func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
existing := update.Job{Tag: downloadTag, State: state, StartedAt: time.Date(2026, 9, 30, 9, 0, 0, 0, time.UTC)}
|
||||
rig.jobs.put(existing)
|
||||
h := newDownloadHTTP(t, rig)
|
||||
|
||||
rec := h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId)
|
||||
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Errorf("status = %d", rec.Code)
|
||||
}
|
||||
if job, _ := rig.jobs.Load(); job != existing || rig.fetcher.totalCalls() != 0 {
|
||||
t.Errorf("the existing job was touched: %+v", job)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Two starts at once run one job", func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
h := newDownloadHTTP(t, rig)
|
||||
gate := make(chan struct{})
|
||||
rig.fetcher.during = func(name string, _ update.ProgressFunc) {
|
||||
if name == rig.assetName {
|
||||
<-gate
|
||||
}
|
||||
}
|
||||
codes := make(chan int, 2)
|
||||
var ready sync.WaitGroup
|
||||
ready.Add(2)
|
||||
for _, owner := range []uint32{updateOwnerId, updateSecondOwner} {
|
||||
go func() {
|
||||
ready.Done()
|
||||
ready.Wait()
|
||||
codes <- h.sendAs(t, http.MethodPost, downloadPath, owner).Code
|
||||
}()
|
||||
}
|
||||
first, second := <-codes, <-codes
|
||||
close(gate)
|
||||
waitForHTTPState(t, h, "ready", "failed")
|
||||
|
||||
accepted, conflicts := 0, 0
|
||||
for _, code := range []int{first, second} {
|
||||
switch code {
|
||||
case http.StatusAccepted:
|
||||
accepted++
|
||||
case http.StatusConflict:
|
||||
conflicts++
|
||||
}
|
||||
}
|
||||
if accepted != 1 || conflicts != 1 {
|
||||
t.Errorf("codes = %d and %d", first, second)
|
||||
}
|
||||
for _, name := range []string{rig.assetName, "checksums.txt", "checksums.txt.sig"} {
|
||||
if rig.fetcher.callsFor(name) != 1 {
|
||||
t.Errorf("%s fetched %d times", name, rig.fetcher.callsFor(name))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Try again after a failure", func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
failedAt := time.Date(2026, 9, 29, 8, 0, 0, 0, time.UTC)
|
||||
rig.jobs.put(update.Job{Tag: downloadTag, State: update.StateFailed, Error: update.ErrorKindDownload, StartedAt: failedAt})
|
||||
if err := os.MkdirAll(rig.stagedDir(), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stale := filepath.Join(rig.stagedDir(), "left-over")
|
||||
if err := os.WriteFile(stale, []byte("old"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := newDownloadHTTP(t, rig)
|
||||
|
||||
rec := h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId)
|
||||
|
||||
body := decodeUpdateBody(t, rec)
|
||||
if rec.Code != http.StatusAccepted || body["error"] != nil || body["started_at"] == "2026-09-29T08:00:00Z" || body["state"] != "downloading" {
|
||||
t.Fatalf("status = %d body = %v", rec.Code, body)
|
||||
}
|
||||
waitForHTTPState(t, h, "ready", "failed")
|
||||
if _, err := os.Stat(stale); !os.IsNotExist(err) {
|
||||
t.Error("the old staged files must be replaced")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Start is rate limited per user", func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
rig.helper.installed = false
|
||||
h := newDownloadHTTP(t, rig)
|
||||
authLimited := middleware.NewRateLimiter(5, time.Minute)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {}))
|
||||
|
||||
for attempt := 1; attempt <= 5; attempt++ {
|
||||
if rec := h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId); rec.Code != http.StatusConflict {
|
||||
t.Fatalf("attempt %d status = %d", attempt, rec.Code)
|
||||
}
|
||||
}
|
||||
rec := h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId)
|
||||
|
||||
retryAfter, err := strconv.Atoi(rec.Header().Get("Retry-After"))
|
||||
if rec.Code != http.StatusTooManyRequests || rec.Body.String() != apperr.TooManyRequestsErrorMessage+"\n" || err != nil || retryAfter < 1 {
|
||||
t.Errorf("status = %d body = %q retry-after = %q", rec.Code, rec.Body.String(), rec.Header().Get("Retry-After"))
|
||||
}
|
||||
if other := h.sendAs(t, http.MethodPost, downloadPath, updateSecondOwner); other.Code != http.StatusConflict {
|
||||
t.Errorf("another owner status = %d", other.Code)
|
||||
}
|
||||
for attempt := 1; attempt <= 5; attempt++ {
|
||||
if check := h.sendAs(t, http.MethodPost, "/update/check", updateOwnerId); check.Code != http.StatusOK {
|
||||
t.Errorf("check limiter was consumed: attempt %d status = %d", attempt, check.Code)
|
||||
}
|
||||
}
|
||||
for attempt := 1; attempt <= 5; attempt++ {
|
||||
recorder := httptest.NewRecorder()
|
||||
authLimited.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/login", nil))
|
||||
if recorder.Code != http.StatusOK {
|
||||
t.Errorf("auth limiter attempt %d status = %d", attempt, recorder.Code)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func assertNothingStarted(t *testing.T, rig *downloadRig, rec *httptest.ResponseRecorder, status int) {
|
||||
t.Helper()
|
||||
if rec.Code != status {
|
||||
t.Errorf("status = %d, want %d", rec.Code, status)
|
||||
}
|
||||
if _, found := rig.jobs.Load(); found || rig.fetcher.totalCalls() != 0 {
|
||||
t.Error("no job may start and the fetcher must not be called")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdatePreflightRefusalsHTTP(t *testing.T) {
|
||||
conditions := []struct {
|
||||
name string
|
||||
apply func(rig *downloadRig)
|
||||
}{
|
||||
{"no asset is named for the host platform", func(rig *downloadRig) { rig.dropAsset(rig.assetName) }},
|
||||
{"checksums.txt is missing from the assets", func(rig *downloadRig) { rig.dropAsset("checksums.txt") }},
|
||||
{"checksums.txt.sig is missing from the assets", func(rig *downloadRig) { rig.dropAsset("checksums.txt.sig") }},
|
||||
{"an asset URL is http, not https", func(rig *downloadRig) {
|
||||
rig.setAsset(rig.assetName, func(asset *update.Asset) { asset.URL = "http://git.example/dl/" + asset.Name })
|
||||
}},
|
||||
{"an asset URL is on a host other than UPDATE_FEED_URL's host", func(rig *downloadRig) {
|
||||
rig.setAsset("checksums.txt", func(asset *update.Asset) { asset.URL = "https://evil.example/dl/" + asset.Name })
|
||||
}},
|
||||
}
|
||||
for _, condition := range conditions {
|
||||
t.Run(condition.name, func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
condition.apply(rig)
|
||||
h := newDownloadHTTP(t, rig)
|
||||
|
||||
rec := h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId)
|
||||
|
||||
if rec.Code != http.StatusUnprocessableEntity || rec.Body.String() != apperr.UpdateRefusedErrorMessage+"\n" {
|
||||
t.Errorf("status = %d body = %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
for _, leak := range []string{"git.example", "evil.example", "renewcms_", "checksums"} {
|
||||
if strings.Contains(rec.Body.String(), leak) {
|
||||
t.Errorf("body leaks %q", leak)
|
||||
}
|
||||
}
|
||||
if _, found := rig.jobs.Load(); found || rig.fetcher.totalCalls() != 0 {
|
||||
t.Error("no job may start and the fetcher must not be called")
|
||||
}
|
||||
if !strings.Contains(rig.logger.text(), "refused") {
|
||||
t.Errorf("the reason must be logged, log: %q", rig.logger.text())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type jobFault struct {
|
||||
name string
|
||||
apply func(rig *downloadRig)
|
||||
logged string
|
||||
}
|
||||
|
||||
func runFaultTable(t *testing.T, wantError string, faults []jobFault) {
|
||||
t.Helper()
|
||||
for _, fault := range faults {
|
||||
t.Run(fault.name, func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
fault.apply(rig)
|
||||
h := newDownloadHTTP(t, rig)
|
||||
|
||||
post := h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId)
|
||||
if post.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d: %s", post.Code, post.Body.String())
|
||||
}
|
||||
rec := h.sendAs(t, http.MethodGet, "/update", updateOwnerId)
|
||||
body := waitForHTTPState(t, h, "failed", "ready")
|
||||
|
||||
if body["state"] != "failed" || body["error"] != wantError || body["progress"] != nil {
|
||||
t.Fatalf("body = %v, log: %s", body, rig.logger.text())
|
||||
}
|
||||
assertStagedDirGone(t, rig)
|
||||
if !strings.Contains(rig.logger.text(), fault.logged) {
|
||||
t.Errorf("log %q must contain %q", rig.logger.text(), fault.logged)
|
||||
}
|
||||
for _, response := range []string{post.Body.String(), rec.Body.String(), h.sendAs(t, http.MethodGet, "/update", updateOwnerId).Body.String()} {
|
||||
if strings.Contains(response, fault.logged) {
|
||||
t.Errorf("a response leaks %q", fault.logged)
|
||||
}
|
||||
}
|
||||
for _, state := range rig.jobs.states() {
|
||||
if state == update.StateReady {
|
||||
t.Error("a failed job must never have been ready")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateVerificationFailuresHTTP(t *testing.T) {
|
||||
runFaultTable(t, "verification", []jobFault{
|
||||
{"the binary was changed after signing (SHA-256 mismatch)", func(rig *downloadRig) {
|
||||
tampered := append([]byte(nil), rig.fetcher.files[rig.assetName]...)
|
||||
tampered[0] ^= 0xff
|
||||
rig.fetcher.files[rig.assetName] = tampered
|
||||
}, "sha-256 mismatch"},
|
||||
{"checksums.txt was changed after signing", func(rig *downloadRig) {
|
||||
tampered := []byte(strings.Replace(string(rig.fetcher.files["checksums.txt"]), "renewcms_", "renewcmz_", 1))
|
||||
rig.fetcher.files["checksums.txt"] = tampered
|
||||
}, "signature"},
|
||||
{"the signature is from a different key", func(rig *downloadRig) {
|
||||
_, other, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rig.signChecksums(string(rig.fetcher.files["checksums.txt"]), other)
|
||||
}, "does not match"},
|
||||
{"checksums.txt has no line for the asset", func(rig *downloadRig) {
|
||||
rig.signChecksums(rig.checksumsFor("renewcms_other_file", []byte("x")), rig.privateKey)
|
||||
rig.refreshAssetSizes()
|
||||
}, "has no line"},
|
||||
{"the staged binary prints v2.2.9-beta for --version", func(rig *downloadRig) {
|
||||
rig.runner.output = "v2.2.9-beta"
|
||||
}, "v2.2.9-beta"},
|
||||
{"the staged checksums cannot be read back", func(rig *downloadRig) {
|
||||
rig.staging.readErr = errDownloadDisk
|
||||
}, "no space left on device"},
|
||||
{"the staged binary cannot be made executable", func(rig *downloadRig) {
|
||||
rig.staging.chmodErr = errDownloadChmod
|
||||
}, "operation not permitted"},
|
||||
{"the staged binary cannot be run", func(rig *downloadRig) {
|
||||
rig.runner.err = errDownloadRunnerFail
|
||||
}, "exec format error"},
|
||||
})
|
||||
}
|
||||
|
||||
func TestUpdateDownloadFailuresHTTP(t *testing.T) {
|
||||
runFaultTable(t, "download", []jobFault{
|
||||
{"the connection drops after half the bytes (truncated download)", func(rig *downloadRig) {
|
||||
rig.fetcher.errors[rig.assetName] = errDownloadNetwork
|
||||
rig.fetcher.partial[rig.assetName] = true
|
||||
}, "connection reset by peer"},
|
||||
{"the bytes received differ from the size the release declares", func(rig *downloadRig) {
|
||||
rig.setAsset(rig.assetName, func(asset *update.Asset) { asset.Size += 7 })
|
||||
}, "the release declares"},
|
||||
{"a file exceeds its size cap", func(rig *downloadRig) {
|
||||
rig.fetcher.errors["checksums.txt"] = errDownloadTooLarge
|
||||
}, "size cap"},
|
||||
{"the download passes the overall timeout", func(rig *downloadRig) {
|
||||
rig.fetcher.errors[rig.assetName] = context.DeadlineExceeded
|
||||
}, "deadline exceeded"},
|
||||
{"the feed host answers 404 or 500 for an asset", func(rig *downloadRig) {
|
||||
rig.fetcher.errors["checksums.txt.sig"] = errAssetStatusNotFound
|
||||
}, "answered 404"},
|
||||
{"the updates directory cannot be created or written (disk error)", func(rig *downloadRig) {
|
||||
if err := os.WriteFile(rig.updatesDir, []byte("a file where the directory should be"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}, "updates"},
|
||||
{"the staging directory cannot be prepared (injected)", func(rig *downloadRig) {
|
||||
rig.staging.prepareErr = errDownloadDisk
|
||||
}, "no space left on device"},
|
||||
{"a staged file cannot be measured", func(rig *downloadRig) {
|
||||
rig.staging.sizeErr = errDownloadStat
|
||||
}, "stat failed"},
|
||||
{"the disk fills during the write", func(rig *downloadRig) {
|
||||
rig.fetcher.errors[rig.assetName] = errDownloadDisk
|
||||
rig.fetcher.partial[rig.assetName] = true
|
||||
}, "no space left on device"},
|
||||
{"the database backup fails", func(rig *downloadRig) {
|
||||
rig.backup.err = errDownloadBackup
|
||||
}, "vacuum into failed"},
|
||||
})
|
||||
}
|
||||
|
||||
func TestUpdateBackupBeforeReadyHTTP(t *testing.T) {
|
||||
t.Run("The backup comes before ready, and the last 3 are kept", func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
backups := filepath.Join(rig.dataDir, "backups")
|
||||
if err := os.MkdirAll(backups, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for index, name := range []string{"earlier-1.db", "earlier-2.db", "earlier-3.db"} {
|
||||
path := filepath.Join(backups, name)
|
||||
if err := os.WriteFile(path, []byte("older copy"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
backdate(t, path, time.Duration(10-index)*time.Hour)
|
||||
}
|
||||
rig.realBackup = infraUpdate.NewSQLiteDatabaseBackup(newBackupTestDatabase(t), backups, time.Now)
|
||||
rig.rebuild()
|
||||
h := newDownloadHTTP(t, rig)
|
||||
|
||||
h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId)
|
||||
body := waitForHTTPState(t, h, "ready", "failed")
|
||||
|
||||
if body["state"] != "ready" {
|
||||
t.Fatalf("body = %v, log: %s", body, rig.logger.text())
|
||||
}
|
||||
entries, err := os.ReadDir(backups)
|
||||
if err != nil || len(entries) != 3 {
|
||||
t.Fatalf("backups = %d, err = %v", len(entries), err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(backups, "earlier-1.db")); !os.IsNotExist(err) {
|
||||
t.Error("the oldest backup must be deleted")
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if strings.HasPrefix(entry.Name(), "renewcms-") {
|
||||
if rows := countBackupRows(t, filepath.Join(backups, entry.Name())); rows != 2 {
|
||||
t.Errorf("rows in the new copy = %d, want 2", rows)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a failed backup leaves state failed and does not prune", func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
rig.backup.err = errDownloadBackup
|
||||
h := newDownloadHTTP(t, rig)
|
||||
|
||||
h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId)
|
||||
body := waitForHTTPState(t, h, "ready", "failed")
|
||||
|
||||
if body["state"] != "failed" || body["error"] != "download" {
|
||||
t.Errorf("body = %v", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestFailedUpdateJobRemovesItsStagedDirectoryEvenWhenRemovalFails(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
rig.fetcher.errors[rig.assetName] = errDownloadNetwork
|
||||
rig.staging.removeErr = errDownloadDisk
|
||||
|
||||
if _, err := rig.start.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
job := rig.waitForJob(update.StateFailed)
|
||||
|
||||
if job.Error != update.ErrorKindDownload || job.StagedBinary != "" {
|
||||
t.Errorf("job = %+v", job)
|
||||
}
|
||||
if got := rig.staging.removed(); len(got) != 1 || got[0] != downloadTag {
|
||||
t.Errorf("removed tags = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOSStagingArea(t *testing.T) {
|
||||
root := filepath.Join(t.TempDir(), "updates")
|
||||
area := infraUpdate.NewOSStagingArea(root)
|
||||
|
||||
t.Run("paths are rooted under the tag", func(t *testing.T) {
|
||||
if got, want := area.PathFor("v1", "a.bin"), filepath.Join(root, "v1", "a.bin"); got != want {
|
||||
t.Errorf("path = %q, want %q", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("prepare empties and recreates the directory", func(t *testing.T) {
|
||||
if err := area.Prepare("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stale := area.PathFor("v1", "stale")
|
||||
if err := os.WriteFile(stale, []byte("old"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := area.Prepare("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(stale); !os.IsNotExist(err) {
|
||||
t.Errorf("stale file survived: %v", err)
|
||||
}
|
||||
if info, err := os.Stat(filepath.Join(root, "v1")); err != nil || !info.IsDir() {
|
||||
t.Errorf("directory missing: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("size and checksums read the staged file", func(t *testing.T) {
|
||||
path := area.PathFor("v1", "checksums.txt")
|
||||
if err := os.WriteFile(path, []byte("abc"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if size, err := area.Size(path); err != nil || size != 3 {
|
||||
t.Errorf("size = %d, err = %v", size, err)
|
||||
}
|
||||
if content, err := area.ReadChecksums(path); err != nil || content != "abc" {
|
||||
t.Errorf("content = %q, err = %v", content, err)
|
||||
}
|
||||
missing := area.PathFor("v1", "missing")
|
||||
if _, err := area.Size(missing); err == nil {
|
||||
t.Error("size of a missing file must fail")
|
||||
}
|
||||
if _, err := area.ReadChecksums(missing); err == nil {
|
||||
t.Error("reading a missing file must fail")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("make executable sets the mode and fails on a missing file", func(t *testing.T) {
|
||||
path := area.PathFor("v1", "binary")
|
||||
if err := os.WriteFile(path, []byte("x"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := area.MakeExecutable(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || info.Mode().Perm() != 0o755 {
|
||||
t.Errorf("mode = %v, err = %v", info.Mode(), err)
|
||||
}
|
||||
}
|
||||
if err := area.MakeExecutable(area.PathFor("v1", "missing")); err == nil {
|
||||
t.Error("a missing file must fail")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("remove deletes the tag directory only", func(t *testing.T) {
|
||||
if err := area.Prepare("v2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := area.Remove("v1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, "v1")); !os.IsNotExist(err) {
|
||||
t.Errorf("v1 still exists: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, "v2")); err != nil {
|
||||
t.Errorf("v2 must remain: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("prepare fails when a file sits where the root should be", func(t *testing.T) {
|
||||
blocked := filepath.Join(t.TempDir(), "updates")
|
||||
if err := os.WriteFile(blocked, []byte("file"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := infraUpdate.NewOSStagingArea(blocked).Prepare("v1"); err == nil {
|
||||
t.Error("prepare must fail")
|
||||
}
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,183 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
infraUpdate "RenewCMS/internal/infrastructure/update"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const giteaReleasesPath = "/api/v1/repos/fsylvain/RenewCMS/releases"
|
||||
|
||||
func newGiteaFeedServer(t *testing.T, status int, body string) (*httptest.Server, *[]string) {
|
||||
t.Helper()
|
||||
var paths []string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
paths = append(paths, r.URL.Path)
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server, &paths
|
||||
}
|
||||
|
||||
func TestGiteaReleaseFeed(t *testing.T) {
|
||||
list := `[
|
||||
{"tag_name":"v2.4.0-beta","html_url":"https://git.example/r/v2.4.0-beta","body":"- Four","draft":false,"prerelease":true,"published_at":"2026-08-01T10:00:00Z"},
|
||||
{"tag_name":"v9.0.0","html_url":"https://git.example/r/v9.0.0","body":"- Draft","draft":true,"prerelease":false,"published_at":"2026-09-30T10:00:00Z"},
|
||||
{"tag_name":"v2.5.0-beta","html_url":"https://git.example/r/v2.5.0-beta","body":"## New\n- **Media** library\n- Fixed [caching](http://x) bug","draft":false,"prerelease":true,"published_at":"2026-09-24T08:30:00Z"},
|
||||
{"tag_name":"v2.3.0-beta","html_url":"https://git.example/r/v2.3.0-beta","body":"","draft":false,"prerelease":true,"published_at":"2026-07-01T10:00:00Z"}
|
||||
]`
|
||||
|
||||
t.Run("requests the release list and returns the newest published release", func(t *testing.T) {
|
||||
server, paths := newGiteaFeedServer(t, http.StatusOK, list)
|
||||
|
||||
release, err := infraUpdate.NewGiteaReleaseFeed(server.URL + "/").Latest()
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("Latest: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(*paths, []string{giteaReleasesPath}) {
|
||||
t.Errorf("paths = %v", *paths)
|
||||
}
|
||||
if release.Tag != "v2.5.0-beta" || release.URL != "https://git.example/r/v2.5.0-beta" {
|
||||
t.Errorf("release = %+v", release)
|
||||
}
|
||||
if want := []string{"Media library", "Fixed caching bug"}; !reflect.DeepEqual(release.Notes.Items, want) {
|
||||
t.Errorf("items = %v", release.Notes.Items)
|
||||
}
|
||||
if want := time.Date(2026, 9, 24, 8, 30, 0, 0, time.UTC); !release.PublishedAt.Equal(want) || !release.Notes.ReleasedAt.Equal(want) {
|
||||
t.Errorf("published = %v, notes released = %v", release.PublishedAt, release.Notes.ReleasedAt)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a final release beats a beta of the same number", func(t *testing.T) {
|
||||
server, _ := newGiteaFeedServer(t, http.StatusOK, `[{"tag_name":"v2.6.0-beta","published_at":"2026-09-01T00:00:00Z"},{"tag_name":"v2.6.0","published_at":"2026-09-02T00:00:00Z"}]`)
|
||||
release, err := infraUpdate.NewGiteaReleaseFeed(server.URL).Latest()
|
||||
if err != nil || release.Tag != "v2.6.0" {
|
||||
t.Errorf("release = %+v, err = %v", release, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("only drafts is no release", func(t *testing.T) {
|
||||
server, _ := newGiteaFeedServer(t, http.StatusOK, `[{"tag_name":"v9.0.0","draft":true}]`)
|
||||
if _, err := infraUpdate.NewGiteaReleaseFeed(server.URL).Latest(); !errors.Is(err, update.ErrNoRelease) {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a 500 is a feed error", func(t *testing.T) {
|
||||
server, _ := newGiteaFeedServer(t, http.StatusInternalServerError, "boom")
|
||||
if _, err := infraUpdate.NewGiteaReleaseFeed(server.URL).Latest(); !errors.Is(err, update.ErrFeedUnavailable) {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid json is a feed error", func(t *testing.T) {
|
||||
server, _ := newGiteaFeedServer(t, http.StatusOK, "not json")
|
||||
if _, err := infraUpdate.NewGiteaReleaseFeed(server.URL).Latest(); !errors.Is(err, update.ErrFeedUnavailable) {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an unreachable server is a feed error", func(t *testing.T) {
|
||||
server, _ := newGiteaFeedServer(t, http.StatusOK, "[]")
|
||||
url := server.URL
|
||||
server.Close()
|
||||
if _, err := infraUpdate.NewGiteaReleaseFeed(url).Latest(); !errors.Is(err, update.ErrFeedUnavailable) {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestJSONStatusStore(t *testing.T) {
|
||||
t.Run("The stored result survives a restart", func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "data", "update-status.json")
|
||||
saved := newStoredUpdateResult()
|
||||
if err := infraUpdate.NewJSONStatusStore(path).Save(saved); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
loaded, found := infraUpdate.NewJSONStatusStore(path).Load()
|
||||
|
||||
if !found {
|
||||
t.Fatal("expected a stored result")
|
||||
}
|
||||
if loaded.Latest != saved.Latest || loaded.ReleaseURL != saved.ReleaseURL || !loaded.CheckedAt.Equal(saved.CheckedAt) {
|
||||
t.Errorf("loaded = %+v", loaded)
|
||||
}
|
||||
if !reflect.DeepEqual(loaded.Notes.Items, saved.Notes.Items) {
|
||||
t.Errorf("items = %v", loaded.Notes.Items)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a second save replaces the first", func(t *testing.T) {
|
||||
store := infraUpdate.NewJSONStatusStore(filepath.Join(t.TempDir(), "update-status.json"))
|
||||
first := newStoredUpdateResult()
|
||||
second := newStoredUpdateResult()
|
||||
second.Latest = "v2.4.0-beta"
|
||||
_ = store.Save(first)
|
||||
_ = store.Save(second)
|
||||
if loaded, _ := store.Load(); loaded.Latest != "v2.4.0-beta" {
|
||||
t.Errorf("latest = %q", loaded.Latest)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a missing file reads as no result", func(t *testing.T) {
|
||||
if _, found := infraUpdate.NewJSONStatusStore(filepath.Join(t.TempDir(), "absent.json")).Load(); found {
|
||||
t.Error("a missing file must read as no result")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a corrupt file reads as no result", func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "update-status.json")
|
||||
if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, found := infraUpdate.NewJSONStatusStore(path).Load(); found {
|
||||
t.Error("a corrupt file must read as no result")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an unwritable location is an error", func(t *testing.T) {
|
||||
blocker := filepath.Join(t.TempDir(), "file")
|
||||
if err := os.WriteFile(blocker, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := infraUpdate.NewJSONStatusStore(filepath.Join(blocker, "update-status.json")).Save(newStoredUpdateResult()); err == nil {
|
||||
t.Error("expected an error")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCommittedReleasePublicKeyHasTheRightShape(t *testing.T) {
|
||||
content, err := os.ReadFile(filepath.Join("..", "internal", "infrastructure", "update", "release.pub"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(content)))
|
||||
if err != nil || len(decoded) != ed25519.PublicKeySize {
|
||||
t.Fatalf("release.pub must be base64 of %d bytes: %v", ed25519.PublicKeySize, err)
|
||||
}
|
||||
if _, err := infraUpdate.EmbeddedPublicKey(); err != nil {
|
||||
t.Errorf("embedded key: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaReleaseFeedRejectsAnOversizedBody(t *testing.T) {
|
||||
huge := `[{"tag_name":"v2.5.0","html_url":"u","body":"` + strings.Repeat("a", 5<<20) + `","draft":false,"published_at":"2026-09-24T08:30:00Z"}]`
|
||||
server, _ := newGiteaFeedServer(t, http.StatusOK, huge)
|
||||
|
||||
if _, err := infraUpdate.NewGiteaReleaseFeed(server.URL).Latest(); !errors.Is(err, update.ErrFeedUnavailable) {
|
||||
t.Fatalf("Latest error = %v, want ErrFeedUnavailable", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
infraUpdate "RenewCMS/internal/infrastructure/update"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRestartRequestJSONStore(t *testing.T) {
|
||||
t.Run("it round trips and replaces atomically", func(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
path := filepath.Join(directory, update.RestartRequestFileName)
|
||||
store := infraUpdate.NewJSONRestartRequestStore(path)
|
||||
if _, err := store.Read(); !errors.Is(err, update.ErrNoRestartRequest) {
|
||||
t.Fatalf("an absent marker = %v", err)
|
||||
}
|
||||
first := update.RestartRequest{Kind: "update", Tag: downloadTag, RequestedAt: restartBaseTime, RequestedBy: 7}
|
||||
second := update.RestartRequest{Kind: "restart", RequestedAt: restartBaseTime.Add(time.Minute), RequestedBy: 8}
|
||||
|
||||
if err := store.Write(first); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Write(second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := store.Read()
|
||||
if err != nil || got != second {
|
||||
t.Errorf("got = %+v, err = %v", got, err)
|
||||
}
|
||||
if entries, _ := os.ReadDir(directory); len(entries) != 1 {
|
||||
t.Errorf("no temporary file may remain, got %d entries", len(entries))
|
||||
}
|
||||
if err := store.Delete(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Delete(); err != nil {
|
||||
t.Errorf("deleting twice = %v", err)
|
||||
}
|
||||
if _, err := store.Read(); !errors.Is(err, update.ErrNoRestartRequest) {
|
||||
t.Errorf("after delete = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a corrupt marker still counts as present", func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), update.RestartRequestFileName)
|
||||
_ = os.WriteFile(path, []byte("{nope"), 0o600)
|
||||
|
||||
_, err := infraUpdate.NewJSONRestartRequestStore(path).Read()
|
||||
|
||||
if err == nil || errors.Is(err, update.ErrNoRestartRequest) {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestResultJSONStore(t *testing.T) {
|
||||
t.Run("it round trips, keeps null finished_at and ignores corrupt or unknown files", func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), update.ResultFileName)
|
||||
store := infraUpdate.NewJSONResultStore(path)
|
||||
if _, found := store.Read(); found {
|
||||
t.Fatal("absent file")
|
||||
}
|
||||
running := update.Result{Outcome: update.OutcomeRunning, Kind: "update", Tag: downloadTag, FromVersion: helperOld, StartedAt: restartBaseTime}
|
||||
|
||||
if err := store.Write(running); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, found := store.Read()
|
||||
if !found || got.Outcome != "running" || got.FinishedAt != nil || !got.StartedAt.Equal(restartBaseTime) {
|
||||
t.Errorf("got = %+v", got)
|
||||
}
|
||||
|
||||
for name, content := range map[string]string{"corrupt": "{nope", "unknown outcome": `{"outcome":"weird"}`, "empty": ""} {
|
||||
_ = os.WriteFile(path, []byte(content), 0o644)
|
||||
if _, found := store.Read(); found {
|
||||
t.Errorf("%s must count as no result", name)
|
||||
}
|
||||
}
|
||||
|
||||
_ = store.Write(running)
|
||||
if err := store.Delete(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, found := store.Read(); found {
|
||||
t.Error("deleted")
|
||||
}
|
||||
if err := store.Delete(); err != nil {
|
||||
t.Errorf("deleting twice = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRunningInfoJSONStore(t *testing.T) {
|
||||
t.Run("it round trips and rejects missing, corrupt and incomplete files", func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), update.RunningInfoFileName)
|
||||
store := infraUpdate.NewJSONRunningInfoStore(path)
|
||||
if _, found := store.Read(); found {
|
||||
t.Fatal("absent file")
|
||||
}
|
||||
info := update.RunningInfo{Version: downloadTag, Pid: 12, StartedAt: restartBaseTime}
|
||||
|
||||
if err := store.Write(info); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, found := store.Read(); !found || got != info {
|
||||
t.Errorf("got = %+v", got)
|
||||
}
|
||||
for name, content := range map[string]string{"corrupt": "{nope", "no pid": `{"version":"v1.0.0"}`, "no version": `{"pid":3}`} {
|
||||
_ = os.WriteFile(path, []byte(content), 0o644)
|
||||
if _, found := store.Read(); found {
|
||||
t.Errorf("%s must not be read as running info", name)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a symlink is never read", func(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
target := filepath.Join(directory, "target.json")
|
||||
_ = os.WriteFile(target, []byte(`{"version":"v9.9.9","pid":1,"started_at":"2026-09-30T09:50:00Z"}`), 0o644)
|
||||
link := filepath.Join(directory, update.RunningInfoFileName)
|
||||
if err := os.Symlink(target, link); err != nil {
|
||||
t.Skipf("symlinks are not available: %v", err)
|
||||
}
|
||||
|
||||
if _, found := infraUpdate.NewJSONRunningInfoStore(link).Read(); found {
|
||||
t.Error("a symlink must not count")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestHelperStatusFile(t *testing.T) {
|
||||
t.Run("it is written world readable so the app can detect it", func(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
writer := infraUpdate.NewJSONHelperStatusWriter()
|
||||
|
||||
err := writer.Write(directory, update.HelperStatus{Version: 1, Service: "renewcms", Binary: "/opt/renewcms/renewcms", DataDir: directory, InstalledAt: restartBaseTime})
|
||||
|
||||
path := filepath.Join(directory, update.HelperStatusFileName)
|
||||
if err != nil || !infraUpdate.NewFileHelperDetector(path).Installed() {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
if info, _ := os.Stat(path); info.Mode().Perm()&0o044 != 0o044 && filepath.Separator == '/' {
|
||||
t.Errorf("mode = %v", info.Mode())
|
||||
}
|
||||
removed, err := writer.Remove(directory)
|
||||
if err != nil || !removed {
|
||||
t.Errorf("removed = %v, err = %v", removed, err)
|
||||
}
|
||||
removed, err = writer.Remove(directory)
|
||||
if err != nil || removed {
|
||||
t.Errorf("a second removal = %v, %v", removed, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestServiceUnitParsing(t *testing.T) {
|
||||
t.Run("it reads the binary, the data directory and the environment file", func(t *testing.T) {
|
||||
unit := "[Service]\nUser=renewcms\nEnvironmentFile=/etc/renewcms/renewcms.env\nExecStart=/opt/renewcms/renewcms\nProtectSystem=strict\nReadWritePaths=/var/lib/renewcms\n"
|
||||
|
||||
got := infraUpdate.ParseServiceUnit(unit)
|
||||
|
||||
if got.BinaryPath != "/opt/renewcms/renewcms" || got.DataDir != "/var/lib/renewcms" || got.EnvironmentFile != "/etc/renewcms/renewcms.env" {
|
||||
t.Errorf("got = %+v", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("systemd prefixes are stripped", func(t *testing.T) {
|
||||
unit := "ExecStart=-@/opt/renewcms/renewcms --flag\nEnvironmentFile=-/etc/x.env\nReadWritePaths=-/var/lib/renewcms /other\n"
|
||||
|
||||
got := infraUpdate.ParseServiceUnit(unit)
|
||||
|
||||
if got.BinaryPath != "/opt/renewcms/renewcms" || got.EnvironmentFile != "/etc/x.env" || got.DataDir != "/var/lib/renewcms" {
|
||||
t.Errorf("got = %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNoFollowFilesystemExists(t *testing.T) {
|
||||
var files update.HelperFilesystem = infraUpdate.NewNoFollowFilesystem()
|
||||
if files == nil {
|
||||
t.Fatal("the adapter must compile on every platform")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
infraUpdate "RenewCMS/internal/infrastructure/update"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestApplyRefusesStagedEntriesThatAreNotRegularFiles(t *testing.T) {
|
||||
for _, name := range []string{helperAsset, update.ChecksumsAssetName, update.SignatureAssetName} {
|
||||
t.Run("a directory in place of "+name, func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
target := path.Join(helperStagedDir, name)
|
||||
rig.forget(target)
|
||||
rig.fs.putDir(target)
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil || rig.result().Outcome != update.OutcomeFailed {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
if !strings.Contains(rig.logger.text(), target+" is not a regular file") {
|
||||
t.Errorf("the refusal must name the entry: %s", rig.logger.text())
|
||||
}
|
||||
if rig.fs.operationCount("tempdir") != 0 {
|
||||
t.Error("nothing may be copied once a staged entry is refused")
|
||||
}
|
||||
rig.assertUntouched()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyKeepsThePreviousBinaryOrFails(t *testing.T) {
|
||||
t.Run("a failed rename of the previous-binary backup stops the install", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
rig.fs.failNth("rename", 2, errors.New("cross-device link"))
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil || rig.result().Outcome != update.OutcomeFailed || rig.service.restartCount() != 0 {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
rig.assertBinary("old")
|
||||
if rig.fs.exists(helperBinary+".previous") || rig.fs.exists(helperBinary+".previous.tmp") {
|
||||
t.Error("no backup file may be left behind")
|
||||
}
|
||||
if !strings.Contains(rig.logger.text(), "keeping the previous binary: ") {
|
||||
t.Errorf("log = %s", rig.logger.text())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a failed rename of the rollback restore is reported loudly", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
rig.service.failOn[1] = errors.New("restart failed")
|
||||
rig.fs.failNth("rename", 4, errors.New("input/output error"))
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err == nil || rig.result().Outcome != update.OutcomeFailed || rig.service.restartCount() != 1 {
|
||||
t.Errorf("err = %v, result = %+v, restarts = %d", err, rig.result(), rig.service.restartCount())
|
||||
}
|
||||
if !strings.Contains(rig.logger.text(), "the site may be down") || rig.fs.exists(helperBinary+".restore") {
|
||||
t.Errorf("log = %s", rig.logger.text())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestApplyRestartWindowBoundary(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
comesBack int
|
||||
wantOK bool
|
||||
}{
|
||||
{"the site back one second before the window ends counts", 59, true},
|
||||
{"the site back exactly when the window ends is too late", 60, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.markRestart()
|
||||
rig.service.onRestart = func(int) {}
|
||||
rig.clock.onSleep = func(sleeps int) {
|
||||
if sleeps == tc.comesBack {
|
||||
rig.running.set(update.RunningInfo{Version: helperOld, Pid: 300, StartedAt: rig.clock.Now().Add(time.Second)})
|
||||
}
|
||||
}
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if tc.wantOK && (err != nil || rig.result().Outcome != update.OutcomeSucceeded) {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
if !tc.wantOK && (err == nil || rig.result().Outcome != update.OutcomeFailed || rig.service.restartCount() != 1) {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyLogsOnlyRealFailures(t *testing.T) {
|
||||
t.Run("a clean update logs neither a write nor a removal failure", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
|
||||
if err := rig.apply(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, unwanted := range []string{"could not be written", "could not remove", "staged files left in place"} {
|
||||
if strings.Contains(rig.logger.text(), unwanted) {
|
||||
t.Errorf("unexpected log %q in %s", unwanted, rig.logger.text())
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a result that cannot be written is logged and does not stop the restart", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.markRestart()
|
||||
rig.fs.failNth("create", 1, errors.New("disk full"))
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil || rig.service.restartCount() != 1 {
|
||||
t.Errorf("err = %v, restarts = %d", err, rig.service.restartCount())
|
||||
}
|
||||
if !strings.Contains(rig.logger.text(), "update-result.json could not be written: disk full") {
|
||||
t.Errorf("log = %s", rig.logger.text())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a temp directory that cannot be removed is logged and the update still succeeds", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
rig.fs.failNth("removeall", 1, errors.New("device busy"))
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil || rig.result().Outcome != update.OutcomeSucceeded {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
if !strings.Contains(rig.logger.text(), "could not remove /tmp/renewcms-update-1: device busy") {
|
||||
t.Errorf("log = %s", rig.logger.text())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("staged files that are already gone at cleanup are not an error", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
rig.fs.after("removeall", 1, func(f *fakeHelperFS) {
|
||||
for name := range f.nodes {
|
||||
if name == helperStagedDir || strings.HasPrefix(name, helperStagedDir+"/") {
|
||||
delete(f.nodes, name)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil || rig.result().Outcome != update.OutcomeSucceeded {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
if strings.Contains(rig.logger.text(), "could not remove") || strings.Contains(rig.logger.text(), "staged files left in place") {
|
||||
t.Errorf("log = %s", rig.logger.text())
|
||||
}
|
||||
if rig.fs.operationCount("removeall") != 1 {
|
||||
t.Errorf("removeall calls = %d, a missing staged directory needs none", rig.fs.operationCount("removeall"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestEnableAndDisableBrowserUpdatesEdges(t *testing.T) {
|
||||
t.Run("a binary given by flag still needs a data directory or a known service", func(t *testing.T) {
|
||||
rig := newInstallRig()
|
||||
rig.locator.found = false
|
||||
rig.locator.description = update.ServiceDescription{}
|
||||
|
||||
_, err := rig.enable.Enable(update.InstallOptions{Binary: "/opt/cms/renewcms"})
|
||||
|
||||
if !errors.Is(err, update.ErrServiceNotFound) || len(rig.events) != 0 {
|
||||
t.Errorf("err = %v, events = %v", err, rig.events)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("every flag given makes an unknown service installable", func(t *testing.T) {
|
||||
rig := newInstallRig()
|
||||
rig.locator.found = false
|
||||
rig.locator.description = update.ServiceDescription{}
|
||||
|
||||
_, err := rig.enable.Enable(update.InstallOptions{Binary: "/opt/cms/renewcms", DataDir: "/srv/cms", Port: "8081"})
|
||||
|
||||
if err != nil || len(rig.units.units) != 2 {
|
||||
t.Errorf("err = %v, units = %v", err, rig.units.units)
|
||||
}
|
||||
if _, found := rig.status.status["/srv/cms"]; !found {
|
||||
t.Error("the status file goes to the data directory given by flag")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the port is accepted from 1 to 65535 and refused outside it", func(t *testing.T) {
|
||||
for port, valid := range map[string]bool{"1": true, "65535": true, "0": false, "65536": false, "-1": false, "80a": false} {
|
||||
rig := newInstallRig()
|
||||
|
||||
_, err := rig.enable.Enable(update.InstallOptions{Port: port})
|
||||
|
||||
if valid && err != nil {
|
||||
t.Errorf("port %q: %v", port, err)
|
||||
}
|
||||
if !valid && !errors.Is(err, update.ErrInvalidPort) {
|
||||
t.Errorf("port %q: err = %v", port, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("disable with the units present but no status file still disables", func(t *testing.T) {
|
||||
rig := newInstallRig()
|
||||
if _, err := rig.enable.Enable(update.InstallOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
delete(rig.status.status, "/var/lib/renewcms")
|
||||
rig.events = nil
|
||||
|
||||
message, err := rig.disable.Disable(update.InstallOptions{})
|
||||
|
||||
if err != nil || strings.Contains(message, "not enabled") || len(rig.units.units) != 0 {
|
||||
t.Errorf("message = %q, err = %v, units = %v", message, err, rig.units.units)
|
||||
}
|
||||
assertInOrder(t, rig.events, "disable "+update.PathUnitName, "daemon-reload")
|
||||
})
|
||||
|
||||
t.Run("disable with a status file but no units still disables", func(t *testing.T) {
|
||||
rig := newInstallRig()
|
||||
if _, err := rig.enable.Enable(update.InstallOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rig.units.units = map[string]string{}
|
||||
rig.events = nil
|
||||
|
||||
message, err := rig.disable.Disable(update.InstallOptions{})
|
||||
|
||||
if err != nil || strings.Contains(message, "not enabled") || len(rig.status.status) != 0 {
|
||||
t.Errorf("message = %q, err = %v", message, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestFSStoresReportRealFailures(t *testing.T) {
|
||||
stores := map[string]func(files *fakeHelperFS) (write func() error, remove func() error){
|
||||
"the result store": func(files *fakeHelperFS) (func() error, func() error) {
|
||||
store := infraUpdate.NewFSResultStore(files, helperResult)
|
||||
return func() error {
|
||||
return store.Write(update.Result{Outcome: update.OutcomeFailed, StartedAt: restartBaseTime})
|
||||
}, store.Delete
|
||||
},
|
||||
"the restart request store": func(files *fakeHelperFS) (func() error, func() error) {
|
||||
store := infraUpdate.NewFSRestartRequestStore(files, helperMarker)
|
||||
return func() error {
|
||||
return store.Write(update.RestartRequest{Kind: update.RestartKindRestart, RequestedAt: restartBaseTime})
|
||||
}, store.Delete
|
||||
},
|
||||
}
|
||||
for name, build := range stores {
|
||||
t.Run(name+": deleting a file that is not there is fine", func(t *testing.T) {
|
||||
files := newFakeHelperFS()
|
||||
files.putDir(helperData)
|
||||
_, remove := build(files)
|
||||
|
||||
if err := remove(); err != nil {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run(name+": a delete that fails for another reason is returned", func(t *testing.T) {
|
||||
files := newFakeHelperFS()
|
||||
files.putDir(helperData)
|
||||
files.failNth("remove", 1, errors.New("read-only file system"))
|
||||
_, remove := build(files)
|
||||
|
||||
if err := remove(); err == nil || err.Error() != "read-only file system" {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run(name+": a failed rename is returned and the temp file is removed", func(t *testing.T) {
|
||||
files := newFakeHelperFS()
|
||||
files.putDir(helperData)
|
||||
files.failNth("rename", 1, errors.New("cross-device link"))
|
||||
write, _ := build(files)
|
||||
|
||||
err := write()
|
||||
|
||||
if err == nil || err.Error() != "cross-device link" {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
for node := range files.nodes {
|
||||
if strings.HasSuffix(node, ".tmp") {
|
||||
t.Errorf("the temp file %s must be removed", node)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run(name+": a stale temp file that cannot be removed fails the write", func(t *testing.T) {
|
||||
files := newFakeHelperFS()
|
||||
files.putDir(helperData)
|
||||
files.putFile(helperMarker+".tmp", "stale")
|
||||
files.putFile(helperResult+".tmp", "stale")
|
||||
files.failNth("remove", 1, errors.New("operation not permitted"))
|
||||
write, _ := build(files)
|
||||
|
||||
err := write()
|
||||
|
||||
if err == nil || err.Error() != "operation not permitted" || files.operationCount("create") != 0 {
|
||||
t.Errorf("err = %v, creates = %d", err, files.operationCount("create"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPHealthChecker(t *testing.T) {
|
||||
serve := func(status int) (string, func()) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/healthz" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
}))
|
||||
return strings.TrimPrefix(server.URL, "http://127.0.0.1:"), server.Close
|
||||
}
|
||||
|
||||
t.Run("a 200 answer on /healthz is healthy", func(t *testing.T) {
|
||||
port, stop := serve(http.StatusOK)
|
||||
defer stop()
|
||||
|
||||
if !infraUpdate.NewHTTPHealthChecker(port).Healthy() {
|
||||
t.Error("a 200 must be healthy")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("any other status is not healthy", func(t *testing.T) {
|
||||
for _, status := range []int{http.StatusNoContent, http.StatusInternalServerError, http.StatusServiceUnavailable} {
|
||||
port, stop := serve(status)
|
||||
|
||||
healthy := infraUpdate.NewHTTPHealthChecker(port).Healthy()
|
||||
stop()
|
||||
|
||||
if healthy {
|
||||
t.Errorf("status %d must not be healthy", status)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("nothing listening is not healthy", func(t *testing.T) {
|
||||
port, stop := serve(http.StatusOK)
|
||||
stop()
|
||||
|
||||
if infraUpdate.NewHTTPHealthChecker(port).Healthy() {
|
||||
t.Error("a closed port must not be healthy")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSystemMachineProbe(t *testing.T) {
|
||||
probe := infraUpdate.NewSystemMachineProbe()
|
||||
|
||||
t.Run("it reports the real OS and effective user", func(t *testing.T) {
|
||||
if probe.OS() != runtime.GOOS {
|
||||
t.Errorf("OS = %q, want %q", probe.OS(), runtime.GOOS)
|
||||
}
|
||||
if probe.IsRoot() != (os.Geteuid() == 0) {
|
||||
t.Errorf("IsRoot = %v, euid = %d", probe.IsRoot(), os.Geteuid())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("it reports systemd only where its runtime directory exists", func(t *testing.T) {
|
||||
info, err := os.Stat("/run/systemd/system")
|
||||
want := err == nil && info.IsDir()
|
||||
|
||||
if probe.SystemdRunning() != want {
|
||||
t.Errorf("SystemdRunning = %v, want %v", probe.SystemdRunning(), want)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
infraUpdate "RenewCMS/internal/infrastructure/update"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type fakeMachineProbe struct {
|
||||
os string
|
||||
systemd bool
|
||||
root bool
|
||||
}
|
||||
|
||||
var _ update.MachineProbe = &fakeMachineProbe{}
|
||||
|
||||
func (f *fakeMachineProbe) OS() string { return f.os }
|
||||
func (f *fakeMachineProbe) SystemdRunning() bool { return f.systemd }
|
||||
func (f *fakeMachineProbe) IsRoot() bool { return f.root }
|
||||
|
||||
type fakeServiceLocator struct {
|
||||
description update.ServiceDescription
|
||||
found bool
|
||||
port string
|
||||
hasPort bool
|
||||
}
|
||||
|
||||
var _ update.ServiceLocator = &fakeServiceLocator{}
|
||||
|
||||
func (f *fakeServiceLocator) Locate(name string) (update.ServiceDescription, bool) {
|
||||
description := f.description
|
||||
description.Name = name
|
||||
return description, f.found
|
||||
}
|
||||
|
||||
func (f *fakeServiceLocator) PortFromEnvironmentFile(string) (string, bool) {
|
||||
return f.port, f.hasPort
|
||||
}
|
||||
|
||||
type fakeUnitWriter struct {
|
||||
units map[string]string
|
||||
writes int
|
||||
failNth int
|
||||
events *[]string
|
||||
}
|
||||
|
||||
var _ update.UnitWriter = &fakeUnitWriter{}
|
||||
|
||||
func (f *fakeUnitWriter) Write(name string, content string) error {
|
||||
f.writes++
|
||||
*f.events = append(*f.events, "write "+name)
|
||||
if f.failNth == f.writes {
|
||||
return errors.New("disk full")
|
||||
}
|
||||
f.units[name] = content
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeUnitWriter) Remove(name string) (bool, error) {
|
||||
_, existed := f.units[name]
|
||||
delete(f.units, name)
|
||||
*f.events = append(*f.events, "remove "+name)
|
||||
return existed, nil
|
||||
}
|
||||
|
||||
type fakeUnitManager struct {
|
||||
reloadErr error
|
||||
enableErr error
|
||||
events *[]string
|
||||
}
|
||||
|
||||
var _ update.UnitManager = &fakeUnitManager{}
|
||||
|
||||
func (f *fakeUnitManager) DaemonReload() error {
|
||||
*f.events = append(*f.events, "daemon-reload")
|
||||
return f.reloadErr
|
||||
}
|
||||
|
||||
func (f *fakeUnitManager) EnableNow(unit string) error {
|
||||
*f.events = append(*f.events, "enable "+unit)
|
||||
return f.enableErr
|
||||
}
|
||||
|
||||
func (f *fakeUnitManager) DisableNow(unit string) error {
|
||||
*f.events = append(*f.events, "disable "+unit)
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeHelperStatusWriter struct {
|
||||
status map[string]update.HelperStatus
|
||||
events *[]string
|
||||
}
|
||||
|
||||
var _ update.HelperStatusWriter = &fakeHelperStatusWriter{}
|
||||
|
||||
func (f *fakeHelperStatusWriter) Write(dataDir string, status update.HelperStatus) error {
|
||||
*f.events = append(*f.events, "status")
|
||||
f.status[dataDir] = status
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeHelperStatusWriter) Remove(dataDir string) (bool, error) {
|
||||
_, existed := f.status[dataDir]
|
||||
delete(f.status, dataDir)
|
||||
*f.events = append(*f.events, "status-removed")
|
||||
return existed, nil
|
||||
}
|
||||
|
||||
type installRig struct {
|
||||
probe *fakeMachineProbe
|
||||
locator *fakeServiceLocator
|
||||
units *fakeUnitWriter
|
||||
manager *fakeUnitManager
|
||||
status *fakeHelperStatusWriter
|
||||
events []string
|
||||
enable *useCases.EnableBrowserUpdatesUseCase
|
||||
disable *useCases.DisableBrowserUpdatesUseCase
|
||||
}
|
||||
|
||||
func newInstallRig() *installRig {
|
||||
rig := &installRig{
|
||||
probe: &fakeMachineProbe{os: "linux", systemd: true, root: true},
|
||||
locator: &fakeServiceLocator{
|
||||
found: true,
|
||||
description: update.ServiceDescription{
|
||||
BinaryPath: "/opt/renewcms/renewcms",
|
||||
DataDir: "/var/lib/renewcms",
|
||||
EnvironmentFile: "/etc/renewcms/renewcms.env",
|
||||
},
|
||||
},
|
||||
}
|
||||
rig.units = &fakeUnitWriter{units: map[string]string{}, events: &rig.events}
|
||||
rig.manager = &fakeUnitManager{events: &rig.events}
|
||||
rig.status = &fakeHelperStatusWriter{status: map[string]update.HelperStatus{}, events: &rig.events}
|
||||
rig.rebuild()
|
||||
return rig
|
||||
}
|
||||
|
||||
func (r *installRig) rebuild() {
|
||||
dependencies := useCases.ManageBrowserUpdatesDependencies{
|
||||
Probe: r.probe, Locator: r.locator, Units: r.units, Manager: r.manager, Status: r.status,
|
||||
Now: func() time.Time { return restartBaseTime },
|
||||
}
|
||||
r.enable = useCases.NewEnableBrowserUpdatesUseCase(dependencies)
|
||||
r.disable = useCases.NewDisableBrowserUpdatesUseCase(dependencies)
|
||||
}
|
||||
|
||||
func TestEnableBrowserUpdatesRefusals(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
prepare func(*installRig)
|
||||
message string
|
||||
}{
|
||||
{"the OS is not Linux", func(r *installRig) { r.probe.os = "windows" }, "Browser updates need Linux with systemd."},
|
||||
{"Linux without systemd", func(r *installRig) { r.probe.systemd = false }, "Browser updates need systemd, which this machine is not running."},
|
||||
{"not run as root", func(r *installRig) { r.probe.root = false }, "Run this command as root, for example with sudo."},
|
||||
{"no unit for the service and no flags", func(r *installRig) { r.locator.found = false; r.locator.description = update.ServiceDescription{} }, "Could not find the RenewCMS service. Pass --service, --binary and --data-dir."},
|
||||
{"the data directory cannot be resolved", func(r *installRig) { r.locator.description.DataDir = "" }, "Could not find the data directory. Pass --data-dir."},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run("enable-browser-updates refuses when it cannot work: "+tc.name, func(t *testing.T) {
|
||||
rig := newInstallRig()
|
||||
tc.prepare(rig)
|
||||
|
||||
_, err := rig.enable.Enable(update.InstallOptions{})
|
||||
|
||||
if err == nil || err.Error() != tc.message {
|
||||
t.Errorf("err = %v, want %q", err, tc.message)
|
||||
}
|
||||
if len(rig.events) != 0 || len(rig.units.units) != 0 || len(rig.status.status) != 0 {
|
||||
t.Errorf("nothing may be written: %v", rig.events)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnableBrowserUpdates(t *testing.T) {
|
||||
t.Run("enable-browser-updates installs the units", func(t *testing.T) {
|
||||
rig := newInstallRig()
|
||||
rig.locator.port, rig.locator.hasPort = "9090", true
|
||||
|
||||
message, err := rig.enable.Enable(update.InstallOptions{})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := rig.units.units[update.ServiceUnitName]
|
||||
path := rig.units.units[update.PathUnitName]
|
||||
for _, want := range []string{"Type=oneshot", "User=root", "ExecStart=/opt/renewcms/renewcms apply-update", "--service renewcms", "--binary /opt/renewcms/renewcms", "--data-dir /var/lib/renewcms", "--port 9090"} {
|
||||
if !strings.Contains(service, want) {
|
||||
t.Errorf("service unit lacks %q:\n%s", want, service)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(path, "PathExists=/var/lib/renewcms/update-restart-request.json") || !strings.Contains(path, "Unit=renewcms-update.service") {
|
||||
t.Errorf("path unit:\n%s", path)
|
||||
}
|
||||
assertInOrder(t, rig.events, "write", "write", "daemon-reload", "enable renewcms-update.path", "status")
|
||||
if rig.events[len(rig.events)-1] != "status" {
|
||||
t.Errorf("the status file must be written last: %v", rig.events)
|
||||
}
|
||||
status := rig.status.status["/var/lib/renewcms"]
|
||||
if status.Version != 1 || status.Service != "renewcms" || status.Binary != "/opt/renewcms/renewcms" || status.DataDir != "/var/lib/renewcms" || !status.InstalledAt.Equal(restartBaseTime) {
|
||||
t.Errorf("status = %+v", status)
|
||||
}
|
||||
if !strings.Contains(message, "renewcms disable-browser-updates") || !strings.Contains(message, update.PathUnitName) {
|
||||
t.Errorf("message = %q", message)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the port comes from --port, else the environment file, else 8080", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
flag, env string
|
||||
hasEnv bool
|
||||
want string
|
||||
}{
|
||||
{"7000", "9090", true, "--port 7000"},
|
||||
{"", "9090", true, "--port 9090"},
|
||||
{"", "", false, "--port 8080"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
rig := newInstallRig()
|
||||
rig.locator.port, rig.locator.hasPort = tc.env, tc.hasEnv
|
||||
|
||||
if _, err := rig.enable.Enable(update.InstallOptions{Port: tc.flag}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if !strings.Contains(rig.units.units[update.ServiceUnitName], tc.want) {
|
||||
t.Errorf("want %q in:\n%s", tc.want, rig.units.units[update.ServiceUnitName])
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("flags override the unit", func(t *testing.T) {
|
||||
rig := newInstallRig()
|
||||
|
||||
_, err := rig.enable.Enable(update.InstallOptions{Service: "cms", Binary: "/srv/cms bin/renewcms", DataDir: "/srv/data", Port: "81"})
|
||||
|
||||
service := rig.units.units[update.ServiceUnitName]
|
||||
if err != nil || !strings.Contains(service, `"/srv/cms bin/renewcms" apply-update --service cms --binary "/srv/cms bin/renewcms" --data-dir /srv/data --port 81`) {
|
||||
t.Errorf("err = %v, unit:\n%s", err, service)
|
||||
}
|
||||
if _, found := rig.status.status["/srv/data"]; !found {
|
||||
t.Error("the status file goes to the overridden data directory")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("an invalid port is refused", func(t *testing.T) {
|
||||
rig := newInstallRig()
|
||||
|
||||
_, err := rig.enable.Enable(update.InstallOptions{Port: "http"})
|
||||
|
||||
if !errors.Is(err, update.ErrInvalidPort) || len(rig.units.units) != 0 {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("enable-browser-updates undoes its own partial work", func(t *testing.T) {
|
||||
cases := map[string]func(*installRig){
|
||||
"writing the second unit": func(r *installRig) { r.units.failNth = 2 },
|
||||
"daemon-reload": func(r *installRig) { r.manager.reloadErr = errors.New("reload failed") },
|
||||
"enable": func(r *installRig) { r.manager.enableErr = errors.New("enable failed") },
|
||||
}
|
||||
for name, fail := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
rig := newInstallRig()
|
||||
fail(rig)
|
||||
|
||||
_, err := rig.enable.Enable(update.InstallOptions{})
|
||||
|
||||
if err == nil || len(rig.units.units) != 0 || len(rig.status.status) != 0 {
|
||||
t.Errorf("err = %v, units = %v, status = %v", err, rig.units.units, rig.status.status)
|
||||
}
|
||||
for _, event := range rig.events {
|
||||
if event == "status" {
|
||||
t.Error("update-helper.json must not be written")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("enable-browser-updates is idempotent", func(t *testing.T) {
|
||||
rig := newInstallRig()
|
||||
if _, err := rig.enable.Enable(update.InstallOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := map[string]string{}
|
||||
for name, content := range rig.units.units {
|
||||
first[name] = content
|
||||
}
|
||||
|
||||
if _, err := rig.enable.Enable(update.InstallOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rig.units.units) != 2 || rig.units.units[update.ServiceUnitName] != first[update.ServiceUnitName] || rig.units.units[update.PathUnitName] != first[update.PathUnitName] {
|
||||
t.Error("a second run must rewrite identical units")
|
||||
}
|
||||
|
||||
rig.locator.description.BinaryPath = "/usr/local/bin/renewcms"
|
||||
if _, err := rig.enable.Enable(update.InstallOptions{Service: "renewcms2"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rig.units.units) != 2 || !strings.Contains(rig.units.units[update.ServiceUnitName], "/usr/local/bin/renewcms") || !strings.Contains(rig.units.units[update.ServiceUnitName], "--service renewcms2") {
|
||||
t.Errorf("units must follow the new values: %v", rig.units.units)
|
||||
}
|
||||
if rig.status.status["/var/lib/renewcms"].Binary != "/usr/local/bin/renewcms" {
|
||||
t.Error("the status file follows the new values")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestBrowserUpdatesOverRealFiles(t *testing.T) {
|
||||
setup := func(t *testing.T) (*installRig, string, string, string) {
|
||||
t.Helper()
|
||||
directory := t.TempDir()
|
||||
unitDirectory := filepath.Join(directory, "units")
|
||||
dataDir := filepath.Join(directory, "data")
|
||||
envFile := filepath.Join(directory, "renewcms.env")
|
||||
for _, path := range []string{unitDirectory, dataDir} {
|
||||
if err := os.MkdirAll(path, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
environment := "ENVIRONMENT=production\nPORT=9191\nJWT_SECRET=sentinel-secret\nSMTP_PASSWORD=sentinel-smtp\n"
|
||||
if err := os.WriteFile(envFile, []byte(environment), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unit := "[Service]\nUser=renewcms\nEnvironmentFile=-" + envFile + "\nExecStart=/opt/renewcms/renewcms\nReadWritePaths=" + dataDir + "\n"
|
||||
if err := os.WriteFile(filepath.Join(unitDirectory, "renewcms.service"), []byte(unit), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rig := newInstallRig()
|
||||
units := infraUpdate.NewSystemdUnitsIn(unitDirectory)
|
||||
rig.locator = nil
|
||||
dependencies := useCases.ManageBrowserUpdatesDependencies{
|
||||
Probe: rig.probe, Locator: units, Units: units, Manager: rig.manager,
|
||||
Status: infraUpdate.NewJSONHelperStatusWriter(), Now: func() time.Time { return restartBaseTime },
|
||||
}
|
||||
rig.enable = useCases.NewEnableBrowserUpdatesUseCase(dependencies)
|
||||
rig.disable = useCases.NewDisableBrowserUpdatesUseCase(dependencies)
|
||||
return rig, unitDirectory, dataDir, envFile
|
||||
}
|
||||
|
||||
t.Run("it reads the unit and writes no secret and no environment value", func(t *testing.T) {
|
||||
rig, unitDirectory, dataDir, _ := setup(t)
|
||||
|
||||
if _, err := rig.enable.Enable(update.InstallOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
for _, name := range []string{update.ServiceUnitName, update.PathUnitName} {
|
||||
content, err := os.ReadFile(filepath.Join(unitDirectory, name))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, forbidden := range []string{"JWT_SECRET", "sentinel-secret", "sentinel-smtp", "SMTP_PASSWORD", "ENVIRONMENT"} {
|
||||
if strings.Contains(string(content), forbidden) {
|
||||
t.Errorf("%s contains %q", name, forbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
service, _ := os.ReadFile(filepath.Join(unitDirectory, update.ServiceUnitName))
|
||||
if !strings.Contains(string(service), "--port 9191") || !strings.Contains(string(service), "--data-dir ") {
|
||||
t.Errorf("service unit:\n%s", service)
|
||||
}
|
||||
if !infraUpdate.NewFileHelperDetector(filepath.Join(dataDir, update.HelperStatusFileName)).Installed() {
|
||||
t.Error("can_apply must read true afterwards")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("disable-browser-updates", func(t *testing.T) {
|
||||
rig, unitDirectory, dataDir, _ := setup(t)
|
||||
if _, err := rig.enable.Enable(update.InstallOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kept := []string{update.RestartRequestFileName, update.ResultFileName, "updates/v2.3.0-beta/binary", "backups/renewcms-1.db"}
|
||||
for _, name := range kept {
|
||||
full := filepath.Join(dataDir, filepath.FromSlash(name))
|
||||
_ = os.MkdirAll(filepath.Dir(full), 0o755)
|
||||
if err := os.WriteFile(full, []byte("keep"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rig.events = nil
|
||||
|
||||
message, err := rig.disable.Disable(update.InstallOptions{})
|
||||
|
||||
if err != nil || !strings.Contains(message, "disabled") {
|
||||
t.Fatalf("message = %q, err = %v", message, err)
|
||||
}
|
||||
for _, name := range []string{update.PathUnitName, update.ServiceUnitName} {
|
||||
if _, statErr := os.Stat(filepath.Join(unitDirectory, name)); statErr == nil {
|
||||
t.Errorf("%s must be removed", name)
|
||||
}
|
||||
}
|
||||
assertInOrder(t, rig.events, "disable renewcms-update.path", "daemon-reload")
|
||||
for _, name := range kept {
|
||||
if _, statErr := os.Stat(filepath.Join(dataDir, filepath.FromSlash(name))); statErr != nil {
|
||||
t.Errorf("%s must be left in place", name)
|
||||
}
|
||||
}
|
||||
if infraUpdate.NewFileHelperDetector(filepath.Join(dataDir, update.HelperStatusFileName)).Installed() {
|
||||
t.Error("can_apply must read false afterwards")
|
||||
}
|
||||
|
||||
again, err := rig.disable.Disable(update.InstallOptions{})
|
||||
if err != nil || !strings.Contains(again, "not enabled") {
|
||||
t.Errorf("a second run: message = %q, err = %v", again, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("disable-browser-updates where it was never enabled exits cleanly", func(t *testing.T) {
|
||||
rig, _, _, _ := setup(t)
|
||||
|
||||
message, err := rig.disable.Disable(update.InstallOptions{})
|
||||
|
||||
if err != nil || !strings.Contains(message, "not enabled") {
|
||||
t.Errorf("message = %q, err = %v", message, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("disable-browser-updates on a machine without systemd is a no-op", func(t *testing.T) {
|
||||
rig := newInstallRig()
|
||||
rig.probe.os = "windows"
|
||||
|
||||
message, err := rig.disable.Disable(update.InstallOptions{})
|
||||
|
||||
if err != nil || !strings.Contains(message, "not enabled") || len(rig.events) != 0 {
|
||||
t.Errorf("message = %q, err = %v, events = %v", message, err, rig.events)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRenderServiceUnitEscaping(t *testing.T) {
|
||||
t.Run("backslashes, quotes, percent and dollar in a value cannot alter the unit", func(t *testing.T) {
|
||||
unit := update.RenderServiceUnit(update.InstallOptions{
|
||||
Service: `svc\x`,
|
||||
Binary: `/opt/a\b"c%d$e/bin`,
|
||||
DataDir: "/data\nUser=evil",
|
||||
Port: "80",
|
||||
})
|
||||
|
||||
want := `ExecStart="/opt/a\\b\"c%%d$$e/bin" apply-update --service "svc\\x" --binary "/opt/a\\b\"c%%d$$e/bin" --data-dir "/data\nUser=evil" --port 80`
|
||||
if !strings.Contains(unit, want) {
|
||||
t.Errorf("unit:\n%s\nwant line %s", unit, want)
|
||||
}
|
||||
if strings.Count(unit, "\nUser=") != 1 {
|
||||
t.Errorf("an injected directive must not appear:\n%s", unit)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a plain value stays unquoted", func(t *testing.T) {
|
||||
unit := update.RenderServiceUnit(update.InstallOptions{Service: "renewcms", Binary: "/opt/renewcms/renewcms", DataDir: "/var/lib/renewcms", Port: "8080"})
|
||||
|
||||
if !strings.Contains(unit, "ExecStart=/opt/renewcms/renewcms apply-update --service renewcms") {
|
||||
t.Errorf("unit:\n%s", unit)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//go:build linux
|
||||
|
||||
package test
|
||||
|
||||
import (
|
||||
infraUpdate "RenewCMS/internal/infrastructure/update"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNoFollowFilesystemOnLinux(t *testing.T) {
|
||||
files := infraUpdate.NewNoFollowFilesystem()
|
||||
directory := t.TempDir()
|
||||
outside := filepath.Join(t.TempDir(), "outside.txt")
|
||||
if err := os.WriteFile(outside, []byte("sentinel"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := filepath.Join(directory, "link")
|
||||
if err := os.Symlink(outside, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
t.Run("lstat reports a symlink without following it", func(t *testing.T) {
|
||||
info, err := files.Lstat(link)
|
||||
if err != nil || !info.IsSymlink || info.IsRegular {
|
||||
t.Errorf("info = %+v, err = %v", info, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("it never reads, copies, writes or chmods through a symlink", func(t *testing.T) {
|
||||
if _, err := files.ReadFile(link); err == nil {
|
||||
t.Error("read followed the link")
|
||||
}
|
||||
if err := files.Copy(link, filepath.Join(directory, "copy"), 0o600); err == nil {
|
||||
t.Error("copy followed the link")
|
||||
}
|
||||
if err := files.CreateExclusive(link, []byte("x"), 0o600); err == nil {
|
||||
t.Error("create followed the link")
|
||||
}
|
||||
if err := files.Chmod(link, 0o777); err == nil {
|
||||
t.Error("chmod followed the link")
|
||||
}
|
||||
if content, _ := os.ReadFile(outside); string(content) != "sentinel" {
|
||||
t.Errorf("the target changed: %q", content)
|
||||
}
|
||||
if info, _ := os.Stat(outside); info.Mode().Perm() != 0o644 {
|
||||
t.Errorf("the target mode changed: %v", info.Mode())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("create-exclusive refuses an existing file and sets the mode", func(t *testing.T) {
|
||||
path := filepath.Join(directory, "exclusive")
|
||||
if err := files.CreateExclusive(path, []byte("one"), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := files.CreateExclusive(path, []byte("two"), 0o640); err == nil {
|
||||
t.Error("the second create must fail")
|
||||
}
|
||||
if info, _ := os.Stat(path); info.Mode().Perm() != 0o640 {
|
||||
t.Errorf("mode = %v", info.Mode())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("copy, rename, chmod and remove work on regular files", func(t *testing.T) {
|
||||
source := filepath.Join(directory, "source")
|
||||
_ = os.WriteFile(source, []byte("payload"), 0o600)
|
||||
copied := filepath.Join(directory, "copied")
|
||||
|
||||
if err := files.Copy(source, copied, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
renamed := filepath.Join(directory, "renamed")
|
||||
if err := files.Rename(copied, renamed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := files.Chmod(renamed, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
content, _ := files.ReadFile(renamed)
|
||||
info, _ := os.Stat(renamed)
|
||||
if string(content) != "payload" || info.Mode().Perm() != 0o700 {
|
||||
t.Errorf("content = %q, mode = %v", content, info.Mode())
|
||||
}
|
||||
if err := files.Remove(renamed); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("remove-all unlinks links and never descends into them", func(t *testing.T) {
|
||||
tree := filepath.Join(directory, "tree")
|
||||
_ = os.MkdirAll(filepath.Join(tree, "nested"), 0o755)
|
||||
_ = os.WriteFile(filepath.Join(tree, "nested", "file"), []byte("x"), 0o644)
|
||||
escape := t.TempDir()
|
||||
_ = os.WriteFile(filepath.Join(escape, "keep"), []byte("keep"), 0o644)
|
||||
_ = os.Symlink(escape, filepath.Join(tree, "escape"))
|
||||
|
||||
if err := files.RemoveAll(tree); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(tree); err == nil {
|
||||
t.Error("the tree must be gone")
|
||||
}
|
||||
if content, _ := os.ReadFile(filepath.Join(escape, "keep")); string(content) != "keep" {
|
||||
t.Error("the link target must be intact")
|
||||
}
|
||||
if err := files.RemoveAll(tree); err != nil {
|
||||
t.Errorf("removing a missing path = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the temp directory is private", func(t *testing.T) {
|
||||
temp, err := files.MakePrivateTempDir()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(temp)
|
||||
info, _ := os.Stat(temp)
|
||||
if !info.IsDir() || info.Mode().Perm() != 0o700 {
|
||||
t.Errorf("mode = %v", info.Mode())
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
//go:build !linux
|
||||
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
infraUpdate "RenewCMS/internal/infrastructure/update"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNoFollowFilesystemStubRefuses(t *testing.T) {
|
||||
files := infraUpdate.NewNoFollowFilesystem()
|
||||
|
||||
_, lstatErr := files.Lstat("x")
|
||||
_, readErr := files.ReadFile("x")
|
||||
_, tempErr := files.MakePrivateTempDir()
|
||||
|
||||
for name, err := range map[string]error{
|
||||
"lstat": lstatErr,
|
||||
"read": readErr,
|
||||
"tempdir": tempErr,
|
||||
"create": files.CreateExclusive("x", nil, 0o600),
|
||||
"copy": files.Copy("x", "y", 0o600),
|
||||
"rename": files.Rename("x", "y"),
|
||||
"remove": files.Remove("x"),
|
||||
"removeAll": files.RemoveAll("x"),
|
||||
"chmod": files.Chmod("x", 0o600),
|
||||
} {
|
||||
if !errors.Is(err, update.ErrHelperUnsupported) {
|
||||
t.Errorf("%s = %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,913 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
infraUpdate "RenewCMS/internal/infrastructure/update"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
helperData = "/var/lib/renewcms"
|
||||
helperBinary = "/opt/renewcms/renewcms"
|
||||
helperBinaryDir = "/opt/renewcms"
|
||||
helperOld = "v2.2.0-beta"
|
||||
helperSentinel = "sentinel bytes that must never change"
|
||||
)
|
||||
|
||||
var (
|
||||
helperMarker = helperData + "/" + update.RestartRequestFileName
|
||||
helperResult = helperData + "/" + update.ResultFileName
|
||||
helperResultTmp = helperResult + ".tmp"
|
||||
helperUpdatesDir = helperData + "/" + update.UpdatesDirName
|
||||
helperStagedDir = helperUpdatesDir + "/" + downloadTag
|
||||
helperAsset = update.AssetName(downloadTag, update.Platform{OS: "linux", Arch: "amd64"})
|
||||
)
|
||||
|
||||
type fsVerifier struct {
|
||||
files *fakeHelperFS
|
||||
key ed25519.PublicKey
|
||||
events *[]string
|
||||
}
|
||||
|
||||
var _ update.SignatureVerifier = &fsVerifier{}
|
||||
|
||||
func (v *fsVerifier) Verify(checksumsPath string, signaturePath string) error {
|
||||
*v.events = append(*v.events, "verify "+checksumsPath)
|
||||
checksums, found := v.files.content(checksumsPath)
|
||||
if !found {
|
||||
return errors.New("checksums missing")
|
||||
}
|
||||
rawSignature, found := v.files.content(signaturePath)
|
||||
if !found {
|
||||
return errors.New("signature missing")
|
||||
}
|
||||
signature, err := base64.StdEncoding.DecodeString(strings.TrimSpace(rawSignature))
|
||||
if err != nil || !ed25519.Verify(v.key, []byte(checksums), signature) {
|
||||
return errors.New("signature mismatch")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type helperRig struct {
|
||||
t *testing.T
|
||||
fs *fakeHelperFS
|
||||
running *fakeRunningInfoStore
|
||||
clock *fakeClock
|
||||
service *fakeServiceControl
|
||||
health *fakeHealthChecker
|
||||
logger *fakeUpdateLogger
|
||||
events []string
|
||||
public ed25519.PublicKey
|
||||
private ed25519.PrivateKey
|
||||
newBinary string
|
||||
bootVersions []string
|
||||
oldInfo update.RunningInfo
|
||||
usecase *useCases.ApplyRestartRequestUseCase
|
||||
}
|
||||
|
||||
func newHelperRig(t *testing.T) *helperRig {
|
||||
t.Helper()
|
||||
public, private, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rig := &helperRig{
|
||||
t: t,
|
||||
fs: newFakeHelperFS(),
|
||||
running: &fakeRunningInfoStore{},
|
||||
clock: &fakeClock{now: restartBaseTime},
|
||||
health: &fakeHealthChecker{healthy: true},
|
||||
logger: &fakeUpdateLogger{},
|
||||
public: public,
|
||||
private: private,
|
||||
newBinary: "new binary bytes 2.3.0",
|
||||
bootVersions: []string{downloadTag, helperOld},
|
||||
oldInfo: update.RunningInfo{Version: helperOld, Pid: 100, StartedAt: restartBaseTime.Add(-time.Hour)},
|
||||
}
|
||||
rig.fs.events = &rig.events
|
||||
rig.fs.putFile(helperBinary, "old")
|
||||
rig.fs.putDir(helperData)
|
||||
rig.running.set(rig.oldInfo)
|
||||
rig.service = &fakeServiceControl{clock: rig.clock, failOn: map[int]error{}, events: &rig.events}
|
||||
rig.service.onRestart = func(call int) {
|
||||
version := rig.bootVersions[min(call, len(rig.bootVersions))-1]
|
||||
rig.running.set(update.RunningInfo{Version: version, Pid: 200 + call, StartedAt: rig.clock.Now().Add(time.Second)})
|
||||
}
|
||||
rig.usecase = rig.build()
|
||||
return rig
|
||||
}
|
||||
|
||||
func (r *helperRig) build() *useCases.ApplyRestartRequestUseCase {
|
||||
return useCases.NewApplyRestartRequestUseCase(useCases.ApplyRestartRequestDependencies{
|
||||
Requests: infraUpdate.NewFSRestartRequestStore(r.fs, helperMarker),
|
||||
Results: infraUpdate.NewFSResultStore(r.fs, helperResult),
|
||||
Running: r.running,
|
||||
Files: r.fs,
|
||||
Service: r.service,
|
||||
Health: r.health,
|
||||
Verifier: &fsVerifier{files: r.fs, key: r.public, events: &r.events},
|
||||
Clock: r.clock,
|
||||
Logger: r.logger,
|
||||
Layout: update.HelperLayout{DataDir: helperData, BinaryPath: helperBinary},
|
||||
Platform: update.Platform{OS: "linux", Arch: "amd64"},
|
||||
})
|
||||
}
|
||||
|
||||
func (r *helperRig) checksumsFor(binary string) string {
|
||||
return update.SHA256Hex([]byte(binary)) + " " + helperAsset + "\n"
|
||||
}
|
||||
|
||||
func (r *helperRig) sign(checksums string, key ed25519.PrivateKey) string {
|
||||
return base64.StdEncoding.EncodeToString(ed25519.Sign(key, []byte(checksums))) + "\n"
|
||||
}
|
||||
|
||||
func (r *helperRig) stage() {
|
||||
checksums := r.checksumsFor(r.newBinary)
|
||||
r.fs.putFile(helperStagedDir+"/"+helperAsset, r.newBinary)
|
||||
r.fs.putFile(helperStagedDir+"/checksums.txt", checksums)
|
||||
r.fs.putFile(helperStagedDir+"/checksums.txt.sig", r.sign(checksums, r.private))
|
||||
}
|
||||
|
||||
func (r *helperRig) markUpdate(tag string) {
|
||||
r.writeMarker(update.RestartRequest{Kind: update.RestartKindUpdate, Tag: tag, RequestedAt: restartBaseTime, RequestedBy: 1})
|
||||
}
|
||||
|
||||
func (r *helperRig) markRestart() {
|
||||
r.bootVersions = []string{helperOld, helperOld}
|
||||
r.writeMarker(update.RestartRequest{Kind: update.RestartKindRestart, RequestedAt: restartBaseTime, RequestedBy: 1})
|
||||
}
|
||||
|
||||
func (r *helperRig) writeMarker(request update.RestartRequest) {
|
||||
content, _ := json.Marshal(request)
|
||||
r.fs.putFile(helperMarker, string(content))
|
||||
}
|
||||
|
||||
func (r *helperRig) apply() error {
|
||||
r.t.Helper()
|
||||
return r.usecase.Apply()
|
||||
}
|
||||
|
||||
func (r *helperRig) result() update.Result {
|
||||
r.t.Helper()
|
||||
content, found := r.fs.content(helperResult)
|
||||
if !found {
|
||||
r.t.Fatal("update-result.json was not written")
|
||||
}
|
||||
var result update.Result
|
||||
if err := json.Unmarshal([]byte(content), &result); err != nil {
|
||||
r.t.Fatalf("result is not json: %v", err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (r *helperRig) outcomes() []string {
|
||||
var outcomes []string
|
||||
for _, content := range r.fs.history[helperResult] {
|
||||
var result update.Result
|
||||
_ = json.Unmarshal([]byte(content), &result)
|
||||
outcomes = append(outcomes, result.Outcome)
|
||||
}
|
||||
return outcomes
|
||||
}
|
||||
|
||||
func (r *helperRig) assertBinary(want string) {
|
||||
r.t.Helper()
|
||||
if content, _ := r.fs.content(helperBinary); content != want {
|
||||
r.t.Errorf("binary = %q, want %q", content, want)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *helperRig) assertUntouched() {
|
||||
r.t.Helper()
|
||||
r.assertBinary("old")
|
||||
if r.fs.exists(helperBinary + ".previous") {
|
||||
r.t.Error("no .previous may be written")
|
||||
}
|
||||
if r.service.restartCount() != 0 {
|
||||
r.t.Errorf("restarts = %d, want 0", r.service.restartCount())
|
||||
}
|
||||
}
|
||||
|
||||
func (r *helperRig) assertOutsideUntouched(sentinelPaths ...string) {
|
||||
r.t.Helper()
|
||||
if outside := r.fs.resolvedOutside(helperData, helperBinaryDir, "/tmp"); len(outside) != 0 {
|
||||
r.t.Errorf("operations reached outside the allowed directories: %v", outside)
|
||||
}
|
||||
for _, target := range sentinelPaths {
|
||||
if content, _ := r.fs.content(target); content != helperSentinel {
|
||||
r.t.Errorf("%s changed: %q", target, content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *helperRig) assertCleaned() {
|
||||
r.t.Helper()
|
||||
if r.fs.exists(helperStagedDir) {
|
||||
r.t.Error("the staged directory must be removed")
|
||||
}
|
||||
for name := range r.fs.nodes {
|
||||
if strings.HasPrefix(name, "/tmp/renewcms-update-") {
|
||||
r.t.Errorf("the temp directory must be removed, found %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertInOrder(t *testing.T, events []string, wants ...string) {
|
||||
t.Helper()
|
||||
position := 0
|
||||
for _, want := range wants {
|
||||
found := false
|
||||
for ; position < len(events); position++ {
|
||||
if strings.HasPrefix(events[position], want) {
|
||||
found = true
|
||||
position++
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("%q is missing or out of order in:\n%s", want, strings.Join(events, "\n"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyPlainRestart(t *testing.T) {
|
||||
t.Run("apply-update, a plain restart", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.markRestart()
|
||||
rig.fs.putFile(helperStagedDir+"/keep", "staged")
|
||||
|
||||
if err := rig.apply(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
assertInOrder(t, rig.events, "lstat "+helperMarker, "read "+helperMarker, "remove "+helperMarker, "create "+helperResultTmp, "restart", "create "+helperResultTmp)
|
||||
if got := rig.outcomes(); len(got) != 2 || got[0] != "running" || got[1] != "succeeded" {
|
||||
t.Errorf("outcomes = %v", got)
|
||||
}
|
||||
result := rig.result()
|
||||
if result.Kind != "restart" || result.FinishedAt == nil || result.FromVersion != helperOld || !result.StartedAt.Equal(restartBaseTime) {
|
||||
t.Errorf("result = %+v", result)
|
||||
}
|
||||
if rig.service.restartCount() != 1 || rig.fs.exists(helperBinary+".previous") {
|
||||
t.Error("one restart, no write next to the binary")
|
||||
}
|
||||
rig.assertBinary("old")
|
||||
if content, _ := rig.fs.content(helperStagedDir + "/keep"); content != "staged" {
|
||||
t.Error("the staged files must be untouched")
|
||||
}
|
||||
if rig.fs.exists(helperMarker) {
|
||||
t.Error("the marker must be deleted")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no marker means nothing to do", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
|
||||
if err := rig.apply(); err != nil || rig.fs.exists(helperResult) || rig.service.restartCount() != 0 {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a corrupt marker or an unknown kind fails without restarting", func(t *testing.T) {
|
||||
for name, content := range map[string]string{"corrupt": "{nope", "unknown kind": `{"kind":"reboot","requested_at":"2026-09-30T09:50:00Z"}`} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.fs.putFile(helperMarker, content)
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil || rig.result().Outcome != "failed" || rig.service.restartCount() != 0 || rig.fs.exists(helperMarker) {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestApplyStaleRunningInfo(t *testing.T) {
|
||||
staleRows := map[string]struct {
|
||||
kind string
|
||||
boots func(rig *helperRig, call int)
|
||||
}{
|
||||
"still holds the old pid and old started_at": {"restart", func(rig *helperRig, call int) {}},
|
||||
"holds the target version but the old pid and an old started_at": {"update", func(rig *helperRig, call int) {
|
||||
rig.running.set(update.RunningInfo{Version: downloadTag, Pid: rig.oldInfo.Pid, StartedAt: rig.oldInfo.StartedAt})
|
||||
}},
|
||||
"is missing": {"restart", func(rig *helperRig, call int) { rig.running.unreadable() }},
|
||||
"is corrupt": {"restart", func(rig *helperRig, call int) { rig.running.unreadable() }},
|
||||
"holds the old version with a new pid (for an update)": {"update", func(rig *helperRig, call int) {
|
||||
rig.running.set(update.RunningInfo{Version: helperOld, Pid: 300, StartedAt: rig.clock.Now().Add(time.Second)})
|
||||
}},
|
||||
}
|
||||
for name, row := range staleRows {
|
||||
t.Run("A stale running file never counts as success: "+name, func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
if row.kind == "update" {
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
} else {
|
||||
rig.markRestart()
|
||||
}
|
||||
rig.service.onRestart = func(call int) {
|
||||
if call == 1 {
|
||||
row.boots(rig, call)
|
||||
return
|
||||
}
|
||||
rig.running.set(update.RunningInfo{Version: helperOld, Pid: 500, StartedAt: rig.clock.Now().Add(time.Second)})
|
||||
}
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
result := rig.result()
|
||||
first := rig.service.restarts[0]
|
||||
if row.kind == "restart" {
|
||||
if err == nil || result.Outcome != "failed" || rig.service.restartCount() != 1 {
|
||||
t.Errorf("err = %v, result = %+v", err, result)
|
||||
}
|
||||
if rig.clock.Now().Sub(first) < update.RestartWindow {
|
||||
t.Errorf("gave up after %v", rig.clock.Now().Sub(first))
|
||||
}
|
||||
return
|
||||
}
|
||||
if result.Outcome != "rolled_back" || rig.service.restartCount() != 2 {
|
||||
t.Fatalf("result = %+v, restarts = %d", result, rig.service.restartCount())
|
||||
}
|
||||
if rig.service.restarts[1].Sub(first) < update.RestartWindow {
|
||||
t.Errorf("rolled back after %v, before the 60 s window", rig.service.restarts[1].Sub(first))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("a file with the same pid but a later started_at counts as new", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.markRestart()
|
||||
rig.service.onRestart = func(int) {
|
||||
rig.running.set(update.RunningInfo{Version: helperOld, Pid: rig.oldInfo.Pid, StartedAt: rig.clock.Now().Add(time.Second)})
|
||||
}
|
||||
|
||||
if err := rig.apply(); err != nil || rig.result().Outcome != "succeeded" || rig.clock.sleeps != 0 {
|
||||
t.Errorf("err = %v, outcome = %v, sleeps = %d", err, rig.result().Outcome, rig.clock.sleeps)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("success needs a healthy answer too", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.markRestart()
|
||||
rig.health.healthy = false
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err == nil || rig.result().Outcome != "failed" {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestApplyUpdate(t *testing.T) {
|
||||
t.Run("apply-update, an update, happy path", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
temp := "/tmp/renewcms-update-1"
|
||||
|
||||
if err := rig.apply(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
assertInOrder(t, rig.events,
|
||||
"read "+helperMarker, "remove "+helperMarker, "create "+helperResultTmp,
|
||||
"lstat "+helperStagedDir+"/"+helperAsset, "tempdir",
|
||||
"copy "+helperStagedDir+"/"+helperAsset, "copy "+helperStagedDir+"/checksums.txt", "copy "+helperStagedDir+"/checksums.txt.sig",
|
||||
"verify "+temp+"/checksums.txt", "read "+temp+"/checksums.txt", "read "+temp+"/"+helperAsset,
|
||||
"copy "+helperBinary, "rename "+helperBinary+".previous.tmp",
|
||||
"copy "+temp+"/"+helperAsset, "read "+helperBinary+".new", "chmod "+helperBinary+".new", "rename "+helperBinary+".new",
|
||||
"restart", "create "+helperResultTmp, "removeall "+temp, "removeall "+helperStagedDir)
|
||||
rig.assertBinary(rig.newBinary)
|
||||
if previous, _ := rig.fs.content(helperBinary + ".previous"); previous != "old" {
|
||||
t.Errorf(".previous = %q", previous)
|
||||
}
|
||||
if rig.fs.mode(helperBinary) != 0o755 || rig.fs.mode(temp) != 0 {
|
||||
t.Errorf("binary mode = %o, temp directory must be gone", rig.fs.mode(helperBinary))
|
||||
}
|
||||
if rig.clock.sleeps != 0 || rig.service.restartCount() != 1 {
|
||||
t.Errorf("success must be declared on the first matching poll: sleeps = %d", rig.clock.sleeps)
|
||||
}
|
||||
result := rig.result()
|
||||
if result.Outcome != "succeeded" || result.Kind != "update" || result.Tag != downloadTag || result.FromVersion != helperOld {
|
||||
t.Errorf("result = %+v", result)
|
||||
}
|
||||
rig.assertCleaned()
|
||||
rig.assertOutsideUntouched()
|
||||
if rig.fs.exists(helperBinary+".new") || rig.fs.exists(helperBinary+".previous.tmp") {
|
||||
t.Error("no temp file may be left next to the binary")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the verified copy lives in a private temp directory", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
rig.fs.after("read", 4, func(f *fakeHelperFS) {
|
||||
if f.mode("/tmp/renewcms-update-1") != 0o700 || f.nodes["/tmp/renewcms-update-1"].owner != "root" {
|
||||
t.Errorf("temp directory mode = %o owner = %s", f.mode("/tmp/renewcms-update-1"), f.nodes["/tmp/renewcms-update-1"].owner)
|
||||
}
|
||||
})
|
||||
|
||||
_ = rig.apply()
|
||||
})
|
||||
|
||||
t.Run("apply-update refuses an untrusted staged binary", func(t *testing.T) {
|
||||
faults := map[string]struct {
|
||||
mutate func(*helperRig)
|
||||
reason string
|
||||
}{
|
||||
"the binary was changed after the job verified it": {func(r *helperRig) { r.fs.putFile(helperStagedDir+"/"+helperAsset, "tampered") }, "sha-256 mismatch"},
|
||||
"checksums.txt was changed": {func(r *helperRig) {
|
||||
r.fs.putFile(helperStagedDir+"/checksums.txt", r.checksumsFor("tampered"))
|
||||
}, "signature"},
|
||||
"the signature is from a different key": {func(r *helperRig) {
|
||||
_, other, _ := ed25519.GenerateKey(rand.Reader)
|
||||
r.fs.putFile(helperStagedDir+"/checksums.txt.sig", r.sign(r.checksumsFor(r.newBinary), other))
|
||||
}, "signature"},
|
||||
"the signature is missing": {func(r *helperRig) { delete(r.fs.nodes, helperStagedDir+"/checksums.txt.sig") }, "checksums.txt.sig"},
|
||||
"checksums.txt has no line for the asset": {func(r *helperRig) {
|
||||
checksums := update.SHA256Hex([]byte("x")) + " something_else\n"
|
||||
r.fs.putFile(helperStagedDir+"/checksums.txt", checksums)
|
||||
r.fs.putFile(helperStagedDir+"/checksums.txt.sig", r.sign(checksums, r.private))
|
||||
}, "no line"},
|
||||
"the staged binary is missing": {func(r *helperRig) { delete(r.fs.nodes, helperStagedDir+"/"+helperAsset) }, helperAsset},
|
||||
}
|
||||
for name, fault := range faults {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
fault.mutate(rig)
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil || rig.result().Outcome != "failed" {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
rig.assertUntouched()
|
||||
rig.assertCleaned()
|
||||
if !strings.Contains(rig.logger.text(), fault.reason) {
|
||||
t.Errorf("the log must carry the reason %q: %s", fault.reason, rig.logger.text())
|
||||
}
|
||||
if raw, _ := rig.fs.content(helperResult); strings.Contains(raw, "mismatch") || strings.Contains(raw, helperData) {
|
||||
t.Errorf("the technical reason must stay out of the result file: %s", raw)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestApplyRefusesSymlinks(t *testing.T) {
|
||||
const outside = "/outside"
|
||||
type row struct {
|
||||
setup func(*helperRig)
|
||||
link string
|
||||
keep []string
|
||||
}
|
||||
rows := map[string]row{
|
||||
"the marker itself is a symlink": {func(r *helperRig) {
|
||||
r.fs.putFile(outside+"/secret", helperSentinel)
|
||||
r.fs.putSymlink(helperMarker, outside+"/secret")
|
||||
}, helperMarker, []string{outside + "/secret"}},
|
||||
"<data>/updates is a symlink to another directory": {func(r *helperRig) {
|
||||
r.fs.putDir(outside + "/updates/" + downloadTag)
|
||||
r.fs.putFile(outside+"/updates/"+downloadTag+"/"+helperAsset, helperSentinel)
|
||||
r.fs.putFile(outside+"/updates/"+downloadTag+"/checksums.txt", helperSentinel)
|
||||
r.fs.putFile(outside+"/updates/"+downloadTag+"/checksums.txt.sig", helperSentinel)
|
||||
r.forget(helperUpdatesDir)
|
||||
r.fs.putSymlink(helperUpdatesDir, outside+"/updates")
|
||||
}, helperUpdatesDir, []string{outside + "/updates/" + downloadTag + "/" + helperAsset}},
|
||||
"<data>/updates/<tag> is a symlink to another directory": {func(r *helperRig) {
|
||||
r.fs.putFile(outside+"/tag/"+helperAsset, helperSentinel)
|
||||
r.fs.putFile(outside+"/tag/checksums.txt", helperSentinel)
|
||||
r.fs.putFile(outside+"/tag/checksums.txt.sig", helperSentinel)
|
||||
r.forget(helperStagedDir)
|
||||
r.fs.putSymlink(helperStagedDir, outside+"/tag")
|
||||
}, helperStagedDir, []string{outside + "/tag/" + helperAsset, outside + "/tag/checksums.txt"}},
|
||||
"the staged binary is a symlink to /usr/bin/something": {func(r *helperRig) {
|
||||
r.fs.putFile("/usr/bin/something", helperSentinel)
|
||||
delete(r.fs.nodes, helperStagedDir+"/"+helperAsset)
|
||||
r.fs.putSymlink(helperStagedDir+"/"+helperAsset, "/usr/bin/something")
|
||||
}, helperStagedDir + "/" + helperAsset, []string{"/usr/bin/something"}},
|
||||
"checksums.txt is a symlink": {func(r *helperRig) {
|
||||
r.fs.putFile(outside+"/c", helperSentinel)
|
||||
delete(r.fs.nodes, helperStagedDir+"/checksums.txt")
|
||||
r.fs.putSymlink(helperStagedDir+"/checksums.txt", outside+"/c")
|
||||
}, helperStagedDir + "/checksums.txt", []string{outside + "/c"}},
|
||||
"checksums.txt.sig is a symlink": {func(r *helperRig) {
|
||||
r.fs.putFile(outside+"/s", helperSentinel)
|
||||
delete(r.fs.nodes, helperStagedDir+"/checksums.txt.sig")
|
||||
r.fs.putSymlink(helperStagedDir+"/checksums.txt.sig", outside+"/s")
|
||||
}, helperStagedDir + "/checksums.txt.sig", []string{outside + "/s"}},
|
||||
"a symlink is placed at the result path": {func(r *helperRig) {
|
||||
r.fs.putFile(outside+"/result-target", helperSentinel)
|
||||
r.fs.putSymlink(helperResult, outside+"/result-target")
|
||||
}, helperResult, []string{outside + "/result-target"}},
|
||||
"a symlink is placed at a temp file name": {func(r *helperRig) {
|
||||
r.fs.putFile(outside+"/tmp-target", helperSentinel)
|
||||
r.fs.putSymlink(helperResultTmp, outside+"/tmp-target")
|
||||
}, helperResultTmp, []string{outside + "/tmp-target"}},
|
||||
}
|
||||
for name, tc := range rows {
|
||||
t.Run("apply-update refuses symlinks: "+name, func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
tc.setup(rig)
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil || rig.result().Outcome != "failed" {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
rig.assertUntouched()
|
||||
rig.assertOutsideUntouched(tc.keep...)
|
||||
if !strings.Contains(rig.logger.text(), tc.link) {
|
||||
t.Errorf("the log must name %s: %s", tc.link, rig.logger.text())
|
||||
}
|
||||
if node := rig.fs.nodes[helperResult]; node == nil || node.kind != "file" {
|
||||
t.Error("the result must be a regular file written next to the link, not through it")
|
||||
}
|
||||
if len(rig.fs.touched("read", "copy")) > 0 {
|
||||
for _, operation := range rig.fs.touched("read", "copy") {
|
||||
if strings.HasPrefix(operation.resolved, outside) || strings.HasPrefix(operation.resolved, "/usr") {
|
||||
t.Errorf("read through a link: %+v", operation)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("A symlinked marker is removed, not followed", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.fs.putFile(outside+"/secret", helperSentinel)
|
||||
rig.fs.putSymlink(helperMarker, outside+"/secret")
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil || rig.fs.exists(helperMarker) || rig.result().Outcome != "failed" {
|
||||
t.Errorf("err = %v, marker present = %v", err, rig.fs.exists(helperMarker))
|
||||
}
|
||||
if content, _ := rig.fs.content(outside + "/secret"); content != helperSentinel {
|
||||
t.Error("the target must be intact")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a link found in the staged directory is unlinked, not followed, when cleaning", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
rig.fs.putFile(outside+"/tag/"+helperAsset, helperSentinel)
|
||||
rig.forget(helperStagedDir)
|
||||
rig.fs.putSymlink(helperStagedDir, outside+"/tag")
|
||||
|
||||
_ = rig.apply()
|
||||
|
||||
if rig.fs.exists(helperStagedDir) {
|
||||
t.Error("the link itself may be removed")
|
||||
}
|
||||
if content, _ := rig.fs.content(outside + "/tag/" + helperAsset); content != helperSentinel {
|
||||
t.Error("the target must be intact")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (r *helperRig) forget(prefix string) {
|
||||
for name := range r.fs.nodes {
|
||||
if name == prefix || strings.HasPrefix(name, prefix+"/") {
|
||||
delete(r.fs.nodes, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplySwapIsRaceFree(t *testing.T) {
|
||||
t.Run("A file swapped after verification is not installed", func(t *testing.T) {
|
||||
swapAfter := map[string]struct {
|
||||
operation string
|
||||
call int
|
||||
}{
|
||||
"the copy step": {"copy", 3},
|
||||
"the signature check": {"read", 2},
|
||||
"the hash check": {"read", 3},
|
||||
"the .previous copy": {"copy", 4},
|
||||
"the final copy and install": {"copy", 5},
|
||||
}
|
||||
for name, point := range swapAfter {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
rig.fs.after(point.operation, point.call, func(f *fakeHelperFS) {
|
||||
f.putFile(helperStagedDir+"/"+helperAsset, "attacker bytes")
|
||||
})
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rig.assertBinary(rig.newBinary)
|
||||
if rig.result().Outcome != "succeeded" {
|
||||
t.Errorf("result = %+v", rig.result())
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a swap of the temp file in the binary's directory before the rename is caught by the re-hash", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
rig.fs.after("copy", 5, func(f *fakeHelperFS) {
|
||||
f.putFile(helperBinary+".new", "attacker bytes in the temp file")
|
||||
})
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil || rig.result().Outcome != "failed" {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
rig.assertBinary("old")
|
||||
if rig.service.restartCount() != 0 || rig.fs.exists(helperBinary+".new") {
|
||||
t.Error("no restart and the temp file must be removed")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestApplyResultWrites(t *testing.T) {
|
||||
t.Run("Result and temp files are written without following links", func(t *testing.T) {
|
||||
files := newFakeHelperFS()
|
||||
files.putFile("/outside/a", helperSentinel)
|
||||
files.putFile("/outside/b", helperSentinel)
|
||||
files.putDir(helperData)
|
||||
files.putSymlink(helperResult, "/outside/a")
|
||||
files.putSymlink(helperResultTmp, "/outside/b")
|
||||
store := infraUpdate.NewFSResultStore(files, helperResult)
|
||||
|
||||
err := store.Write(update.Result{Outcome: update.OutcomeFailed, Kind: "update", StartedAt: restartBaseTime, FinishedAt: finishedAt(restartBaseTime)})
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a, _ := files.content("/outside/a"); a != helperSentinel {
|
||||
t.Error("the result link target must be untouched")
|
||||
}
|
||||
if b, _ := files.content("/outside/b"); b != helperSentinel {
|
||||
t.Error("the temp link target must be untouched")
|
||||
}
|
||||
if node := files.nodes[helperResult]; node == nil || node.kind != "file" || node.mode != 0o644 {
|
||||
t.Errorf("result node = %+v", node)
|
||||
}
|
||||
if got, found := store.Read(); !found || got.Outcome != update.OutcomeFailed {
|
||||
t.Errorf("read back = %+v, %v", got, found)
|
||||
}
|
||||
assertInOrder(t, files.eventsFrom(), "lstat", "remove", "create", "rename")
|
||||
})
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) eventsFrom() []string {
|
||||
names := make([]string, 0, len(f.ops))
|
||||
for _, operation := range f.ops {
|
||||
names = append(names, operation.name+" "+operation.path)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func TestApplyDistrustsTheMarker(t *testing.T) {
|
||||
tags := map[string]string{
|
||||
"../../etc/passwd": "../../etc/passwd",
|
||||
"v2.3.0-beta/../../x": "v2.3.0-beta/../../x",
|
||||
"an empty string": "",
|
||||
"v2.1.0-beta (older than the running)": "v2.1.0-beta",
|
||||
"not-a-version": "not-a-version",
|
||||
"the running version itself": helperOld,
|
||||
}
|
||||
for name, tag := range tags {
|
||||
t.Run("apply-update distrusts the marker: "+name, func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.fs.putFile("/var/lib/renewcms/etc/passwd", helperSentinel)
|
||||
rig.markUpdate(tag)
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil || rig.result().Outcome != "failed" {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
rig.assertUntouched()
|
||||
rig.assertOutsideUntouched()
|
||||
for _, operation := range rig.fs.ops {
|
||||
if strings.Contains(operation.path, "..") || strings.Contains(operation.path, "passwd") || strings.HasPrefix(operation.path, helperUpdatesDir) {
|
||||
t.Errorf("a distrusted tag reached the filesystem: %+v", operation)
|
||||
}
|
||||
}
|
||||
if !rig.fs.exists(helperStagedDir + "/" + helperAsset) {
|
||||
t.Error("staged files of another tag must be left alone")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyRollsBack(t *testing.T) {
|
||||
faults := map[string]func(*helperRig){
|
||||
"/healthz never answers within 60 s": func(r *helperRig) {
|
||||
r.health.healthy = false
|
||||
r.service.onRestart = func(call int) {
|
||||
if call == 2 {
|
||||
r.health.healthy = true
|
||||
}
|
||||
r.running.set(update.RunningInfo{Version: r.bootVersions[call-1], Pid: 200 + call, StartedAt: r.clock.Now().Add(time.Second)})
|
||||
}
|
||||
},
|
||||
"/healthz answers but update-running.json stays old": func(r *helperRig) {
|
||||
r.service.onRestart = func(call int) {
|
||||
if call == 2 {
|
||||
r.running.set(update.RunningInfo{Version: helperOld, Pid: 300, StartedAt: r.clock.Now().Add(time.Second)})
|
||||
}
|
||||
}
|
||||
},
|
||||
"update-running.json holds another version": func(r *helperRig) {
|
||||
r.service.onRestart = func(call int) {
|
||||
version := "v9.9.9"
|
||||
if call == 2 {
|
||||
version = helperOld
|
||||
}
|
||||
r.running.set(update.RunningInfo{Version: version, Pid: 200 + call, StartedAt: r.clock.Now().Add(time.Second)})
|
||||
}
|
||||
},
|
||||
"the service restart command fails": func(r *helperRig) {
|
||||
r.service.failOn[1] = errors.New("systemctl restart renewcms: exit status 1")
|
||||
},
|
||||
}
|
||||
for name, fault := range faults {
|
||||
t.Run("apply-update rolls back when the new version does not come up: "+name, func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
fault(rig)
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("a rollback that worked is not an error: %v", err)
|
||||
}
|
||||
rig.assertBinary("old")
|
||||
if rig.service.restartCount() != 2 {
|
||||
t.Fatalf("restarts = %d", rig.service.restartCount())
|
||||
}
|
||||
if name != "the service restart command fails" && rig.service.restarts[1].Sub(rig.service.restarts[0]) < update.RestartWindow {
|
||||
t.Errorf("rolled back after %v", rig.service.restarts[1].Sub(rig.service.restarts[0]))
|
||||
}
|
||||
assertInOrder(t, rig.events, "rename "+helperBinary+".new", "restart", "copy "+helperBinary+".previous", "rename "+helperBinary+".restore", "restart")
|
||||
result := rig.result()
|
||||
if result.Outcome != "rolled_back" || result.FromVersion != helperOld || result.Tag != downloadTag || result.FinishedAt == nil {
|
||||
t.Errorf("result = %+v", result)
|
||||
}
|
||||
rig.assertCleaned()
|
||||
if rig.fs.exists(helperBinary + ".restore") {
|
||||
t.Error("no restore temp file may be left")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplySwapFailures(t *testing.T) {
|
||||
t.Run("copying to .previous fails", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
rig.fs.failNth("copy", 4, errors.New("no space left on device"))
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil || rig.result().Outcome != "failed" {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
rig.assertUntouched()
|
||||
})
|
||||
|
||||
t.Run("the atomic install fails", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
rig.fs.failNth("rename", 3, errors.New("text file busy"))
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err != nil || rig.result().Outcome != "failed" || rig.service.restartCount() != 0 {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
rig.assertBinary("old")
|
||||
if previous, _ := rig.fs.content(helperBinary + ".previous"); previous != "old" {
|
||||
t.Errorf(".previous = %q", previous)
|
||||
}
|
||||
if rig.fs.exists(helperBinary + ".new") {
|
||||
t.Error("the temp file must be removed")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the rollback restore itself fails", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
rig.service.failOn[1] = errors.New("restart failed")
|
||||
rig.fs.failNth("copy", 6, errors.New("input/output error"))
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err == nil || rig.result().Outcome != "failed" || rig.service.restartCount() != 1 {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
if !strings.Contains(rig.logger.text(), "the site may be down") {
|
||||
t.Errorf("the failure must be logged loudly: %s", rig.logger.text())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the old version never returns after rollback", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
rig.service.onRestart = func(call int) {
|
||||
if call == 1 {
|
||||
rig.running.set(update.RunningInfo{Version: "v9.9.9", Pid: 201, StartedAt: rig.clock.Now().Add(time.Second)})
|
||||
}
|
||||
}
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
if err == nil || rig.result().Outcome != "failed" || rig.service.restartCount() != 2 {
|
||||
t.Errorf("err = %v, result = %+v", err, rig.result())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestApplyAlwaysWritesAResult(t *testing.T) {
|
||||
t.Run("a panic in the helper still leaves a failed result", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.stage()
|
||||
rig.markUpdate(downloadTag)
|
||||
rig.service.panicOn = 1
|
||||
|
||||
err := rig.apply()
|
||||
|
||||
result := rig.result()
|
||||
if err == nil || result.Outcome != "failed" || result.FinishedAt == nil || result.Kind != "update" || result.Tag != downloadTag || result.FromVersion != helperOld {
|
||||
t.Errorf("err = %v, result = %+v", err, result)
|
||||
}
|
||||
assertInOrder(t, rig.events, "create "+helperResultTmp, "rename "+helperResultTmp, "restart", "create "+helperResultTmp)
|
||||
})
|
||||
|
||||
t.Run("a running record exists before the first service call and every write is a temp file plus a rename", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.markRestart()
|
||||
var seenBeforeRestart []string
|
||||
rig.service.onRestart = func(call int) {
|
||||
seenBeforeRestart = append([]string(nil), rig.outcomes()...)
|
||||
rig.running.set(update.RunningInfo{Version: helperOld, Pid: 300, StartedAt: rig.clock.Now().Add(time.Second)})
|
||||
}
|
||||
|
||||
_ = rig.apply()
|
||||
|
||||
if len(seenBeforeRestart) != 1 || seenBeforeRestart[0] != "running" {
|
||||
t.Errorf("outcomes before the restart = %v", seenBeforeRestart)
|
||||
}
|
||||
creates := rig.fs.operationCount("create")
|
||||
renames := len(rig.fs.history[helperResult])
|
||||
if creates != renames || creates != 2 {
|
||||
t.Errorf("creates = %d, renames = %d", creates, renames)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("timestamps come from the clock and finished is not before started", func(t *testing.T) {
|
||||
rig := newHelperRig(t)
|
||||
rig.markRestart()
|
||||
rig.clock.onSleep = func(sleeps int) {
|
||||
if sleeps == 3 {
|
||||
rig.running.set(update.RunningInfo{Version: helperOld, Pid: 300, StartedAt: rig.clock.Now().Add(time.Second)})
|
||||
}
|
||||
}
|
||||
rig.service.onRestart = func(int) {}
|
||||
|
||||
if err := rig.apply(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result := rig.result()
|
||||
if !result.StartedAt.Equal(restartBaseTime) || result.FinishedAt == nil || !result.FinishedAt.Equal(restartBaseTime.Add(3*time.Second)) || result.FinishedAt.Before(result.StartedAt) {
|
||||
t.Errorf("result = %+v", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/api"
|
||||
"RenewCMS/api/middleware"
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
"RenewCMS/internal/domain/update"
|
||||
"RenewCMS/internal/domain/user"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sort"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
)
|
||||
|
||||
const (
|
||||
updateOwnerId = 1
|
||||
updateAdminId = 2
|
||||
updateUnverifiedId = 3
|
||||
updateSecondOwner = 4
|
||||
updateUnverifiedOwner = 5
|
||||
updateRunning = "v2.2.0-beta"
|
||||
)
|
||||
|
||||
var updateStatusKeys = []string{"available", "can_apply", "checked_at", "current", "error", "finished_at", "latest", "notes", "progress", "release_url", "started_at", "state"}
|
||||
|
||||
type updateHarness struct {
|
||||
router http.Handler
|
||||
token *jwtauth.JWTAuth
|
||||
feed *fakeReleaseFeed
|
||||
store *fakeUpdateStore
|
||||
}
|
||||
|
||||
func newUpdateUserRepo() *mockUserRepo {
|
||||
users := newMockUserRepo()
|
||||
users.users[updateOwnerId] = user.User{ID: updateOwnerId, IsVerified: true, Role: user.RoleOwner, TokenVersion: 2}
|
||||
users.users[updateAdminId] = user.User{ID: updateAdminId, IsVerified: true, Role: user.RoleAdmin}
|
||||
users.users[updateUnverifiedId] = user.User{ID: updateUnverifiedId, IsVerified: false, Role: user.RoleAdmin}
|
||||
users.users[updateSecondOwner] = user.User{ID: updateSecondOwner, IsVerified: true, Role: user.RoleOwner}
|
||||
users.users[updateUnverifiedOwner] = user.User{ID: updateUnverifiedOwner, IsVerified: false, Role: user.RoleOwner}
|
||||
return users
|
||||
}
|
||||
|
||||
func newUpdateHarness(t *testing.T, running string) *updateHarness {
|
||||
t.Helper()
|
||||
validator.InitValidator()
|
||||
users := newUpdateUserRepo()
|
||||
feed := &fakeReleaseFeed{release: update.Release{
|
||||
Tag: "v2.3.0-beta",
|
||||
URL: "https://git.example/fsylvain/RenewCMS/releases/tag/v2.3.0-beta",
|
||||
PublishedAt: time.Date(2026, 9, 24, 8, 0, 0, 0, time.UTC),
|
||||
Notes: update.ReleaseNotes{Version: "v2.3.0-beta", Items: []string{"Media library"}},
|
||||
}}
|
||||
store := &fakeUpdateStore{}
|
||||
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||
now := func() time.Time { return updateTestCheckedAt }
|
||||
container := &api.UseCases{
|
||||
Token: token,
|
||||
GetUserUseCase: useCases.NewGetUserUseCase(users),
|
||||
GetUpdateStatusUseCase: newUpdateStatusUseCase(store, &fakeJobStore{}, &fakeHelperDetector{}, running),
|
||||
CheckForUpdateUseCase: useCases.NewCheckForUpdateUseCase(feed, store, running, now),
|
||||
}
|
||||
return &updateHarness{router: api.NewSystemRouter(container), token: token, feed: feed, store: store}
|
||||
}
|
||||
|
||||
func (h *updateHarness) send(t *testing.T, method, path string, userId uint32, tokenVersion uint32) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, nil)
|
||||
if userId != 0 {
|
||||
_, tokenString, err := h.token.Encode(map[string]any{"user_id": userId, "token_version": tokenVersion})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.router.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func (h *updateHarness) sendAs(t *testing.T, method, path string, userId uint32) *httptest.ResponseRecorder {
|
||||
tokenVersion := uint32(0)
|
||||
if userId == updateOwnerId {
|
||||
tokenVersion = 2
|
||||
}
|
||||
return h.send(t, method, path, userId, tokenVersion)
|
||||
}
|
||||
|
||||
func decodeUpdateBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
|
||||
t.Helper()
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("body is not json: %v: %s", err, rec.Body.String())
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func assertUpdateKeys(t *testing.T, body map[string]any) {
|
||||
t.Helper()
|
||||
keys := make([]string, 0, len(body))
|
||||
for key := range body {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
if len(keys) != len(updateStatusKeys) {
|
||||
t.Fatalf("keys = %v, want %v", keys, updateStatusKeys)
|
||||
}
|
||||
for i := range keys {
|
||||
if keys[i] != updateStatusKeys[i] {
|
||||
t.Fatalf("keys = %v, want %v", keys, updateStatusKeys)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateStatusHTTP(t *testing.T) {
|
||||
t.Run("GET returns the idle shape, never applicable", func(t *testing.T) {
|
||||
h := newUpdateHarness(t, updateRunning)
|
||||
h.store.result = newStoredUpdateResult()
|
||||
h.store.found = true
|
||||
|
||||
rec := h.sendAs(t, http.MethodGet, "/update", updateOwnerId)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
body := decodeUpdateBody(t, rec)
|
||||
assertUpdateKeys(t, body)
|
||||
if body["current"] != updateRunning || body["latest"] != "v2.3.0-beta" || body["available"] != true || body["can_apply"] != false || body["state"] != "idle" {
|
||||
t.Errorf("body = %v", body)
|
||||
}
|
||||
if body["release_url"] != h.store.result.ReleaseURL || body["checked_at"] != "2026-09-30T09:41:00Z" {
|
||||
t.Errorf("release_url = %v, checked_at = %v", body["release_url"], body["checked_at"])
|
||||
}
|
||||
if body["progress"] != nil || body["error"] != nil || body["started_at"] != nil || body["finished_at"] != nil {
|
||||
t.Errorf("progress, error, started_at and finished_at must be null: %v", body)
|
||||
}
|
||||
notes := body["notes"].(map[string]any)
|
||||
if notes["version"] != "v2.3.0-beta" || len(notes["items"].([]any)) != 1 || notes["released_at"] != "2026-09-24T08:00:00Z" {
|
||||
t.Errorf("notes = %v", notes)
|
||||
}
|
||||
if h.feed.calls != 0 {
|
||||
t.Errorf("feed calls = %d", h.feed.calls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GET before any check", func(t *testing.T) {
|
||||
h := newUpdateHarness(t, updateRunning)
|
||||
|
||||
rec := h.sendAs(t, http.MethodGet, "/update", updateOwnerId)
|
||||
|
||||
body := decodeUpdateBody(t, rec)
|
||||
assertUpdateKeys(t, body)
|
||||
if rec.Code != http.StatusOK || body["available"] != false || body["latest"] != "" || body["state"] != "idle" {
|
||||
t.Errorf("status = %d body = %v", rec.Code, body)
|
||||
}
|
||||
for _, key := range []string{"release_url", "notes", "checked_at", "progress", "error", "started_at", "finished_at"} {
|
||||
if body[key] != nil {
|
||||
t.Errorf("%s = %v, want null", key, body[key])
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
for name, userId := range map[string]uint32{"owner": updateOwnerId, "admin": updateAdminId} {
|
||||
t.Run("GET is open to any verified user: "+name, func(t *testing.T) {
|
||||
rec := newUpdateHarness(t, updateRunning).sendAs(t, http.MethodGet, "/update", userId)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("status = %d", rec.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("GET without a cookie", func(t *testing.T) {
|
||||
rec := newUpdateHarness(t, updateRunning).send(t, http.MethodGet, "/update", 0, 0)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("status = %d", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GET with a stale token", func(t *testing.T) {
|
||||
rec := newUpdateHarness(t, updateRunning).send(t, http.MethodGet, "/update", updateOwnerId, 1)
|
||||
if rec.Code != http.StatusUnauthorized || rec.Body.String() != apperr.UnauthorizedErrorMessage+"\n" {
|
||||
t.Errorf("status = %d body = %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("GET by an unverified account", func(t *testing.T) {
|
||||
rec := newUpdateHarness(t, updateRunning).sendAs(t, http.MethodGet, "/update", updateUnverifiedId)
|
||||
if rec.Code != http.StatusForbidden || rec.Body.String() != apperr.VerificationRequiredErrorMessage+"\n" {
|
||||
t.Errorf("status = %d body = %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestUpdateCheckHTTP(t *testing.T) {
|
||||
t.Run("The owner checks and the result is stored", func(t *testing.T) {
|
||||
h := newUpdateHarness(t, updateRunning)
|
||||
|
||||
rec := h.sendAs(t, http.MethodPost, "/update/check", updateOwnerId)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
body := decodeUpdateBody(t, rec)
|
||||
assertUpdateKeys(t, body)
|
||||
if body["available"] != true || body["latest"] != "v2.3.0-beta" || body["checked_at"] != "2026-09-30T09:41:00Z" {
|
||||
t.Errorf("body = %v", body)
|
||||
}
|
||||
if h.store.result.Latest != "v2.3.0-beta" || !h.store.result.CheckedAt.Equal(updateTestCheckedAt) {
|
||||
t.Errorf("stored = %+v", h.store.result)
|
||||
}
|
||||
later := h.sendAs(t, http.MethodGet, "/update", updateOwnerId)
|
||||
if later.Body.String() != rec.Body.String() {
|
||||
t.Errorf("later GET = %s, check = %s", later.Body.String(), rec.Body.String())
|
||||
}
|
||||
if h.feed.calls != 1 {
|
||||
t.Errorf("feed calls = %d", h.feed.calls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A check with nothing newer", func(t *testing.T) {
|
||||
h := newUpdateHarness(t, "v2.3.0-beta")
|
||||
rec := h.sendAs(t, http.MethodPost, "/update/check", updateOwnerId)
|
||||
if rec.Code != http.StatusOK || decodeUpdateBody(t, rec)["available"] != false {
|
||||
t.Errorf("status = %d body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A dev build never reports an update", func(t *testing.T) {
|
||||
h := newUpdateHarness(t, "dev")
|
||||
h.feed.release.Tag = "v9.9.9"
|
||||
rec := h.sendAs(t, http.MethodPost, "/update/check", updateOwnerId)
|
||||
if rec.Code != http.StatusOK || decodeUpdateBody(t, rec)["available"] != false {
|
||||
t.Errorf("status = %d body = %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("An admin cannot check", func(t *testing.T) {
|
||||
h := newUpdateHarness(t, updateRunning)
|
||||
rec := h.sendAs(t, http.MethodPost, "/update/check", updateAdminId)
|
||||
if rec.Code != http.StatusForbidden || rec.Body.String() != apperr.OwnerRequiredErrorMessage+"\n" {
|
||||
t.Errorf("status = %d body = %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if h.feed.calls != 0 {
|
||||
t.Errorf("feed calls = %d", h.feed.calls)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A check without a cookie is unauthorized", func(t *testing.T) {
|
||||
h := newUpdateHarness(t, updateRunning)
|
||||
if rec := h.send(t, http.MethodPost, "/update/check", 0, 0); rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("status = %d", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Feed failure keeps the last result", func(t *testing.T) {
|
||||
h := newUpdateHarness(t, updateRunning)
|
||||
h.store.result = newStoredUpdateResult()
|
||||
h.store.found = true
|
||||
h.feed.err = update.ErrFeedUnavailable
|
||||
|
||||
rec := h.sendAs(t, http.MethodPost, "/update/check", updateOwnerId)
|
||||
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Errorf("status = %d", rec.Code)
|
||||
}
|
||||
if h.store.result.Latest != "v2.3.0-beta" || !h.store.result.CheckedAt.Equal(updateTestCheckedAt) || h.store.saves != 0 {
|
||||
t.Errorf("store changed: %+v", h.store.result)
|
||||
}
|
||||
if body := rec.Body.String(); body != "Internal server error\n" {
|
||||
t.Errorf("body leaks detail: %q", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Check is rate limited per user", func(t *testing.T) {
|
||||
h := newUpdateHarness(t, updateRunning)
|
||||
loginLimited := middleware.NewRateLimiter(5, time.Minute)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {}))
|
||||
var codes []int
|
||||
var last *httptest.ResponseRecorder
|
||||
for i := 0; i < 6; i++ {
|
||||
last = h.sendAs(t, http.MethodPost, "/update/check", updateOwnerId)
|
||||
codes = append(codes, last.Code)
|
||||
}
|
||||
|
||||
for i, code := range codes[:5] {
|
||||
if code != http.StatusOK {
|
||||
t.Errorf("check %d status = %d", i+1, code)
|
||||
}
|
||||
}
|
||||
if codes[5] != http.StatusTooManyRequests || last.Body.String() != apperr.TooManyRequestsErrorMessage+"\n" {
|
||||
t.Fatalf("6th status = %d body = %q", codes[5], last.Body.String())
|
||||
}
|
||||
if seconds, err := strconv.Atoi(last.Header().Get("Retry-After")); err != nil || seconds < 1 {
|
||||
t.Errorf("Retry-After = %q", last.Header().Get("Retry-After"))
|
||||
}
|
||||
if h.feed.calls != 5 {
|
||||
t.Errorf("feed calls = %d", h.feed.calls)
|
||||
}
|
||||
if other := h.sendAs(t, http.MethodPost, "/update/check", updateSecondOwner); other.Code != http.StatusOK {
|
||||
t.Errorf("another owner status = %d", other.Code)
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
rec := httptest.NewRecorder()
|
||||
loginLimited.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/login", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("auth limiter request %d status = %d", i+1, rec.Code)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
@@ -0,0 +1,592 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newUpdateStatusUseCase(store update.StatusStore, jobs update.JobStore, helper update.HelperDetector, running string) *useCases.GetUpdateStatusUseCase {
|
||||
return useCases.NewGetUpdateStatusUseCase(store, jobs, helper, &fakeResultStore{}, &fakeRestartRequestStore{}, running, time.Now)
|
||||
}
|
||||
|
||||
type fakeRestartRequestStore struct {
|
||||
mu sync.Mutex
|
||||
request update.RestartRequest
|
||||
present bool
|
||||
corrupt bool
|
||||
writeErr error
|
||||
writes int
|
||||
deletes int
|
||||
}
|
||||
|
||||
var _ update.RestartRequestStore = &fakeRestartRequestStore{}
|
||||
|
||||
func (f *fakeRestartRequestStore) Write(request update.RestartRequest) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.writeErr != nil {
|
||||
return f.writeErr
|
||||
}
|
||||
f.request = request
|
||||
f.present = true
|
||||
f.writes++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeRestartRequestStore) Read() (update.RestartRequest, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.corrupt {
|
||||
return update.RestartRequest{}, errors.New("corrupt marker")
|
||||
}
|
||||
if !f.present {
|
||||
return update.RestartRequest{}, update.ErrNoRestartRequest
|
||||
}
|
||||
return f.request, nil
|
||||
}
|
||||
|
||||
func (f *fakeRestartRequestStore) Delete() error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.present = false
|
||||
f.deletes++
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeResultStore struct {
|
||||
mu sync.Mutex
|
||||
result update.Result
|
||||
found bool
|
||||
writeErr error
|
||||
writes []update.Result
|
||||
deletes int
|
||||
}
|
||||
|
||||
var _ update.ResultStore = &fakeResultStore{}
|
||||
|
||||
func (f *fakeResultStore) Read() (update.Result, bool) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.result, f.found
|
||||
}
|
||||
|
||||
func (f *fakeResultStore) Write(result update.Result) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.writeErr != nil {
|
||||
return f.writeErr
|
||||
}
|
||||
f.result = result
|
||||
f.found = true
|
||||
f.writes = append(f.writes, result)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeResultStore) Delete() error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.found = false
|
||||
f.result = update.Result{}
|
||||
f.deletes++
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeRunningInfoStore struct {
|
||||
mu sync.Mutex
|
||||
info update.RunningInfo
|
||||
found bool
|
||||
writeErr error
|
||||
writes []update.RunningInfo
|
||||
}
|
||||
|
||||
var _ update.RunningInfoStore = &fakeRunningInfoStore{}
|
||||
|
||||
func (f *fakeRunningInfoStore) Write(info update.RunningInfo) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.writeErr != nil {
|
||||
return f.writeErr
|
||||
}
|
||||
f.info = info
|
||||
f.found = true
|
||||
f.writes = append(f.writes, info)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeRunningInfoStore) Read() (update.RunningInfo, bool) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.info, f.found
|
||||
}
|
||||
|
||||
func (f *fakeRunningInfoStore) set(info update.RunningInfo) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.info = info
|
||||
f.found = true
|
||||
}
|
||||
|
||||
func (f *fakeRunningInfoStore) unreadable() {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.info = update.RunningInfo{}
|
||||
f.found = false
|
||||
}
|
||||
|
||||
type fakeClock struct {
|
||||
mu sync.Mutex
|
||||
now time.Time
|
||||
sleeps int
|
||||
onSleep func(sleeps int)
|
||||
}
|
||||
|
||||
var _ update.Clock = &fakeClock{}
|
||||
|
||||
func (f *fakeClock) Now() time.Time {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.now
|
||||
}
|
||||
|
||||
func (f *fakeClock) Sleep(duration time.Duration) {
|
||||
f.mu.Lock()
|
||||
f.now = f.now.Add(duration)
|
||||
f.sleeps++
|
||||
sleeps, hook := f.sleeps, f.onSleep
|
||||
f.mu.Unlock()
|
||||
if hook != nil {
|
||||
hook(sleeps)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeClock) advance(duration time.Duration) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.now = f.now.Add(duration)
|
||||
}
|
||||
|
||||
type fakeServiceControl struct {
|
||||
mu sync.Mutex
|
||||
restarts []time.Time
|
||||
clock *fakeClock
|
||||
failOn map[int]error
|
||||
panicOn int
|
||||
onRestart func(call int)
|
||||
events *[]string
|
||||
}
|
||||
|
||||
var _ update.ServiceControl = &fakeServiceControl{}
|
||||
|
||||
func (f *fakeServiceControl) Restart() error {
|
||||
f.mu.Lock()
|
||||
f.restarts = append(f.restarts, f.clock.Now())
|
||||
call := len(f.restarts)
|
||||
failure := f.failOn[call]
|
||||
shouldPanic := f.panicOn == call
|
||||
hook := f.onRestart
|
||||
f.mu.Unlock()
|
||||
if f.events != nil {
|
||||
*f.events = append(*f.events, "restart")
|
||||
}
|
||||
if shouldPanic {
|
||||
panic("service control exploded")
|
||||
}
|
||||
if failure != nil {
|
||||
return failure
|
||||
}
|
||||
if hook != nil {
|
||||
hook(call)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeServiceControl) Status() (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (f *fakeServiceControl) restartCount() int {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return len(f.restarts)
|
||||
}
|
||||
|
||||
type fakeHealthChecker struct {
|
||||
mu sync.Mutex
|
||||
healthy bool
|
||||
asked int
|
||||
}
|
||||
|
||||
var _ update.HealthChecker = &fakeHealthChecker{}
|
||||
|
||||
func (f *fakeHealthChecker) Healthy() bool {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.asked++
|
||||
return f.healthy
|
||||
}
|
||||
|
||||
type fsNode struct {
|
||||
kind string
|
||||
content []byte
|
||||
mode uint32
|
||||
target string
|
||||
owner string
|
||||
}
|
||||
|
||||
type fsOperation struct {
|
||||
name string
|
||||
path string
|
||||
resolved string
|
||||
}
|
||||
|
||||
var errFakeLoop = errors.New("too many levels of symbolic links")
|
||||
|
||||
type fakeHelperFS struct {
|
||||
mu sync.Mutex
|
||||
nodes map[string]*fsNode
|
||||
ops []fsOperation
|
||||
counts map[string]int
|
||||
failures map[string]map[int]error
|
||||
hooks map[string]map[int]func(*fakeHelperFS)
|
||||
tempDirs int
|
||||
events *[]string
|
||||
history map[string][]string
|
||||
}
|
||||
|
||||
var _ update.HelperFilesystem = &fakeHelperFS{}
|
||||
|
||||
func newFakeHelperFS() *fakeHelperFS {
|
||||
f := &fakeHelperFS{
|
||||
nodes: map[string]*fsNode{"/": {kind: "dir", mode: 0o755, owner: "root"}},
|
||||
counts: map[string]int{},
|
||||
failures: map[string]map[int]error{},
|
||||
hooks: map[string]map[int]func(*fakeHelperFS){},
|
||||
history: map[string][]string{},
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) failNth(operation string, call int, err error) {
|
||||
if f.failures[operation] == nil {
|
||||
f.failures[operation] = map[int]error{}
|
||||
}
|
||||
f.failures[operation][call] = err
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) after(operation string, call int, mutate func(*fakeHelperFS)) {
|
||||
if f.hooks[operation] == nil {
|
||||
f.hooks[operation] = map[int]func(*fakeHelperFS){}
|
||||
}
|
||||
f.hooks[operation][call] = mutate
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) putDir(target string) {
|
||||
target = path.Clean(target)
|
||||
for current := target; current != "/"; current = path.Dir(current) {
|
||||
if _, found := f.nodes[current]; !found {
|
||||
f.nodes[current] = &fsNode{kind: "dir", mode: 0o755, owner: "app"}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) putFile(target string, content string) {
|
||||
target = path.Clean(target)
|
||||
f.putDir(path.Dir(target))
|
||||
f.nodes[target] = &fsNode{kind: "file", content: []byte(content), mode: 0o644, owner: "app"}
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) putSymlink(target string, destination string) {
|
||||
target = path.Clean(target)
|
||||
f.putDir(path.Dir(target))
|
||||
f.nodes[target] = &fsNode{kind: "symlink", target: destination, owner: "app"}
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) content(target string) (string, bool) {
|
||||
node, found := f.nodes[path.Clean(target)]
|
||||
if !found || node.kind != "file" {
|
||||
return "", false
|
||||
}
|
||||
return string(node.content), true
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) exists(target string) bool {
|
||||
_, found := f.nodes[path.Clean(target)]
|
||||
return found
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) mode(target string) uint32 {
|
||||
if node, found := f.nodes[path.Clean(target)]; found {
|
||||
return node.mode
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) resolve(target string, followFinal bool) (string, error) {
|
||||
return f.resolveDepth(path.Clean(target), followFinal, 0)
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) resolveDepth(target string, followFinal bool, depth int) (string, error) {
|
||||
if depth > 8 {
|
||||
return "", errFakeLoop
|
||||
}
|
||||
parts := strings.Split(strings.Trim(target, "/"), "/")
|
||||
current := "/"
|
||||
for index, part := range parts {
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
next := path.Join(current, part)
|
||||
node, found := f.nodes[next]
|
||||
last := index == len(parts)-1
|
||||
if found && node.kind == "symlink" && (!last || followFinal) {
|
||||
resolved, err := f.resolveDepth(node.target, true, depth+1)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
current = resolved
|
||||
continue
|
||||
}
|
||||
current = next
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) begin(operation string, target string, followFinal bool) (string, error) {
|
||||
f.counts[operation]++
|
||||
resolved, err := f.resolve(target, followFinal)
|
||||
f.ops = append(f.ops, fsOperation{name: operation, path: target, resolved: resolved})
|
||||
if f.events != nil {
|
||||
*f.events = append(*f.events, operation+" "+target)
|
||||
}
|
||||
if failure := f.failures[operation][f.counts[operation]]; failure != nil {
|
||||
return resolved, failure
|
||||
}
|
||||
return resolved, err
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) end(operation string) {
|
||||
if hook := f.hooks[operation][f.counts[operation]]; hook != nil {
|
||||
hook(f)
|
||||
}
|
||||
}
|
||||
|
||||
func missing(operation string, target string) error {
|
||||
return &fs.PathError{Op: operation, Path: target, Err: fs.ErrNotExist}
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) Lstat(target string) (update.FileInfo, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
defer f.end("lstat")
|
||||
resolved, err := f.begin("lstat", target, false)
|
||||
if err != nil {
|
||||
return update.FileInfo{}, err
|
||||
}
|
||||
node, found := f.nodes[resolved]
|
||||
if !found {
|
||||
return update.FileInfo{}, missing("lstat", target)
|
||||
}
|
||||
return update.FileInfo{IsSymlink: node.kind == "symlink", IsDir: node.kind == "dir", IsRegular: node.kind == "file"}, nil
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) ReadFile(target string) ([]byte, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
defer f.end("read")
|
||||
resolved, err := f.begin("read", target, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
node, found := f.nodes[resolved]
|
||||
if !found {
|
||||
return nil, missing("read", target)
|
||||
}
|
||||
if node.kind == "symlink" {
|
||||
return nil, errFakeLoop
|
||||
}
|
||||
if node.kind != "file" {
|
||||
return nil, errors.New("is a directory")
|
||||
}
|
||||
return append([]byte(nil), node.content...), nil
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) createNode(operation string, target string, content []byte, mode uint32) error {
|
||||
resolved, err := f.begin(operation, target, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, found := f.nodes[resolved]; found {
|
||||
return &fs.PathError{Op: operation, Path: target, Err: fs.ErrExist}
|
||||
}
|
||||
parent, found := f.nodes[path.Dir(resolved)]
|
||||
if !found || parent.kind != "dir" {
|
||||
return missing(operation, target)
|
||||
}
|
||||
f.nodes[resolved] = &fsNode{kind: "file", content: content, mode: mode, owner: "root"}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) CreateExclusive(target string, content []byte, mode uint32) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
defer f.end("create")
|
||||
return f.createNode("create", target, append([]byte(nil), content...), mode)
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) Copy(source string, destination string, mode uint32) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
defer f.end("copy")
|
||||
resolved, err := f.begin("copy", source, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
node, found := f.nodes[resolved]
|
||||
if !found {
|
||||
return missing("copy", source)
|
||||
}
|
||||
if node.kind == "symlink" {
|
||||
return errFakeLoop
|
||||
}
|
||||
if node.kind != "file" {
|
||||
return errors.New("not a regular file")
|
||||
}
|
||||
f.ops = append(f.ops, fsOperation{name: "copy-to", path: destination})
|
||||
return f.createNode("copy-to", destination, append([]byte(nil), node.content...), mode)
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) Rename(oldPath string, newPath string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
defer f.end("rename")
|
||||
from, err := f.begin("rename", oldPath, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
to, err := f.resolve(newPath, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
node, found := f.nodes[from]
|
||||
if !found {
|
||||
return missing("rename", oldPath)
|
||||
}
|
||||
if existing, found := f.nodes[to]; found && existing.kind == "dir" {
|
||||
return errors.New("is a directory")
|
||||
}
|
||||
f.ops = append(f.ops, fsOperation{name: "rename-to", path: newPath, resolved: to})
|
||||
f.nodes[to] = node
|
||||
delete(f.nodes, from)
|
||||
f.history[to] = append(f.history[to], string(node.content))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) Remove(target string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
defer f.end("remove")
|
||||
resolved, err := f.begin("remove", target, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, found := f.nodes[resolved]; !found {
|
||||
return missing("remove", target)
|
||||
}
|
||||
delete(f.nodes, resolved)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) RemoveAll(target string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
defer f.end("removeall")
|
||||
resolved, err := f.begin("removeall", target, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
prefix := resolved + "/"
|
||||
for name := range f.nodes {
|
||||
if name == resolved || strings.HasPrefix(name, prefix) {
|
||||
delete(f.nodes, name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) Chmod(target string, mode uint32) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
defer f.end("chmod")
|
||||
resolved, err := f.begin("chmod", target, false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
node, found := f.nodes[resolved]
|
||||
if !found {
|
||||
return missing("chmod", target)
|
||||
}
|
||||
if node.kind == "symlink" {
|
||||
return errFakeLoop
|
||||
}
|
||||
node.mode = mode
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) MakePrivateTempDir() (string, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
defer f.end("tempdir")
|
||||
f.tempDirs++
|
||||
directory := "/tmp/renewcms-update-" + string(rune('0'+f.tempDirs))
|
||||
if _, err := f.begin("tempdir", directory, false); err != nil {
|
||||
return "", err
|
||||
}
|
||||
f.nodes["/tmp"] = &fsNode{kind: "dir", mode: 0o1777, owner: "root"}
|
||||
f.nodes[directory] = &fsNode{kind: "dir", mode: 0o700, owner: "root"}
|
||||
return directory, nil
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) touched(operations ...string) []fsOperation {
|
||||
wanted := map[string]bool{}
|
||||
for _, name := range operations {
|
||||
wanted[name] = true
|
||||
}
|
||||
var touched []fsOperation
|
||||
for _, operation := range f.ops {
|
||||
if wanted[operation.name] {
|
||||
touched = append(touched, operation)
|
||||
}
|
||||
}
|
||||
return touched
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) resolvedOutside(allowed ...string) []string {
|
||||
var outside []string
|
||||
for _, operation := range f.ops {
|
||||
if operation.resolved == "" {
|
||||
continue
|
||||
}
|
||||
inside := false
|
||||
for _, directory := range allowed {
|
||||
if operation.resolved == directory || strings.HasPrefix(operation.resolved, directory+"/") {
|
||||
inside = true
|
||||
}
|
||||
}
|
||||
if !inside {
|
||||
outside = append(outside, operation.name+" "+operation.resolved)
|
||||
}
|
||||
}
|
||||
sort.Strings(outside)
|
||||
return outside
|
||||
}
|
||||
|
||||
func (f *fakeHelperFS) operationCount(name string) int {
|
||||
return f.counts[name]
|
||||
}
|
||||
@@ -0,0 +1,623 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/api"
|
||||
"RenewCMS/api/pkg/apperr"
|
||||
validator "RenewCMS/api/pkg/validator"
|
||||
"RenewCMS/internal/domain/update"
|
||||
"RenewCMS/internal/infrastructure/config"
|
||||
infraUpdate "RenewCMS/internal/infrastructure/update"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
)
|
||||
|
||||
const restartPath = "/update/restart"
|
||||
|
||||
type restartHTTP struct {
|
||||
router http.Handler
|
||||
token *jwtauth.JWTAuth
|
||||
dataDir string
|
||||
markerPath string
|
||||
resultPath string
|
||||
store *fakeUpdateStore
|
||||
jobs *fakeJobStore
|
||||
helper *fakeHelperDetector
|
||||
clock *fakeClock
|
||||
markers update.RestartRequestStore
|
||||
resultFiles update.ResultStore
|
||||
}
|
||||
|
||||
func newRestartHTTP(t *testing.T) *restartHTTP {
|
||||
t.Helper()
|
||||
validator.InitValidator()
|
||||
dataDir := t.TempDir()
|
||||
h := &restartHTTP{
|
||||
token: jwtauth.New("HS256", []byte("test-secret"), nil),
|
||||
dataDir: dataDir,
|
||||
markerPath: filepath.Join(dataDir, update.RestartRequestFileName),
|
||||
resultPath: filepath.Join(dataDir, update.ResultFileName),
|
||||
store: &fakeUpdateStore{result: newStoredUpdateResult(), found: true},
|
||||
jobs: &fakeJobStore{},
|
||||
helper: &fakeHelperDetector{installed: true},
|
||||
clock: &fakeClock{now: restartBaseTime},
|
||||
}
|
||||
h.markers = infraUpdate.NewJSONRestartRequestStore(h.markerPath)
|
||||
h.resultFiles = infraUpdate.NewJSONResultStore(h.resultPath)
|
||||
container := &api.UseCases{
|
||||
Token: h.token,
|
||||
GetUserUseCase: useCases.NewGetUserUseCase(newUpdateUserRepo()),
|
||||
GetUpdateStatusUseCase: useCases.NewGetUpdateStatusUseCase(
|
||||
h.store, h.jobs, h.helper, h.resultFiles, h.markers, updateRunning, h.clock.Now),
|
||||
RequestRestartUseCase: useCases.NewRequestRestartUseCase(
|
||||
h.store, h.jobs, h.helper, h.resultFiles, h.markers, updateRunning, h.clock.Now),
|
||||
}
|
||||
h.router = api.NewSystemRouter(container)
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *restartHTTP) readyJob() {
|
||||
h.jobs.put(update.Job{Tag: downloadTag, State: update.StateReady, StartedAt: restartBaseTime.Add(-time.Hour)})
|
||||
}
|
||||
|
||||
func (h *restartHTTP) post(t *testing.T, userId uint32, tokenVersion uint32, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return h.request(t, http.MethodPost, restartPath, userId, tokenVersion, body)
|
||||
}
|
||||
|
||||
func (h *restartHTTP) postAsOwner(t *testing.T, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
return h.post(t, updateOwnerId, 2, body)
|
||||
}
|
||||
|
||||
func (h *restartHTTP) request(t *testing.T, method string, target string, userId uint32, tokenVersion uint32, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, target, strings.NewReader(body))
|
||||
if userId != 0 {
|
||||
_, tokenString, err := h.token.Encode(map[string]any{"user_id": userId, "token_version": tokenVersion})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.router.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func (h *restartHTTP) getAs(t *testing.T, userId uint32) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
tokenVersion := uint32(0)
|
||||
if userId == updateOwnerId {
|
||||
tokenVersion = 2
|
||||
}
|
||||
return h.request(t, http.MethodGet, "/update", userId, tokenVersion, "")
|
||||
}
|
||||
|
||||
func (h *restartHTTP) markerBytes() ([]byte, bool) {
|
||||
content, err := os.ReadFile(h.markerPath)
|
||||
return content, err == nil
|
||||
}
|
||||
|
||||
func (h *restartHTTP) seedResult(t *testing.T, result update.Result) {
|
||||
t.Helper()
|
||||
if err := h.resultFiles.Write(result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *restartHTTP) assertNoMarkerAndResultKept(t *testing.T, resultKept bool) {
|
||||
t.Helper()
|
||||
if _, found := h.markerBytes(); found {
|
||||
t.Error("no marker may be written")
|
||||
}
|
||||
if _, found := h.resultFiles.Read(); found != resultKept {
|
||||
t.Errorf("result present = %v, want %v", found, resultKept)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestartHTTP(t *testing.T) {
|
||||
t.Run("Request an update restart, happy path", func(t *testing.T) {
|
||||
for name, body := range map[string]string{"no body": "", "kind update": `{"kind":"update"}`} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
h := newRestartHTTP(t)
|
||||
h.readyJob()
|
||||
h.seedResult(t, update.Result{Outcome: update.OutcomeRolledBack, Kind: update.RestartKindUpdate, Tag: downloadTag, StartedAt: restartBaseTime.Add(-time.Hour), FinishedAt: finishedAt(restartBaseTime.Add(-time.Hour))})
|
||||
|
||||
rec := h.postAsOwner(t, body)
|
||||
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
status := decodeUpdateBody(t, rec)
|
||||
assertUpdateKeys(t, status)
|
||||
if status["state"] != "restarting" || status["started_at"] != "2026-09-30T09:50:00Z" || status["error"] != nil || status["finished_at"] != nil {
|
||||
t.Errorf("status = %v", status)
|
||||
}
|
||||
marker, err := h.markers.Read()
|
||||
if err != nil || marker.Kind != "update" || marker.Tag != downloadTag || marker.RequestedBy != updateOwnerId || !marker.RequestedAt.Equal(restartBaseTime) {
|
||||
t.Errorf("marker = %+v, err = %v", marker, err)
|
||||
}
|
||||
if _, found := h.resultFiles.Read(); found {
|
||||
t.Error("update-result.json must be deleted first")
|
||||
}
|
||||
entries, _ := os.ReadDir(h.dataDir)
|
||||
if len(entries) != 1 {
|
||||
t.Errorf("only the marker may exist in the data directory, got %d entries", len(entries))
|
||||
}
|
||||
asAdmin := decodeUpdateBody(t, h.getAs(t, updateAdminId))
|
||||
if asAdmin["state"] != "restarting" || asAdmin["can_apply"] != false {
|
||||
t.Errorf("admin view = %v", asAdmin)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Request a plain restart", func(t *testing.T) {
|
||||
for name, body := range map[string]string{"no body": "", "kind restart": `{"kind":"restart"}`, "empty object": `{}`} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
h := newRestartHTTP(t)
|
||||
|
||||
rec := h.postAsOwner(t, body)
|
||||
|
||||
marker, err := h.markers.Read()
|
||||
if rec.Code != http.StatusAccepted || err != nil || marker.Kind != "restart" || marker.Tag != "" {
|
||||
t.Fatalf("status = %d, marker = %+v, err = %v", rec.Code, marker, err)
|
||||
}
|
||||
if decodeUpdateBody(t, h.getAs(t, updateOwnerId))["state"] != "restarting" {
|
||||
t.Error("GET must report restarting")
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The kind must match the state", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
prepare func(*restartHTTP)
|
||||
kind string
|
||||
}{
|
||||
{"no job ready (idle) with update", func(*restartHTTP) {}, "update"},
|
||||
{"a job failed with update", func(h *restartHTTP) {
|
||||
h.jobs.put(update.Job{Tag: downloadTag, State: update.StateFailed, Error: "download"})
|
||||
}, "update"},
|
||||
{"a job ready with restart", func(h *restartHTTP) { h.readyJob() }, "restart"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
h := newRestartHTTP(t)
|
||||
h.seedResult(t, update.Result{Outcome: update.OutcomeFailed, StartedAt: restartBaseTime, FinishedAt: finishedAt(restartBaseTime)})
|
||||
tc.prepare(h)
|
||||
jobBefore, _ := h.jobs.Load()
|
||||
|
||||
rec := h.postAsOwner(t, `{"kind":"`+tc.kind+`"}`)
|
||||
|
||||
jobAfter, _ := h.jobs.Load()
|
||||
if rec.Code != http.StatusConflict || jobAfter != jobBefore {
|
||||
t.Errorf("status = %d", rec.Code)
|
||||
}
|
||||
h.assertNoMarkerAndResultKept(t, true)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Restart site never installs an update another owner just made ready", func(t *testing.T) {
|
||||
h := newRestartHTTP(t)
|
||||
h.readyJob()
|
||||
|
||||
rec := h.postAsOwner(t, `{"kind":"restart"}`)
|
||||
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
h.assertNoMarkerAndResultKept(t, false)
|
||||
if job, found := h.jobs.Load(); !found || job.State != update.StateReady {
|
||||
t.Error("the ready job must stay ready")
|
||||
}
|
||||
if decodeUpdateBody(t, h.getAs(t, updateOwnerId))["state"] != "ready" {
|
||||
t.Error("the card must read Ready to install after the reload")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A bad body is a 400", func(t *testing.T) {
|
||||
for _, body := range []string{`{"kind":"upgrade"}`, `{"kind":""}`, `{"kind":7}`, `{"kind":"update"`, `not json`} {
|
||||
t.Run(body, func(t *testing.T) {
|
||||
h := newRestartHTTP(t)
|
||||
h.readyJob()
|
||||
h.seedResult(t, update.Result{Outcome: update.OutcomeFailed})
|
||||
|
||||
rec := h.postAsOwner(t, body)
|
||||
|
||||
if rec.Code != http.StatusBadRequest || rec.Body.String() != apperr.BodyErrorMessage+"\n" {
|
||||
t.Errorf("status = %d body = %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
h.assertNoMarkerAndResultKept(t, true)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("POST is guarded like the other system routes", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
userId uint32
|
||||
tokenVersion uint32
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{"no jwt cookie", 0, 0, http.StatusUnauthorized, ""},
|
||||
{"a stale token version", updateOwnerId, 1, http.StatusUnauthorized, apperr.UnauthorizedErrorMessage + "\n"},
|
||||
{"an unverified owner", updateUnverifiedOwner, 0, http.StatusForbidden, apperr.VerificationRequiredErrorMessage + "\n"},
|
||||
{"an admin", updateAdminId, 0, http.StatusForbidden, apperr.OwnerRequiredErrorMessage + "\n"},
|
||||
{"an admin with a bad body", updateAdminId, 0, http.StatusForbidden, apperr.OwnerRequiredErrorMessage + "\n"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
h := newRestartHTTP(t)
|
||||
h.seedResult(t, update.Result{Outcome: update.OutcomeFailed})
|
||||
body := ""
|
||||
if strings.Contains(tc.name, "bad body") {
|
||||
body = "not json"
|
||||
}
|
||||
|
||||
rec := h.post(t, tc.userId, tc.tokenVersion, body)
|
||||
|
||||
if rec.Code != tc.status || (tc.body != "" && rec.Body.String() != tc.body) {
|
||||
t.Errorf("status = %d body = %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
h.assertNoMarkerAndResultKept(t, true)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The checks run in the documented order", func(t *testing.T) {
|
||||
h := newRestartHTTP(t)
|
||||
h.helper.installed = false
|
||||
|
||||
if rec := h.postAsOwner(t, "not json"); rec.Code != http.StatusBadRequest {
|
||||
t.Errorf("a bad body with can_apply off = %d, want 400", rec.Code)
|
||||
}
|
||||
if rec := h.postAsOwner(t, `{"kind":"update"}`); rec.Code != http.StatusConflict {
|
||||
t.Errorf("can_apply off with a mismatching kind = %d, want 409", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Restart is refused with 409", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
prepare func(*restartHTTP, *testing.T)
|
||||
}{
|
||||
{"can_apply is false (no update-helper.json)", func(h *restartHTTP, _ *testing.T) { h.helper.installed = false }},
|
||||
{"the job state is downloading", func(h *restartHTTP, _ *testing.T) {
|
||||
h.jobs.put(update.Job{Tag: downloadTag, State: update.StateDownloading})
|
||||
}},
|
||||
{"the job state is verifying", func(h *restartHTTP, _ *testing.T) {
|
||||
h.jobs.put(update.Job{Tag: downloadTag, State: update.StateVerifying})
|
||||
}},
|
||||
{"a marker is already pending", func(h *restartHTTP, t *testing.T) {
|
||||
if err := h.markers.Write(update.RestartRequest{Kind: "restart", RequestedAt: restartBaseTime, RequestedBy: 9}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}},
|
||||
{"the result file reads running (helper at work)", func(h *restartHTTP, t *testing.T) {
|
||||
h.seedResult(t, update.Result{Outcome: update.OutcomeRunning, Kind: "update", StartedAt: restartBaseTime.Add(-30 * time.Second)})
|
||||
}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
h := newRestartHTTP(t)
|
||||
tc.prepare(h, t)
|
||||
markerBefore, markerExisted := h.markerBytes()
|
||||
resultBefore, resultExisted := os.ReadFile(h.resultPath)
|
||||
|
||||
rec := h.postAsOwner(t, "")
|
||||
|
||||
markerAfter, markerExistsNow := h.markerBytes()
|
||||
resultAfter, resultExistsNow := os.ReadFile(h.resultPath)
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
if markerExisted != markerExistsNow || string(markerBefore) != string(markerAfter) || (resultExisted == nil) != (resultExistsNow == nil) || string(resultBefore) != string(resultAfter) {
|
||||
t.Error("the existing marker and result must be untouched and no new marker written")
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Two restarts at once write one marker", func(t *testing.T) {
|
||||
h := newRestartHTTP(t)
|
||||
var wait sync.WaitGroup
|
||||
codes := make([]int, 2)
|
||||
for i, userId := range []uint32{updateOwnerId, updateSecondOwner} {
|
||||
wait.Add(1)
|
||||
go func() {
|
||||
defer wait.Done()
|
||||
tokenVersion := uint32(0)
|
||||
if userId == updateOwnerId {
|
||||
tokenVersion = 2
|
||||
}
|
||||
codes[i] = h.post(t, userId, tokenVersion, "").Code
|
||||
}()
|
||||
}
|
||||
wait.Wait()
|
||||
|
||||
accepted, refused := 0, 0
|
||||
for _, code := range codes {
|
||||
switch code {
|
||||
case http.StatusAccepted:
|
||||
accepted++
|
||||
case http.StatusConflict:
|
||||
refused++
|
||||
}
|
||||
}
|
||||
entries, _ := os.ReadDir(h.dataDir)
|
||||
if accepted != 1 || refused != 1 || len(entries) != 1 {
|
||||
t.Errorf("codes = %v, entries = %d", codes, len(entries))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("The marker cannot be written", func(t *testing.T) {
|
||||
assertFailure := func(t *testing.T, h *restartHTTP) {
|
||||
t.Helper()
|
||||
jobBefore, _ := h.jobs.Load()
|
||||
rec := h.postAsOwner(t, "")
|
||||
jobAfter, _ := h.jobs.Load()
|
||||
if rec.Code != http.StatusInternalServerError || rec.Body.String() != "Internal server error\n" {
|
||||
t.Errorf("status = %d body = %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), h.dataDir) || jobAfter != jobBefore {
|
||||
t.Error("no path may leak and the job record must not change")
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("a directory sits where the marker goes", func(t *testing.T) {
|
||||
h := newRestartHTTP(t)
|
||||
h.readyJob()
|
||||
if err := os.Mkdir(h.markerPath, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertFailure(t, h)
|
||||
if info, err := os.Stat(h.markerPath); err != nil || !info.IsDir() {
|
||||
t.Error("the directory must stay")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the data directory is not writable", func(t *testing.T) {
|
||||
if runtime.GOOS == "windows" || os.Geteuid() == 0 {
|
||||
t.Skip("directory permissions are not enforced here")
|
||||
}
|
||||
h := newRestartHTTP(t)
|
||||
if err := os.Chmod(h.dataDir, 0o500); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.Chmod(h.dataDir, 0o700)
|
||||
assertFailure(t, h)
|
||||
if _, found := h.markerBytes(); found {
|
||||
t.Error("no marker may exist")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("GET derives the state from the files and never changes them", func(t *testing.T) {
|
||||
finished := restartBaseTime.Add(-10 * time.Second)
|
||||
cases := []struct {
|
||||
name string
|
||||
files func(*restartHTTP, *testing.T)
|
||||
state string
|
||||
errKind any
|
||||
finished any
|
||||
}{
|
||||
{"a marker is present", func(h *restartHTTP, t *testing.T) {
|
||||
_ = h.markers.Write(update.RestartRequest{Kind: "restart", RequestedAt: restartBaseTime.Add(-time.Second)})
|
||||
}, "restarting", nil, nil},
|
||||
{"result running written 30 s ago", func(h *restartHTTP, t *testing.T) {
|
||||
h.seedResult(t, update.Result{Outcome: "running", Kind: "update", Tag: downloadTag, StartedAt: restartBaseTime.Add(-30 * time.Second)})
|
||||
}, "restarting", nil, nil},
|
||||
{"result running written 6 minutes ago, no marker", func(h *restartHTTP, t *testing.T) {
|
||||
h.seedResult(t, update.Result{Outcome: "running", Kind: "update", Tag: downloadTag, StartedAt: restartBaseTime.Add(-6 * time.Minute), FinishedAt: &finished})
|
||||
}, "failed", "install", "2026-09-30T09:49:50Z"},
|
||||
{"result succeeded, kind update, tag equal to the running version", func(h *restartHTTP, t *testing.T) {
|
||||
h.seedResult(t, update.Result{Outcome: "succeeded", Kind: "update", Tag: updateRunning, StartedAt: restartBaseTime.Add(-time.Minute), FinishedAt: &finished})
|
||||
}, "succeeded", nil, "2026-09-30T09:49:50Z"},
|
||||
{"result succeeded, kind update, tag older than the running one", func(h *restartHTTP, t *testing.T) {
|
||||
h.seedResult(t, update.Result{Outcome: "succeeded", Kind: "update", Tag: "v2.1.0-beta", StartedAt: restartBaseTime.Add(-time.Minute), FinishedAt: &finished})
|
||||
}, "idle", nil, "2026-09-30T09:49:50Z"},
|
||||
{"result succeeded, kind restart", func(h *restartHTTP, t *testing.T) {
|
||||
h.seedResult(t, update.Result{Outcome: "succeeded", Kind: "restart", StartedAt: restartBaseTime.Add(-time.Minute), FinishedAt: &finished})
|
||||
}, "idle", nil, "2026-09-30T09:49:50Z"},
|
||||
{"result rolled_back", func(h *restartHTTP, t *testing.T) {
|
||||
h.seedResult(t, update.Result{Outcome: "rolled_back", Kind: "update", Tag: downloadTag, StartedAt: restartBaseTime.Add(-time.Minute), FinishedAt: &finished})
|
||||
}, "failed", "rolled_back", "2026-09-30T09:49:50Z"},
|
||||
{"result failed", func(h *restartHTTP, t *testing.T) {
|
||||
h.seedResult(t, update.Result{Outcome: "failed", Kind: "update", Tag: downloadTag, StartedAt: restartBaseTime.Add(-time.Minute), FinishedAt: &finished})
|
||||
}, "failed", "install", "2026-09-30T09:49:50Z"},
|
||||
{"no marker, no result", func(*restartHTTP, *testing.T) {}, "idle", nil, nil},
|
||||
{"a corrupt result file", func(h *restartHTTP, t *testing.T) {
|
||||
if err := os.WriteFile(h.resultPath, []byte("{not json"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}, "idle", nil, nil},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
h := newRestartHTTP(t)
|
||||
tc.files(h, t)
|
||||
before := snapshotDirectory(t, h.dataDir)
|
||||
|
||||
first := h.getAs(t, updateAdminId)
|
||||
second := h.getAs(t, updateAdminId)
|
||||
|
||||
body := decodeUpdateBody(t, first)
|
||||
assertUpdateKeys(t, body)
|
||||
if first.Body.String() != second.Body.String() {
|
||||
t.Error("two GETs must answer identically")
|
||||
}
|
||||
if body["state"] != tc.state || body["error"] != tc.errKind || body["finished_at"] != tc.finished {
|
||||
t.Errorf("state = %v, error = %v, finished_at = %v", body["state"], body["error"], body["finished_at"])
|
||||
}
|
||||
if after := snapshotDirectory(t, h.dataDir); !equalSnapshots(before, after) {
|
||||
t.Errorf("a GET changed the data directory: %v -> %v", before, after)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("After a successful update the status is consistent", func(t *testing.T) {
|
||||
h := newRestartHTTP(t)
|
||||
h.seedResult(t, update.Result{Outcome: "succeeded", Kind: "update", Tag: updateRunning, StartedAt: restartBaseTime.Add(-time.Minute), FinishedAt: finishedAt(restartBaseTime)})
|
||||
h.store.result.Latest = updateRunning
|
||||
|
||||
body := decodeUpdateBody(t, h.getAs(t, updateOwnerId))
|
||||
|
||||
if body["state"] != "succeeded" || body["available"] != false || body["current"] != updateRunning || body["finished_at"] == nil {
|
||||
t.Errorf("body = %v", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type directorySnapshot map[string]string
|
||||
|
||||
func snapshotDirectory(t *testing.T, directory string) directorySnapshot {
|
||||
t.Helper()
|
||||
snapshot := directorySnapshot{}
|
||||
entries, err := os.ReadDir(directory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
info, _ := entry.Info()
|
||||
content, _ := os.ReadFile(filepath.Join(directory, entry.Name()))
|
||||
snapshot[entry.Name()] = string(content) + "|" + info.ModTime().String()
|
||||
}
|
||||
return snapshot
|
||||
}
|
||||
|
||||
func equalSnapshots(a, b directorySnapshot) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for name, value := range a {
|
||||
if b[name] != value {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func TestRestartResultLivesUntilTheNextJob(t *testing.T) {
|
||||
t.Run("The result lives until the next job", func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
h := newDownloadHTTP(t, rig)
|
||||
rig.results.put(update.Result{Outcome: update.OutcomeRolledBack, Kind: update.RestartKindUpdate, Tag: downloadTag, StartedAt: restartBaseTime, FinishedAt: finishedAt(restartBaseTime)})
|
||||
|
||||
before := decodeUpdateBody(t, h.sendAs(t, http.MethodGet, "/update", updateOwnerId))
|
||||
rec := h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId)
|
||||
ready := waitForHTTPState(t, h, "ready", "failed")
|
||||
|
||||
if before["state"] != "failed" || before["error"] != "rolled_back" || before["finished_at"] == nil {
|
||||
t.Errorf("before = %v", before)
|
||||
}
|
||||
if rec.Code != http.StatusAccepted || rig.results.deletes != 1 || rig.results.found {
|
||||
t.Errorf("status = %d, deletes = %d", rec.Code, rig.results.deletes)
|
||||
}
|
||||
assertUpdateKeys(t, ready)
|
||||
if ready["state"] != "ready" || ready["error"] != nil || ready["finished_at"] != nil {
|
||||
t.Errorf("ready = %v", ready)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A download is refused while a restart is pending", func(t *testing.T) {
|
||||
rig := newDownloadRig(t)
|
||||
h := newDownloadHTTP(t, rig)
|
||||
rig.requests.present = true
|
||||
rig.results.put(update.Result{Outcome: update.OutcomeRunning, StartedAt: restartBaseTime})
|
||||
|
||||
rec := h.sendAs(t, http.MethodPost, downloadPath, updateOwnerId)
|
||||
|
||||
if rec.Code != http.StatusConflict || rig.results.deletes != 0 || rig.fetcher.totalCalls() != 0 {
|
||||
t.Errorf("status = %d", rec.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestHealthzIsUnchanged(t *testing.T) {
|
||||
t.Run("Healthz is unchanged", func(t *testing.T) {
|
||||
container := &api.UseCases{Token: jwtauth.New("HS256", []byte("test-secret"), nil)}
|
||||
router := api.InitRoutes(container, config.Settings{Environment: "production"})
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/healthz", nil))
|
||||
|
||||
if rec.Code != http.StatusOK || rec.Body.String() != "ok" {
|
||||
t.Errorf("status = %d body = %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
for name := range rec.Header() {
|
||||
if strings.Contains(strings.ToLower(name), "version") {
|
||||
t.Errorf("unexpected header %s", name)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRunningInfoFileAtStartup(t *testing.T) {
|
||||
t.Run("The server writes update-running.json at startup", func(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
path := filepath.Join(directory, update.RunningInfoFileName)
|
||||
store := infraUpdate.NewJSONRunningInfoStore(path)
|
||||
first := &fakeClock{now: restartBaseTime}
|
||||
|
||||
if err := useCases.NewRecordRunningInfoUseCase(store, "v2.3.0-beta", 111, first.Now).Record(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
content, _ := os.ReadFile(path)
|
||||
var written map[string]any
|
||||
_ = json.Unmarshal(content, &written)
|
||||
if written["version"] != "v2.3.0-beta" || written["pid"] != float64(111) || written["started_at"] != "2026-09-30T09:50:00Z" || len(written) != 3 {
|
||||
t.Errorf("file = %s", content)
|
||||
}
|
||||
|
||||
later := &fakeClock{now: restartBaseTime.Add(time.Minute)}
|
||||
if err := useCases.NewRecordRunningInfoUseCase(store, "v2.3.0-beta", 222, later.Now).Record(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, found := store.Read()
|
||||
if !found || info.Pid != 222 || !info.StartedAt.Equal(later.now) {
|
||||
t.Errorf("a second start must replace the file: %+v", info)
|
||||
}
|
||||
if entries, _ := os.ReadDir(directory); len(entries) != 1 {
|
||||
t.Errorf("the temporary file must be renamed away, got %d entries", len(entries))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a write error is returned and nothing panics", func(t *testing.T) {
|
||||
store := infraUpdate.NewJSONRunningInfoStore(filepath.Join(t.TempDir(), "missing", update.RunningInfoFileName))
|
||||
|
||||
err := useCases.NewRecordRunningInfoUseCase(store, "v2.3.0-beta", 1, time.Now).Record()
|
||||
|
||||
if err == nil {
|
||||
t.Error("the error must reach the startup code")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the file is not served by any route", func(t *testing.T) {
|
||||
container := &api.UseCases{Token: jwtauth.New("HS256", []byte("test-secret"), nil)}
|
||||
router := api.InitRoutes(container, config.Settings{Environment: "production"})
|
||||
|
||||
for _, target := range []string{"/update-running.json", "/v1/update-running.json", "/static/uploadedImages/update-running.json"} {
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, target, nil))
|
||||
if rec.Code == http.StatusOK && strings.Contains(rec.Body.String(), "pid") {
|
||||
t.Errorf("%s served the file", target)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var restartBaseTime = time.Date(2026, 9, 30, 9, 50, 0, 0, time.UTC)
|
||||
|
||||
type restartRig struct {
|
||||
store *fakeUpdateStore
|
||||
jobs *fakeJobStore
|
||||
helper *fakeHelperDetector
|
||||
results *fakeResultStore
|
||||
requests *fakeRestartRequestStore
|
||||
clock *fakeClock
|
||||
request *useCases.RequestRestartUseCase
|
||||
status *useCases.GetUpdateStatusUseCase
|
||||
}
|
||||
|
||||
func newRestartRig(running string) *restartRig {
|
||||
rig := &restartRig{
|
||||
store: &fakeUpdateStore{result: newStoredUpdateResult(), found: true},
|
||||
jobs: &fakeJobStore{},
|
||||
helper: &fakeHelperDetector{installed: true},
|
||||
results: &fakeResultStore{},
|
||||
requests: &fakeRestartRequestStore{},
|
||||
clock: &fakeClock{now: restartBaseTime},
|
||||
}
|
||||
rig.request = useCases.NewRequestRestartUseCase(rig.store, rig.jobs, rig.helper, rig.results, rig.requests, running, rig.clock.Now)
|
||||
rig.status = useCases.NewGetUpdateStatusUseCase(rig.store, rig.jobs, rig.helper, rig.results, rig.requests, running, rig.clock.Now)
|
||||
return rig
|
||||
}
|
||||
|
||||
func (r *restartRig) readyJob() {
|
||||
r.jobs.put(update.Job{Tag: downloadTag, State: update.StateReady, StartedAt: restartBaseTime.Add(-time.Hour)})
|
||||
}
|
||||
|
||||
func finishedAt(at time.Time) *time.Time {
|
||||
return &at
|
||||
}
|
||||
|
||||
func TestRequestRestartUseCase(t *testing.T) {
|
||||
t.Run("a ready job gives an update marker with the tag and the requester", func(t *testing.T) {
|
||||
rig := newRestartRig(updateRunning)
|
||||
rig.readyJob()
|
||||
rig.results.put(update.Result{Outcome: update.OutcomeRolledBack})
|
||||
|
||||
status, err := rig.request.Request(updateOwnerId, "")
|
||||
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
marker, markerErr := rig.requests.Read()
|
||||
if markerErr != nil || marker.Kind != update.RestartKindUpdate || marker.Tag != downloadTag || marker.RequestedBy != updateOwnerId || !marker.RequestedAt.Equal(restartBaseTime) {
|
||||
t.Errorf("marker = %+v, err = %v", marker, markerErr)
|
||||
}
|
||||
if status.State != update.StateRestarting || status.StartedAt == nil || !status.StartedAt.Equal(marker.RequestedAt) || !status.CanApply {
|
||||
t.Errorf("status = %+v", status)
|
||||
}
|
||||
if rig.results.deletes != 1 || rig.results.found {
|
||||
t.Errorf("the result must be deleted first: deletes = %d", rig.results.deletes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no ready job gives a plain restart marker without a tag", func(t *testing.T) {
|
||||
for name, prepare := range map[string]func(*restartRig){
|
||||
"idle": func(*restartRig) {},
|
||||
"failed job": func(r *restartRig) {
|
||||
r.jobs.put(update.Job{Tag: downloadTag, State: update.StateFailed, Error: "download"})
|
||||
},
|
||||
"rolled back": func(r *restartRig) {
|
||||
r.results.put(update.Result{Outcome: update.OutcomeRolledBack, Kind: update.RestartKindUpdate})
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
rig := newRestartRig(updateRunning)
|
||||
prepare(rig)
|
||||
|
||||
status, err := rig.request.Request(updateOwnerId, update.RestartKindRestart)
|
||||
|
||||
marker, _ := rig.requests.Read()
|
||||
if err != nil || marker.Kind != update.RestartKindRestart || marker.Tag != "" || status.State != update.StateRestarting {
|
||||
t.Errorf("err = %v, marker = %+v, status = %+v", err, marker, status)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a kind that does not match the state is refused and nothing changes", func(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
prepare func(*restartRig)
|
||||
kind string
|
||||
}{
|
||||
"update without a ready job": {func(*restartRig) {}, update.RestartKindUpdate},
|
||||
"update after a failed job": {func(r *restartRig) { r.jobs.put(update.Job{Tag: downloadTag, State: update.StateFailed}) }, update.RestartKindUpdate},
|
||||
"restart with a ready job": {func(r *restartRig) { r.readyJob() }, update.RestartKindRestart},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
rig := newRestartRig(updateRunning)
|
||||
rig.results.put(update.Result{Outcome: update.OutcomeFailed})
|
||||
tc.prepare(rig)
|
||||
jobBefore, _ := rig.jobs.Load()
|
||||
|
||||
_, err := rig.request.Request(updateOwnerId, tc.kind)
|
||||
|
||||
if !errors.Is(err, update.ErrRestartKindMismatch) {
|
||||
t.Fatalf("err = %v", err)
|
||||
}
|
||||
jobAfter, _ := rig.jobs.Load()
|
||||
if rig.requests.writes != 0 || rig.results.deletes != 0 || !rig.results.found || jobAfter != jobBefore {
|
||||
t.Error("nothing may change on a mismatch")
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a restart is refused while it cannot or must not run", func(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
prepare func(*restartRig)
|
||||
want error
|
||||
}{
|
||||
"no helper": {func(r *restartRig) { r.helper.installed = false }, update.ErrNotPrepared},
|
||||
"downloading": {func(r *restartRig) { r.jobs.put(update.Job{State: update.StateDownloading}) }, update.ErrJobInProgress},
|
||||
"verifying": {func(r *restartRig) { r.jobs.put(update.Job{State: update.StateVerifying}) }, update.ErrJobInProgress},
|
||||
"marker pending": {func(r *restartRig) { r.requests.present = true }, update.ErrRestartPending},
|
||||
"helper at work": {func(r *restartRig) {
|
||||
r.results.put(update.Result{Outcome: update.OutcomeRunning, StartedAt: restartBaseTime.Add(-time.Minute)})
|
||||
}, update.ErrRestartPending},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
rig := newRestartRig(updateRunning)
|
||||
tc.prepare(rig)
|
||||
resultBefore, foundBefore := rig.results.Read()
|
||||
writesBefore := rig.requests.writes
|
||||
|
||||
_, err := rig.request.Request(updateOwnerId, "")
|
||||
|
||||
resultAfter, foundAfter := rig.results.Read()
|
||||
if !errors.Is(err, tc.want) || rig.requests.writes != writesBefore || resultAfter != resultBefore || foundAfter != foundBefore || rig.results.deletes != 0 {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a stale running result does not block a new restart", func(t *testing.T) {
|
||||
rig := newRestartRig(updateRunning)
|
||||
rig.results.put(update.Result{Outcome: update.OutcomeRunning, StartedAt: restartBaseTime.Add(-6 * time.Minute)})
|
||||
|
||||
_, err := rig.request.Request(updateOwnerId, "")
|
||||
|
||||
if err != nil || rig.requests.writes != 1 {
|
||||
t.Errorf("err = %v, writes = %d", err, rig.requests.writes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a marker write error is returned and leaves the job alone", func(t *testing.T) {
|
||||
rig := newRestartRig(updateRunning)
|
||||
rig.readyJob()
|
||||
rig.requests.writeErr = errors.New("disk full at /var/lib/renewcms")
|
||||
jobBefore, _ := rig.jobs.Load()
|
||||
|
||||
_, err := rig.request.Request(updateOwnerId, "")
|
||||
|
||||
jobAfter, _ := rig.jobs.Load()
|
||||
if err == nil || errors.Is(err, update.ErrRestartKindMismatch) || rig.requests.present || jobAfter != jobBefore {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("two simultaneous requests write one marker", func(t *testing.T) {
|
||||
rig := newRestartRig(updateRunning)
|
||||
var wait sync.WaitGroup
|
||||
errs := make([]error, 2)
|
||||
for i := range errs {
|
||||
wait.Add(1)
|
||||
go func() {
|
||||
defer wait.Done()
|
||||
_, errs[i] = rig.request.Request(uint32(i+1), "")
|
||||
}()
|
||||
}
|
||||
wait.Wait()
|
||||
|
||||
accepted, refused := 0, 0
|
||||
for _, err := range errs {
|
||||
switch {
|
||||
case err == nil:
|
||||
accepted++
|
||||
case errors.Is(err, update.ErrRestartPending):
|
||||
refused++
|
||||
}
|
||||
}
|
||||
if accepted != 1 || refused != 1 || rig.requests.writes != 1 {
|
||||
t.Errorf("accepted = %d, refused = %d, writes = %d", accepted, refused, rig.requests.writes)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (f *fakeResultStore) put(result update.Result) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.result = result
|
||||
f.found = true
|
||||
}
|
||||
|
||||
func TestUpdateStatusFromFiles(t *testing.T) {
|
||||
running := updateRunning
|
||||
started := restartBaseTime.Add(-30 * time.Second)
|
||||
finished := restartBaseTime.Add(-10 * time.Second)
|
||||
cases := []struct {
|
||||
name string
|
||||
marker bool
|
||||
result *update.Result
|
||||
corrupt bool
|
||||
state string
|
||||
errKind string
|
||||
finished *time.Time
|
||||
}{
|
||||
{"a marker is present", true, nil, false, "restarting", "", nil},
|
||||
{"a marker wins over a finished result", true, &update.Result{Outcome: update.OutcomeFailed, StartedAt: started, FinishedAt: &finished}, false, "restarting", "", &finished},
|
||||
{"result running written 30 s ago", false, &update.Result{Outcome: update.OutcomeRunning, StartedAt: started}, false, "restarting", "", nil},
|
||||
{"result running just under 5 minutes", false, &update.Result{Outcome: update.OutcomeRunning, StartedAt: restartBaseTime.Add(-5*time.Minute + time.Second)}, false, "restarting", "", nil},
|
||||
{"result running for 5 minutes, no marker", false, &update.Result{Outcome: update.OutcomeRunning, StartedAt: restartBaseTime.Add(-5 * time.Minute), FinishedAt: &finished}, false, "failed", "install", &finished},
|
||||
{"result running written 6 minutes ago, no marker", false, &update.Result{Outcome: update.OutcomeRunning, StartedAt: restartBaseTime.Add(-6 * time.Minute), FinishedAt: &finished}, false, "failed", "install", &finished},
|
||||
{"succeeded update with the running tag", false, &update.Result{Outcome: update.OutcomeSucceeded, Kind: update.RestartKindUpdate, Tag: running, StartedAt: started, FinishedAt: &finished}, false, "succeeded", "", &finished},
|
||||
{"succeeded update with an older tag", false, &update.Result{Outcome: update.OutcomeSucceeded, Kind: update.RestartKindUpdate, Tag: "v2.1.0-beta", StartedAt: started, FinishedAt: &finished}, false, "idle", "", &finished},
|
||||
{"succeeded plain restart", false, &update.Result{Outcome: update.OutcomeSucceeded, Kind: update.RestartKindRestart, StartedAt: started, FinishedAt: &finished}, false, "idle", "", &finished},
|
||||
{"rolled back", false, &update.Result{Outcome: update.OutcomeRolledBack, Kind: update.RestartKindUpdate, Tag: "v2.3.0-beta", StartedAt: started, FinishedAt: &finished}, false, "failed", "rolled_back", &finished},
|
||||
{"failed", false, &update.Result{Outcome: update.OutcomeFailed, Kind: update.RestartKindUpdate, StartedAt: started, FinishedAt: &finished}, false, "failed", "install", &finished},
|
||||
{"no marker, no result", false, nil, false, "idle", "", nil},
|
||||
{"a corrupt result file", false, nil, true, "idle", "", nil},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rig := newRestartRig(running)
|
||||
rig.requests.present = tc.marker
|
||||
if tc.marker {
|
||||
rig.requests.request = update.RestartRequest{Kind: update.RestartKindRestart, RequestedAt: started}
|
||||
}
|
||||
if tc.result != nil {
|
||||
rig.results.put(*tc.result)
|
||||
}
|
||||
if tc.marker || tc.result != nil {
|
||||
rig.jobs.put(update.Job{Tag: downloadTag, State: update.StateReady, StartedAt: started})
|
||||
}
|
||||
|
||||
first := rig.status.GetStatus(true)
|
||||
second := rig.status.GetStatus(true)
|
||||
|
||||
if first.State != tc.state || (tc.errKind == "") != (first.Error == nil) || (first.Error != nil && *first.Error != tc.errKind) {
|
||||
t.Errorf("state = %q, error = %v", first.State, first.Error)
|
||||
}
|
||||
if (tc.finished == nil) != (first.FinishedAt == nil) || (tc.finished != nil && !first.FinishedAt.Equal(*tc.finished)) {
|
||||
t.Errorf("finished_at = %v", first.FinishedAt)
|
||||
}
|
||||
if first.Progress != nil && tc.state != "ready" {
|
||||
t.Errorf("progress = %v", first.Progress)
|
||||
}
|
||||
if first.State != second.State || rig.results.deletes != 0 || rig.requests.deletes != 0 || rig.results.writes != nil || rig.requests.writes != 0 {
|
||||
t.Error("GET must not change anything")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("without any file a ready job is reported as ready", func(t *testing.T) {
|
||||
rig := newRestartRig(running)
|
||||
rig.readyJob()
|
||||
|
||||
status := rig.status.GetStatus(true)
|
||||
|
||||
if status.State != update.StateReady || status.FinishedAt != nil {
|
||||
t.Errorf("status = %+v", status)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("after a successful update nothing is available and current is the new version", func(t *testing.T) {
|
||||
rig := newRestartRig(downloadTag)
|
||||
rig.results.put(update.Result{Outcome: update.OutcomeSucceeded, Kind: update.RestartKindUpdate, Tag: downloadTag, StartedAt: started, FinishedAt: &finished})
|
||||
|
||||
status := rig.status.GetStatus(true)
|
||||
|
||||
if status.State != update.StateSucceeded || status.Available || status.Current != downloadTag || status.FinishedAt == nil {
|
||||
t.Errorf("status = %+v", status)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestRecordRunningInfoUseCase(t *testing.T) {
|
||||
t.Run("it writes the version, the pid and the start instant", func(t *testing.T) {
|
||||
store := &fakeRunningInfoStore{}
|
||||
clock := &fakeClock{now: restartBaseTime}
|
||||
|
||||
err := useCases.NewRecordRunningInfoUseCase(store, "v2.3.0-beta", 4242, clock.Now).Record()
|
||||
|
||||
want := update.RunningInfo{Version: "v2.3.0-beta", Pid: 4242, StartedAt: restartBaseTime}
|
||||
if err != nil || len(store.writes) != 1 || store.writes[0] != want {
|
||||
t.Errorf("err = %v, writes = %+v", err, store.writes)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a write error is returned, not raised", func(t *testing.T) {
|
||||
store := &fakeRunningInfoStore{writeErr: errors.New("read-only file system")}
|
||||
|
||||
err := useCases.NewRecordRunningInfoUseCase(store, "v2.3.0-beta", 1, time.Now).Record()
|
||||
|
||||
if err == nil {
|
||||
t.Error("the error must be returned so the startup code can log it")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/internal/domain/update"
|
||||
"RenewCMS/internal/infrastructure/useCases"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type fakeReleaseFeed struct {
|
||||
release update.Release
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
var _ update.ReleaseFeed = &fakeReleaseFeed{}
|
||||
|
||||
func (f *fakeReleaseFeed) Latest() (update.Release, error) {
|
||||
f.calls++
|
||||
if f.err != nil {
|
||||
return update.Release{}, f.err
|
||||
}
|
||||
return f.release, nil
|
||||
}
|
||||
|
||||
type fakeUpdateStore struct {
|
||||
result update.CheckResult
|
||||
found bool
|
||||
saveErr error
|
||||
saves int
|
||||
}
|
||||
|
||||
var _ update.StatusStore = &fakeUpdateStore{}
|
||||
|
||||
func (f *fakeUpdateStore) Load() (update.CheckResult, bool) {
|
||||
return f.result, f.found
|
||||
}
|
||||
|
||||
func (f *fakeUpdateStore) Save(result update.CheckResult) error {
|
||||
f.saves++
|
||||
if f.saveErr != nil {
|
||||
return f.saveErr
|
||||
}
|
||||
f.result = result
|
||||
f.found = true
|
||||
return nil
|
||||
}
|
||||
|
||||
var updateTestCheckedAt = time.Date(2026, 9, 30, 9, 41, 0, 0, time.UTC)
|
||||
|
||||
func newStoredUpdateResult() update.CheckResult {
|
||||
return update.CheckResult{
|
||||
Latest: "v2.3.0-beta",
|
||||
ReleaseURL: "https://git.example/fsylvain/RenewCMS/releases/tag/v2.3.0-beta",
|
||||
Notes: update.ReleaseNotes{
|
||||
Version: "v2.3.0-beta",
|
||||
ReleasedAt: time.Date(2026, 9, 24, 8, 0, 0, 0, time.UTC),
|
||||
Items: []string{"Media library"},
|
||||
},
|
||||
CheckedAt: updateTestCheckedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func TestVersionComparison(t *testing.T) {
|
||||
cases := []struct {
|
||||
current, latest string
|
||||
available bool
|
||||
}{
|
||||
{"v2.2.0-beta", "v2.3.0-beta", true},
|
||||
{"v2.5.0-beta", "v2.5.0", true},
|
||||
{"v2.5.0", "v2.5.0-beta", false},
|
||||
{"v2.9.0", "v2.10.0", true},
|
||||
{"v2.5.0-beta", "v2.5.0-beta", false},
|
||||
{"v2.5.0", "v2.4.9", false},
|
||||
{"dev", "v9.9.9", false},
|
||||
{"v2.5.0-beta.2", "v2.5.0-beta.10", true},
|
||||
{"v2.5.0-alpha", "v2.5.0-beta", true},
|
||||
{"2.0.0-beta", "v2.1.0-beta", true},
|
||||
{"v2.5", "v2.5.0", false},
|
||||
{"v2.2.0", "garbage", false},
|
||||
{"v1.0.0-1", "v1.0.0-alpha", true},
|
||||
{"v1.0.0-alpha", "v1.0.0-1", false},
|
||||
{"v1.0.0-beta", "v1.0.0-beta.1", true},
|
||||
{"v1.0.0-beta.1", "v1.0.0-beta", false},
|
||||
{"v1.0.0-beta.2", "v1.0.0-beta.1", false},
|
||||
{"v1.0.0-beta", "v1.0.0-alpha", false},
|
||||
{"v1.0.0", "v1.0.0", false},
|
||||
{"v1.1.0", "v1.0.9", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.current+" to "+c.latest, func(t *testing.T) {
|
||||
if got := update.IsNewer(c.current, c.latest); got != c.available {
|
||||
t.Errorf("IsNewer(%q, %q) = %v, want %v", c.current, c.latest, got, c.available)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseVersionRejectsGarbage(t *testing.T) {
|
||||
for _, raw := range []string{"", "dev", "v", "v1.x.0", "v1.2.3-", "v-1.0.0"} {
|
||||
if _, err := update.ParseVersion(raw); !errors.Is(err, update.ErrInvalidVersion) {
|
||||
t.Errorf("ParseVersion(%q) error = %v, want ErrInvalidVersion", raw, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewestReleaseIsChosenRegardlessOfOrder(t *testing.T) {
|
||||
releases := []update.Release{{Tag: "v2.4.0-beta"}, {Tag: "v2.5.0-beta"}, {Tag: "v2.3.0-beta"}}
|
||||
newest, err := update.Newest(releases)
|
||||
if err != nil || newest.Tag != "v2.5.0-beta" {
|
||||
t.Fatalf("Newest = %q, %v, want v2.5.0-beta", newest.Tag, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewestReleaseOfNothingIsAnError(t *testing.T) {
|
||||
if _, err := update.Newest(nil); !errors.Is(err, update.ErrNoRelease) {
|
||||
t.Errorf("error = %v, want ErrNoRelease", err)
|
||||
}
|
||||
if _, err := update.Newest([]update.Release{{Tag: "nightly"}}); !errors.Is(err, update.ErrNoRelease) {
|
||||
t.Errorf("error = %v, want ErrNoRelease for an unparsable tag", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReleaseNotesBecomeAPlainTextList(t *testing.T) {
|
||||
published := time.Date(2026, 9, 24, 8, 0, 0, 0, time.UTC)
|
||||
body := "## What's new\n- **Media** library\n- Fixed [caching](http://x) bug\n\n* Faster start"
|
||||
|
||||
notes := update.BuildNotes("v2.3.0-beta", published, body)
|
||||
|
||||
want := []string{"Media library", "Fixed caching bug", "Faster start"}
|
||||
if !reflect.DeepEqual(notes.Items, want) {
|
||||
t.Errorf("items = %v, want %v", notes.Items, want)
|
||||
}
|
||||
if !notes.ReleasedAt.Equal(published) || notes.Version != "v2.3.0-beta" {
|
||||
t.Errorf("notes = %+v", notes)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReleaseNotesWithoutBulletsHaveNoItems(t *testing.T) {
|
||||
notes := update.BuildNotes("v1.0.0", time.Time{}, "Just an intro.\n\n**Group**\n")
|
||||
if notes.Items == nil || len(notes.Items) != 0 {
|
||||
t.Errorf("items = %#v, want an empty non-nil list", notes.Items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReleaseNotesStripInlineMarkdown(t *testing.T) {
|
||||
notes := update.BuildNotes("v1.0.0", time.Time{}, "- Run `task build` and *enjoy* __it__")
|
||||
if want := []string{"Run task build and enjoy it"}; !reflect.DeepEqual(notes.Items, want) {
|
||||
t.Errorf("items = %v, want %v", notes.Items, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetUpdateStatusUseCase(t *testing.T) {
|
||||
t.Run("never checked", func(t *testing.T) {
|
||||
status := newUpdateStatusUseCase(&fakeUpdateStore{}, &fakeJobStore{}, &fakeHelperDetector{}, "v2.2.0-beta").GetStatus(true)
|
||||
|
||||
if status.Current != "v2.2.0-beta" || status.Latest != "" || status.Available {
|
||||
t.Errorf("status = %+v", status)
|
||||
}
|
||||
if status.ReleaseURL != nil || status.Notes != nil || status.CheckedAt != nil || status.Progress != nil || status.Error != nil || status.StartedAt != nil {
|
||||
t.Errorf("never-checked values must be nil: %+v", status)
|
||||
}
|
||||
if status.State != update.StateIdle || status.CanApply {
|
||||
t.Errorf("state = %q, can_apply = %v", status.State, status.CanApply)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("stored result", func(t *testing.T) {
|
||||
store := &fakeUpdateStore{result: newStoredUpdateResult(), found: true}
|
||||
|
||||
status := newUpdateStatusUseCase(store, &fakeJobStore{}, &fakeHelperDetector{}, "v2.2.0-beta").GetStatus(true)
|
||||
|
||||
if status.Latest != "v2.3.0-beta" || !status.Available || status.CanApply || status.State != update.StateIdle {
|
||||
t.Errorf("status = %+v", status)
|
||||
}
|
||||
if status.ReleaseURL == nil || *status.ReleaseURL != store.result.ReleaseURL {
|
||||
t.Errorf("release_url = %v", status.ReleaseURL)
|
||||
}
|
||||
if status.CheckedAt == nil || !status.CheckedAt.Equal(updateTestCheckedAt) {
|
||||
t.Errorf("checked_at = %v", status.CheckedAt)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("dev build never reports an update", func(t *testing.T) {
|
||||
store := &fakeUpdateStore{result: newStoredUpdateResult(), found: true}
|
||||
if newUpdateStatusUseCase(store, &fakeJobStore{}, &fakeHelperDetector{}, "dev").GetStatus(true).Available {
|
||||
t.Error("a dev build must not report an update")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestCheckForUpdateUseCase(t *testing.T) {
|
||||
newRelease := update.Release{Tag: "v2.3.0-beta", URL: "https://git.example/r/v2.3.0-beta", PublishedAt: updateTestCheckedAt}
|
||||
now := func() time.Time { return updateTestCheckedAt }
|
||||
|
||||
t.Run("stores the result and reports it", func(t *testing.T) {
|
||||
store := &fakeUpdateStore{}
|
||||
feed := &fakeReleaseFeed{release: newRelease}
|
||||
|
||||
status, err := useCases.NewCheckForUpdateUseCase(feed, store, "v2.2.0-beta", now).Check()
|
||||
|
||||
if err != nil || !status.Available || status.Latest != "v2.3.0-beta" {
|
||||
t.Fatalf("status = %+v, err = %v", status, err)
|
||||
}
|
||||
if store.result.Latest != "v2.3.0-beta" || store.result.ReleaseURL != newRelease.URL || !store.result.CheckedAt.Equal(updateTestCheckedAt) {
|
||||
t.Errorf("stored = %+v", store.result)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("nothing newer", func(t *testing.T) {
|
||||
feed := &fakeReleaseFeed{release: update.Release{Tag: "v2.2.0-beta"}}
|
||||
status, err := useCases.NewCheckForUpdateUseCase(feed, &fakeUpdateStore{}, "v2.2.0-beta", now).Check()
|
||||
if err != nil || status.Available {
|
||||
t.Errorf("status = %+v, err = %v", status, err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("feed failure keeps the previous result", func(t *testing.T) {
|
||||
store := &fakeUpdateStore{result: newStoredUpdateResult(), found: true}
|
||||
feed := &fakeReleaseFeed{err: update.ErrFeedUnavailable}
|
||||
|
||||
_, err := useCases.NewCheckForUpdateUseCase(feed, store, "v2.2.0-beta", now).Check()
|
||||
|
||||
if !errors.Is(err, update.ErrFeedUnavailable) {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
if store.saves != 0 || store.result.Latest != "v2.3.0-beta" {
|
||||
t.Errorf("store changed: %+v saves %d", store.result, store.saves)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("store failure is returned", func(t *testing.T) {
|
||||
store := &fakeUpdateStore{saveErr: errRepositoryFailure}
|
||||
feed := &fakeReleaseFeed{release: newRelease}
|
||||
if _, err := useCases.NewCheckForUpdateUseCase(feed, store, "v2.2.0-beta", now).Check(); !errors.Is(err, errRepositoryFailure) {
|
||||
t.Errorf("err = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useSessionStore } from '@/stores/session'
|
||||
import { useUpdateStore } from '@/stores/update'
|
||||
import { useApi } from '@/composables/useApi'
|
||||
import { useSidebarCollapsed } from '@/composables/useSidebarCollapsed'
|
||||
import AppBoot from '@/components/AppBoot.vue'
|
||||
@@ -9,6 +10,7 @@ import AccountMenuSheet from '@/components/AccountMenuSheet.vue'
|
||||
import AppLogo from '@/components/AppLogo.vue'
|
||||
import ErrorView from '@/components/ErrorView.vue'
|
||||
import OfflineBanner from '@/components/OfflineBanner.vue'
|
||||
import UpdatePill from '@/components/UpdatePill.vue'
|
||||
import UserMenu from '@/components/UserMenu.vue'
|
||||
|
||||
const props = withDefaults(
|
||||
@@ -43,6 +45,7 @@ const bodyUi = computed(() => {
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const session = useSessionStore()
|
||||
const update = useUpdateStore()
|
||||
const api = useApi()
|
||||
|
||||
const navItems = computed(() =>
|
||||
@@ -52,7 +55,7 @@ const navItems = computed(() =>
|
||||
{ label: 'Media', to: '/media', icon: 'i-lucide-images' },
|
||||
{ label: 'Users', to: '/users', icon: 'i-lucide-users' },
|
||||
{ label: 'Integration', to: '/integration', icon: 'i-lucide-plug' },
|
||||
{ label: 'Settings', to: '/settings', icon: 'i-lucide-settings' },
|
||||
{ label: 'Settings', to: '/settings', icon: 'i-lucide-settings', slot: 'settings' },
|
||||
].map((item) => ({
|
||||
...item,
|
||||
active: route.path === item.to || route.path.startsWith(`${item.to}/`),
|
||||
@@ -154,7 +157,11 @@ async function onLogout() {
|
||||
:collapsed="sidebarCollapsed"
|
||||
aria-label="Main"
|
||||
:ui="navUi"
|
||||
/>
|
||||
>
|
||||
<template #settings-trailing>
|
||||
<UpdatePill v-if="update.showCue && !sidebarCollapsed" />
|
||||
</template>
|
||||
</UNavigationMenu>
|
||||
|
||||
<template #footer>
|
||||
<UserMenu
|
||||
@@ -172,7 +179,6 @@ async function onLogout() {
|
||||
<UDashboardPanel :ui="{ body: bodyUi }">
|
||||
<template #header>
|
||||
<UDashboardNavbar
|
||||
:toggle="{ ui: { leadingIcon: 'size-5' } }"
|
||||
:title="pageTitle"
|
||||
:ui="{
|
||||
root: 'h-14 gap-1 bg-default px-1.5 sm:px-1.5 lg:h-12 lg:gap-2 lg:px-6',
|
||||
@@ -181,6 +187,23 @@ async function onLogout() {
|
||||
toggle: 'size-11 justify-center',
|
||||
}"
|
||||
>
|
||||
<template #toggle>
|
||||
<span class="relative lg:hidden">
|
||||
<UDashboardSidebarToggle
|
||||
data-slot="toggle"
|
||||
color="neutral"
|
||||
variant="ghost"
|
||||
class="size-11 justify-center"
|
||||
:ui="{ leadingIcon: 'size-5' }"
|
||||
/>
|
||||
<span
|
||||
v-if="update.showCue"
|
||||
role="img"
|
||||
aria-label="Update available"
|
||||
class="absolute top-2.25 right-2.25 size-2.5 border-2 border-(--ui-bg) bg-info"
|
||||
/>
|
||||
</span>
|
||||
</template>
|
||||
<template #leading>
|
||||
<UDashboardSidebarCollapse
|
||||
color="neutral"
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
|
||||
defineProps<{
|
||||
version: string
|
||||
date: string
|
||||
items: string[]
|
||||
}>()
|
||||
|
||||
const open = ref(false)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UCollapsible
|
||||
v-model:open="open"
|
||||
class="flex flex-col gap-2.5"
|
||||
:ui="{ content: 'data-[state=closed]:hidden' }"
|
||||
>
|
||||
<UButton
|
||||
color="neutral"
|
||||
variant="link"
|
||||
:icon="open ? 'i-lucide-chevron-down' : 'i-lucide-chevron-right'"
|
||||
class="min-h-11 self-start gap-1.5 p-0 font-medium text-highlighted md:min-h-8"
|
||||
:ui="{ leadingIcon: 'size-3.5' }"
|
||||
>
|
||||
What's new in {{ version }}
|
||||
</UButton>
|
||||
|
||||
<template #content>
|
||||
<div class="flex flex-col gap-2 pl-5">
|
||||
<span class="text-xs text-muted">{{ date }}</span>
|
||||
<ul class="flex flex-col gap-2">
|
||||
<li v-for="item in items" :key="item" class="flex gap-2">
|
||||
<span aria-hidden="true" class="mt-2 size-1 shrink-0 bg-muted" />
|
||||
<span class="text-sm text-pretty text-toned">{{ item }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
</UCollapsible>
|
||||
</template>
|
||||
@@ -0,0 +1,104 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import AppLogo from '@/components/AppLogo.vue'
|
||||
import type { RestartKind } from '@/composables/useUpdate'
|
||||
import { formatStartedAt, formatStartedWithAge } from '@/lib/updateFormat'
|
||||
|
||||
const LOGO_SIZE = 26
|
||||
|
||||
const props = defineProps<{
|
||||
kind: RestartKind | null
|
||||
version: string
|
||||
startedAt: string
|
||||
slow: boolean
|
||||
now: number
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
reload: []
|
||||
}>()
|
||||
|
||||
const copy = computed(() => {
|
||||
if (props.slow) {
|
||||
return {
|
||||
title: 'Still restarting',
|
||||
text: 'This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now.',
|
||||
}
|
||||
}
|
||||
if (props.kind === 'update') {
|
||||
return {
|
||||
title: `Installing version ${props.version}`,
|
||||
text: 'Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back.',
|
||||
}
|
||||
}
|
||||
return {
|
||||
title: 'Restarting your site',
|
||||
text: 'This takes about 10 seconds. This page reloads on its own when the site is back.',
|
||||
}
|
||||
})
|
||||
|
||||
const meta = computed(() =>
|
||||
props.slow
|
||||
? formatStartedWithAge(props.startedAt, new Date(props.now))
|
||||
: formatStartedAt(props.startedAt),
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
role="status"
|
||||
data-testid="restart-overlay"
|
||||
class="fixed inset-0 z-70 flex items-center justify-center bg-muted p-6"
|
||||
>
|
||||
<div class="flex w-full max-w-110 flex-col items-start gap-4">
|
||||
<AppLogo :size="LOGO_SIZE" />
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<h2 class="text-xl/7.5 font-semibold text-highlighted" data-testid="restart-title">
|
||||
{{ copy.title }}
|
||||
</h2>
|
||||
<span class="text-base/5.5 text-pretty text-toned" data-testid="restart-text">{{
|
||||
copy.text
|
||||
}}</span>
|
||||
</div>
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-label="Restarting"
|
||||
class="h-1 w-full overflow-hidden bg-accented"
|
||||
>
|
||||
<div class="restart-bar h-1 w-7/20 bg-primary" />
|
||||
</div>
|
||||
<span class="text-xs text-muted" data-testid="restart-meta">{{ meta }}</span>
|
||||
<UButton
|
||||
v-if="slow"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
class="h-11 gap-1.5 border border-accented bg-default px-3.5 text-highlighted ring-0 md:h-8"
|
||||
@click="emit('reload')"
|
||||
>
|
||||
Reload page
|
||||
</UButton>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.restart-bar {
|
||||
margin-left: 30%;
|
||||
animation: restart-slide 1.6s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.restart-bar {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes restart-slide {
|
||||
from {
|
||||
margin-left: 0;
|
||||
}
|
||||
to {
|
||||
margin-left: 65%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,53 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useCopyToClipboard } from '@/composables/useCopyToClipboard'
|
||||
|
||||
const props = defineProps<{
|
||||
line: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
copy: []
|
||||
}>()
|
||||
|
||||
const { copied, copy } = useCopyToClipboard()
|
||||
|
||||
const buttonLabel = computed(() => (copied.value ? 'Copied' : 'Copy'))
|
||||
const buttonIcon = computed(() => (copied.value ? 'i-lucide-check' : 'i-lucide-copy'))
|
||||
|
||||
async function copyLine() {
|
||||
try {
|
||||
await copy(props.line)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
emit('copy')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-2">
|
||||
<span class="text-sm font-medium text-highlighted">For whoever manages the server</span>
|
||||
<div class="flex flex-col gap-2 md:flex-row md:items-start">
|
||||
<code
|
||||
class="min-w-0 flex-1 truncate bg-elevated px-3 py-2 font-mono text-code/5.5 text-highlighted"
|
||||
>{{ line }}</code
|
||||
>
|
||||
<UButton
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
:icon="buttonIcon"
|
||||
aria-live="polite"
|
||||
class="h-11 justify-center gap-1.5 border border-accented bg-default px-3 ring-0 md:h-8"
|
||||
:class="copied ? 'text-success' : 'text-highlighted'"
|
||||
:ui="{ leadingIcon: 'size-4' }"
|
||||
@click="copyLine"
|
||||
>
|
||||
{{ buttonLabel }}
|
||||
</UButton>
|
||||
</div>
|
||||
<span class="text-xs/5 text-muted"
|
||||
>They run this once on the server. After that, Update and Restart appear here.</span
|
||||
>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,73 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
export type UpdateBannerState = 'available' | 'ready'
|
||||
|
||||
const props = defineProps<{
|
||||
state: UpdateBannerState
|
||||
version: string
|
||||
}>()
|
||||
|
||||
const COPY = {
|
||||
available: {
|
||||
icon: 'i-lucide-circle-arrow-up',
|
||||
title: (version: string) => `Version ${version} is available`,
|
||||
description: 'Update it from Settings. It takes about 2 minutes and the site stays online.',
|
||||
},
|
||||
ready: {
|
||||
icon: 'i-lucide-circle-check',
|
||||
title: (version: string) => `Version ${version} is ready to install`,
|
||||
description:
|
||||
'Restart from Settings to finish. The site is unavailable for about 10 seconds.',
|
||||
},
|
||||
} as const
|
||||
|
||||
const copy = computed(() => COPY[props.state])
|
||||
|
||||
const emit = defineEmits<{
|
||||
'go-to-settings': []
|
||||
dismiss: []
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UAlert
|
||||
role="region"
|
||||
aria-label="Update available"
|
||||
color="info"
|
||||
variant="soft"
|
||||
orientation="horizontal"
|
||||
:icon="copy.icon"
|
||||
:title="copy.title(version)"
|
||||
:description="copy.description"
|
||||
:ui="{
|
||||
root: 'flex-wrap items-start gap-x-2.5 gap-y-3 border border-default py-3 ring-0 md:flex-nowrap md:items-center',
|
||||
wrapper: 'basis-0 gap-0.5',
|
||||
title: 'text-sm text-highlighted',
|
||||
description: 'mt-0 text-sm/5 text-toned',
|
||||
actions: 'max-md:w-full max-md:basis-full',
|
||||
}"
|
||||
>
|
||||
<template #actions>
|
||||
<div class="flex w-full items-center gap-2">
|
||||
<UButton
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
class="h-11 flex-1 justify-center border border-accented bg-default px-3 text-highlighted ring-0 md:h-8 md:flex-none"
|
||||
@click="emit('go-to-settings')"
|
||||
>
|
||||
Go to Settings
|
||||
</UButton>
|
||||
<UButton
|
||||
color="neutral"
|
||||
variant="ghost"
|
||||
icon="i-lucide-x"
|
||||
aria-label="Dismiss"
|
||||
class="size-11 shrink-0 justify-center text-muted md:size-8"
|
||||
:ui="{ leadingIcon: 'size-4' }"
|
||||
@click="emit('dismiss')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</UAlert>
|
||||
</template>
|
||||
@@ -0,0 +1,3 @@
|
||||
<template>
|
||||
<UBadge label="Update" color="info" variant="solid" class="ml-auto h-4.5 px-1.5 py-0 text-xs" />
|
||||
</template>
|
||||
@@ -0,0 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
label: string
|
||||
text: string
|
||||
value: number | null
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div aria-live="off" class="flex flex-col gap-1.5 pt-2">
|
||||
<UProgress
|
||||
:model-value="value"
|
||||
:max="100"
|
||||
:get-value-label="() => label"
|
||||
:ui="{
|
||||
base: 'h-1.5 bg-accented',
|
||||
indicator: value === null ? 'h-full w-7/20 bg-primary' : 'bg-primary',
|
||||
}"
|
||||
/>
|
||||
<span class="font-mono text-xs/4 text-muted">{{ text }}</span>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,46 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
export type UpdateTone = 'neutral' | 'success' | 'info' | 'warning' | 'error'
|
||||
|
||||
const TONE_CLASSES: Record<UpdateTone, { block: string; icon: string }> = {
|
||||
neutral: { block: 'bg-muted', icon: 'text-toned' },
|
||||
success: { block: 'bg-(--rc-success-soft)', icon: 'text-success' },
|
||||
info: { block: 'bg-(--rc-info-soft)', icon: 'text-info' },
|
||||
warning: { block: 'bg-(--rc-warning-soft)', icon: 'text-warning' },
|
||||
error: { block: 'bg-(--rc-error-soft)', icon: 'text-error' },
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
tone: UpdateTone
|
||||
icon: string
|
||||
title: string
|
||||
text: string
|
||||
meta?: string
|
||||
live?: 'polite' | 'off'
|
||||
}>()
|
||||
|
||||
const toneClasses = computed(() => TONE_CLASSES[props.tone])
|
||||
const spinning = computed(() => props.icon === 'i-lucide-loader-circle')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :aria-live="live ?? 'polite'" class="flex gap-3 p-3.5" :class="toneClasses.block">
|
||||
<span class="flex pt-0.5">
|
||||
<UIcon
|
||||
:name="icon"
|
||||
class="size-4.5 shrink-0"
|
||||
:class="[
|
||||
toneClasses.icon,
|
||||
spinning ? 'animate-spin motion-reduce:animate-none' : '',
|
||||
]"
|
||||
/>
|
||||
</span>
|
||||
<div class="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<span class="text-base font-semibold text-highlighted">{{ title }}</span>
|
||||
<span class="text-sm text-pretty text-toned">{{ text }}</span>
|
||||
<slot />
|
||||
<span v-if="meta" class="text-xs/5 text-muted">{{ meta }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,534 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import ReleaseNotes from '@/components/ReleaseNotes.vue'
|
||||
import ServerCommand from '@/components/ServerCommand.vue'
|
||||
import UpdateProgress from '@/components/UpdateProgress.vue'
|
||||
import UpdateStatusBlock, { type UpdateTone } from '@/components/UpdateStatusBlock.vue'
|
||||
import type { RestartKind, UpdateStatus } from '@/composables/useUpdate'
|
||||
import type { UserRole } from '@/composables/useApi'
|
||||
import type { UpdateApplyPhase, UpdateCheckPhase } from '@/stores/update'
|
||||
import {
|
||||
ENABLE_BROWSER_UPDATES_COMMAND,
|
||||
VERIFYING_ANNOUNCEMENT,
|
||||
browserUpdatesDocsUrl,
|
||||
displayVersion,
|
||||
downloadAnnouncement,
|
||||
formatDownloadProgress,
|
||||
formatLastChecked,
|
||||
formatReleased,
|
||||
formatUpdatedAt,
|
||||
} from '@/lib/updateFormat'
|
||||
|
||||
type ApplyView =
|
||||
| 'available'
|
||||
| 'downloading'
|
||||
| 'verifying'
|
||||
| 'ready'
|
||||
| 'download-failed'
|
||||
| 'verification-failed'
|
||||
| 'rolled-back'
|
||||
| 'limited'
|
||||
|
||||
type ButtonAction = 'check' | 'update' | 'restart'
|
||||
|
||||
interface Block {
|
||||
tone: UpdateTone
|
||||
icon: string
|
||||
title: string
|
||||
text: string
|
||||
meta?: string
|
||||
}
|
||||
|
||||
interface ActionButton {
|
||||
label: string
|
||||
icon: string
|
||||
primary: boolean
|
||||
disabled: boolean
|
||||
action: ButtonAction | null
|
||||
restartKind?: RestartKind
|
||||
}
|
||||
|
||||
interface ProgressView {
|
||||
label: string
|
||||
text: string
|
||||
value: number | null
|
||||
}
|
||||
|
||||
const AVAILABLE_HINT = 'Takes about 2 minutes. Your site stays online.'
|
||||
const RESTART_HINT = 'Restart takes about 10 seconds. Your site is unavailable while it restarts.'
|
||||
const READY_HINT =
|
||||
'Not now? Leave this page. The update waits here, and the banner on Home reminds you.'
|
||||
const LIMITED_BLOCK: Block = {
|
||||
tone: 'info',
|
||||
icon: 'i-lucide-info',
|
||||
title: 'Too many tries',
|
||||
text: 'Wait a moment before trying again.',
|
||||
}
|
||||
const ZERO_PROGRESS = { percent: 0, downloaded_bytes: 0, total_bytes: 0 }
|
||||
|
||||
const props = defineProps<{
|
||||
status: UpdateStatus
|
||||
role: UserRole | undefined
|
||||
phase: UpdateCheckPhase
|
||||
applyPhase: UpdateApplyPhase
|
||||
retryLabel: string
|
||||
retryActive: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
check: []
|
||||
update: []
|
||||
restart: [kind: RestartKind]
|
||||
}>()
|
||||
|
||||
const card = ref<HTMLElement | null>(null)
|
||||
const heading = ref<HTMLElement | null>(null)
|
||||
|
||||
function focusHeading() {
|
||||
heading.value?.focus()
|
||||
}
|
||||
|
||||
function focusRestart() {
|
||||
card.value?.querySelector<HTMLElement>('[data-testid="restart-button"]')?.focus()
|
||||
}
|
||||
|
||||
defineExpose({ focusHeading, focusRestart })
|
||||
|
||||
const isOwner = computed(() => props.role === 'owner')
|
||||
const newVersion = computed(() => displayVersion(props.status.latest))
|
||||
const lastChecked = computed(() =>
|
||||
props.status.checked_at ? formatLastChecked(props.status.checked_at) : undefined,
|
||||
)
|
||||
|
||||
const canApplyView = computed(() => isOwner.value && props.status.can_apply)
|
||||
|
||||
const applyView = computed<ApplyView | null>(() => {
|
||||
if (!canApplyView.value || props.phase !== 'idle') {
|
||||
return null
|
||||
}
|
||||
if (props.applyPhase === 'limited') {
|
||||
return 'limited'
|
||||
}
|
||||
if (props.applyPhase === 'failed') {
|
||||
return 'download-failed'
|
||||
}
|
||||
if (props.applyPhase === 'untrusted') {
|
||||
return 'verification-failed'
|
||||
}
|
||||
const { state, error, available } = props.status
|
||||
if (state === 'downloading' || state === 'verifying' || state === 'ready') {
|
||||
return state
|
||||
}
|
||||
if (state === 'failed') {
|
||||
return failedView(error)
|
||||
}
|
||||
return available ? 'available' : null
|
||||
})
|
||||
|
||||
function failedView(error: UpdateStatus['error']): ApplyView {
|
||||
if (error === 'verification') {
|
||||
return 'verification-failed'
|
||||
}
|
||||
return error === 'rolled_back' || error === 'install' ? 'rolled-back' : 'download-failed'
|
||||
}
|
||||
|
||||
const isStarting = computed(() => props.applyPhase === 'starting')
|
||||
|
||||
const downloadFailed = computed(() => applyView.value === 'download-failed' && !isStarting.value)
|
||||
|
||||
watch(downloadFailed, async (failed) => {
|
||||
if (failed) {
|
||||
await nextTick()
|
||||
heading.value?.focus()
|
||||
}
|
||||
})
|
||||
|
||||
const applyBlocks = computed<Record<ApplyView, Block>>(() => ({
|
||||
available: {
|
||||
tone: 'info',
|
||||
icon: 'i-lucide-circle-arrow-up',
|
||||
title: `Version ${newVersion.value} is available`,
|
||||
text: `You have ${props.status.current}. Update downloads the new version and checks it. Nothing changes until you restart.`,
|
||||
meta: lastChecked.value,
|
||||
},
|
||||
downloading: {
|
||||
tone: 'info',
|
||||
icon: 'i-lucide-download',
|
||||
title: `Downloading version ${newVersion.value}…`,
|
||||
text: 'You can leave this page. The download continues and your site stays online.',
|
||||
},
|
||||
verifying: {
|
||||
tone: 'info',
|
||||
icon: 'i-lucide-shield-check',
|
||||
title: 'Checking the download…',
|
||||
text: 'Making sure the file is complete and safe to install. This takes a few seconds.',
|
||||
},
|
||||
ready: {
|
||||
tone: 'success',
|
||||
icon: 'i-lucide-circle-check',
|
||||
title: `Version ${newVersion.value} is ready to install`,
|
||||
text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.',
|
||||
meta: 'Nothing has changed yet.',
|
||||
},
|
||||
'download-failed': {
|
||||
tone: 'error',
|
||||
icon: 'i-lucide-circle-x',
|
||||
title: "The download didn't finish",
|
||||
text: 'The connection dropped before the file was complete. Nothing was changed and your site is running as before.',
|
||||
},
|
||||
'verification-failed': {
|
||||
tone: 'warning',
|
||||
icon: 'i-lucide-triangle-alert',
|
||||
title: "We didn't use this update",
|
||||
text: "The file didn't pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support.",
|
||||
},
|
||||
'rolled-back': {
|
||||
tone: 'warning',
|
||||
icon: 'i-lucide-triangle-alert',
|
||||
title: "The update didn't install",
|
||||
text: 'RenewCMS put the previous version back, so your site is running as before. Nothing was lost.',
|
||||
meta: 'What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update.',
|
||||
},
|
||||
limited: LIMITED_BLOCK,
|
||||
}))
|
||||
|
||||
const progressView = computed<ProgressView | null>(() => {
|
||||
if (applyView.value === 'downloading') {
|
||||
const progress = props.status.progress ?? ZERO_PROGRESS
|
||||
return {
|
||||
label: `Downloading version ${newVersion.value}`,
|
||||
text: props.status.progress ? formatDownloadProgress(progress) : '0%',
|
||||
value: progress.percent,
|
||||
}
|
||||
}
|
||||
if (applyView.value === 'verifying') {
|
||||
return { label: VERIFYING_ANNOUNCEMENT, text: 'Almost there', value: null }
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
const announcement = computed(() => {
|
||||
if (applyView.value === 'downloading') {
|
||||
return downloadAnnouncement(newVersion.value, props.status.progress?.percent ?? 0)
|
||||
}
|
||||
return applyView.value === 'verifying' ? VERIFYING_ANNOUNCEMENT : ''
|
||||
})
|
||||
|
||||
const hint = computed(() => {
|
||||
if (applyView.value === 'available') {
|
||||
return AVAILABLE_HINT
|
||||
}
|
||||
if (applyView.value === 'ready') {
|
||||
return READY_HINT
|
||||
}
|
||||
return showRestartHint.value ? RESTART_HINT : null
|
||||
})
|
||||
|
||||
function applyButton(view: ApplyView): ActionButton {
|
||||
if (isStarting.value || view === 'downloading' || view === 'verifying') {
|
||||
return {
|
||||
label: 'Updating…',
|
||||
icon: 'i-lucide-loader-circle',
|
||||
primary: false,
|
||||
disabled: true,
|
||||
action: null,
|
||||
}
|
||||
}
|
||||
if (view === 'ready') {
|
||||
return {
|
||||
label: 'Restart',
|
||||
icon: 'i-lucide-power',
|
||||
primary: true,
|
||||
disabled: false,
|
||||
action: 'restart',
|
||||
restartKind: 'update',
|
||||
}
|
||||
}
|
||||
if (view === 'limited') {
|
||||
return limitedButton('update')
|
||||
}
|
||||
if (view === 'available') {
|
||||
return {
|
||||
label: 'Update',
|
||||
icon: 'i-lucide-download',
|
||||
primary: true,
|
||||
disabled: false,
|
||||
action: 'update',
|
||||
}
|
||||
}
|
||||
return {
|
||||
label: 'Try again',
|
||||
icon: 'i-lucide-rotate-cw',
|
||||
primary: true,
|
||||
disabled: false,
|
||||
action: 'update',
|
||||
}
|
||||
}
|
||||
|
||||
const block = computed<Block>(() => {
|
||||
if (isOwner.value && props.phase === 'checking') {
|
||||
return {
|
||||
tone: 'neutral',
|
||||
icon: 'i-lucide-loader-circle',
|
||||
title: 'Checking for updates…',
|
||||
text: 'This usually takes a few seconds.',
|
||||
}
|
||||
}
|
||||
if (isOwner.value && props.phase === 'limited') {
|
||||
return LIMITED_BLOCK
|
||||
}
|
||||
if (isOwner.value && props.phase === 'failed') {
|
||||
return {
|
||||
tone: 'warning',
|
||||
icon: 'i-lucide-wifi-off',
|
||||
title: "Couldn't check for updates",
|
||||
text: "RenewCMS couldn't reach the update server. Check your connection and try again. Your site isn't affected.",
|
||||
meta: lastChecked.value,
|
||||
}
|
||||
}
|
||||
if (applyView.value) {
|
||||
return applyBlocks.value[applyView.value]
|
||||
}
|
||||
if (isDone.value) {
|
||||
return {
|
||||
tone: 'success',
|
||||
icon: 'i-lucide-circle-check',
|
||||
title: `You're on version ${displayVersion(props.status.current)}`,
|
||||
text: 'The update is installed and your site is running again.',
|
||||
meta: props.status.finished_at ? formatUpdatedAt(props.status.finished_at) : undefined,
|
||||
}
|
||||
}
|
||||
if (props.status.available && isOwner.value) {
|
||||
return {
|
||||
tone: 'info',
|
||||
icon: 'i-lucide-info',
|
||||
title: `Version ${newVersion.value} is available`,
|
||||
text: "This site can't update itself from the browser yet. Whoever manages your server can set it up once, or update RenewCMS for you.",
|
||||
}
|
||||
}
|
||||
if (props.status.available) {
|
||||
return {
|
||||
tone: 'info',
|
||||
icon: 'i-lucide-circle-arrow-up',
|
||||
title: `Version ${newVersion.value} is available`,
|
||||
text: `You have ${props.status.current}. Only the owner can update RenewCMS. Ask the owner of this site.`,
|
||||
}
|
||||
}
|
||||
return {
|
||||
tone: 'success',
|
||||
icon: 'i-lucide-circle-check',
|
||||
title: "You're up to date",
|
||||
text: isOwner.value
|
||||
? 'You have the latest version of RenewCMS.'
|
||||
: 'Only the owner can update or restart the site.',
|
||||
meta: isOwner.value ? lastChecked.value : undefined,
|
||||
}
|
||||
})
|
||||
|
||||
const isDone = computed(() => props.status.state === 'succeeded')
|
||||
|
||||
const isRestarting = computed(() => props.status.state === 'restarting')
|
||||
|
||||
const restartAvailable = computed(
|
||||
() => canApplyView.value && (props.status.state === 'idle' || isDone.value),
|
||||
)
|
||||
|
||||
const showServerGuidance = computed(
|
||||
() =>
|
||||
isOwner.value &&
|
||||
!props.status.can_apply &&
|
||||
props.status.available &&
|
||||
props.phase === 'idle',
|
||||
)
|
||||
|
||||
const plainRestartButton: ActionButton = {
|
||||
label: 'Restart',
|
||||
icon: 'i-lucide-power',
|
||||
primary: false,
|
||||
disabled: false,
|
||||
action: 'restart',
|
||||
restartKind: 'restart',
|
||||
}
|
||||
|
||||
const actionButtons = computed<ActionButton[]>(() => {
|
||||
if (!isOwner.value || isRestarting.value) {
|
||||
return []
|
||||
}
|
||||
if (props.phase === 'checking') {
|
||||
return [
|
||||
{
|
||||
label: 'Checking…',
|
||||
icon: 'i-lucide-loader-circle',
|
||||
primary: false,
|
||||
disabled: true,
|
||||
action: null,
|
||||
},
|
||||
]
|
||||
}
|
||||
if (props.phase === 'failed') {
|
||||
return withPlainRestart({
|
||||
label: 'Try again',
|
||||
icon: 'i-lucide-rotate-cw',
|
||||
primary: true,
|
||||
disabled: false,
|
||||
action: 'check',
|
||||
})
|
||||
}
|
||||
if (props.phase === 'limited') {
|
||||
return [limitedButton('check')]
|
||||
}
|
||||
if (applyView.value) {
|
||||
return [applyButton(applyView.value)]
|
||||
}
|
||||
if (props.status.available && !isDone.value) {
|
||||
return []
|
||||
}
|
||||
return withPlainRestart({
|
||||
label: 'Check for updates',
|
||||
icon: 'i-lucide-refresh-cw',
|
||||
primary: false,
|
||||
disabled: false,
|
||||
action: 'check',
|
||||
})
|
||||
})
|
||||
|
||||
const showRestartHint = computed(() => actionButtons.value.includes(plainRestartButton))
|
||||
|
||||
function withPlainRestart(button: ActionButton) {
|
||||
return restartAvailable.value ? [button, plainRestartButton] : [button]
|
||||
}
|
||||
|
||||
function limitedButton(action: ButtonAction): ActionButton {
|
||||
return props.retryActive
|
||||
? {
|
||||
label: `Try again in ${props.retryLabel}`,
|
||||
icon: 'i-lucide-clock',
|
||||
primary: false,
|
||||
disabled: true,
|
||||
action: null,
|
||||
}
|
||||
: {
|
||||
label: 'Try again',
|
||||
icon: 'i-lucide-rotate-cw',
|
||||
primary: false,
|
||||
disabled: false,
|
||||
action,
|
||||
}
|
||||
}
|
||||
|
||||
function onAction(button: ActionButton) {
|
||||
if (button.action === 'check') {
|
||||
emit('check')
|
||||
}
|
||||
if (button.action === 'update') {
|
||||
emit('update')
|
||||
}
|
||||
if (button.action === 'restart' && button.restartKind) {
|
||||
emit('restart', button.restartKind)
|
||||
}
|
||||
}
|
||||
|
||||
const showNotes = computed(
|
||||
() =>
|
||||
showServerGuidance.value || applyView.value === 'available' || applyView.value === 'ready',
|
||||
)
|
||||
|
||||
const notes = computed(() => {
|
||||
const items = props.status.notes?.items ?? []
|
||||
if (!showNotes.value || items.length === 0 || !props.status.notes) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
items,
|
||||
date: formatReleased(props.status.notes.released_at),
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
ref="card"
|
||||
aria-labelledby="updates-h"
|
||||
data-testid="updates-card"
|
||||
class="flex flex-col gap-4 border border-default bg-default p-4 lg:p-5"
|
||||
>
|
||||
<h2
|
||||
id="updates-h"
|
||||
ref="heading"
|
||||
tabindex="-1"
|
||||
class="self-start text-lg font-semibold text-highlighted focus:outline-2 focus:outline-offset-4 focus:outline-primary"
|
||||
>
|
||||
Updates
|
||||
</h2>
|
||||
|
||||
<UpdateStatusBlock
|
||||
:tone="block.tone"
|
||||
:icon="block.icon"
|
||||
:title="block.title"
|
||||
:text="block.text"
|
||||
:meta="block.meta"
|
||||
:live="progressView ? 'off' : 'polite'"
|
||||
>
|
||||
<UpdateProgress
|
||||
v-if="progressView"
|
||||
:label="progressView.label"
|
||||
:text="progressView.text"
|
||||
:value="progressView.value"
|
||||
/>
|
||||
</UpdateStatusBlock>
|
||||
|
||||
<p v-if="canApplyView" role="status" data-testid="update-announcer" class="sr-only">
|
||||
{{ announcement }}
|
||||
</p>
|
||||
|
||||
<ReleaseNotes v-if="notes" :version="newVersion" :date="notes.date" :items="notes.items" />
|
||||
|
||||
<ServerCommand v-if="showServerGuidance" :line="ENABLE_BROWSER_UPDATES_COMMAND" />
|
||||
|
||||
<div v-if="actionButtons.length" class="flex flex-col gap-2 md:flex-row md:items-center">
|
||||
<UButton
|
||||
v-for="button in actionButtons"
|
||||
:key="button.label"
|
||||
:data-testid="button.action === 'restart' ? 'restart-button' : undefined"
|
||||
:color="button.primary ? 'primary' : 'neutral'"
|
||||
:variant="button.primary ? 'solid' : 'outline'"
|
||||
:icon="button.icon"
|
||||
:disabled="button.disabled"
|
||||
class="h-11 justify-center gap-1.5 px-3.5 md:h-8"
|
||||
:class="
|
||||
button.primary
|
||||
? ''
|
||||
: 'border border-accented bg-default text-highlighted ring-0'
|
||||
"
|
||||
:ui="{ leadingIcon: 'size-4' }"
|
||||
@click="onAction(button)"
|
||||
>
|
||||
{{ button.label }}
|
||||
</UButton>
|
||||
</div>
|
||||
|
||||
<span v-if="hint" class="text-xs/4.5 text-pretty text-muted">{{ hint }}</span>
|
||||
|
||||
<a
|
||||
v-if="showServerGuidance && status.release_url"
|
||||
:href="browserUpdatesDocsUrl(status.release_url)"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="inline-flex items-center gap-1.5 self-start text-sm font-medium text-highlighted underline underline-offset-3"
|
||||
>
|
||||
How to update
|
||||
<UIcon name="i-lucide-arrow-up-right" class="size-3.5" />
|
||||
</a>
|
||||
|
||||
<a
|
||||
v-if="isDone && status.release_url"
|
||||
:href="status.release_url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="inline-flex items-center gap-1.5 self-start text-sm font-medium text-highlighted underline underline-offset-3"
|
||||
>
|
||||
Read the release notes
|
||||
<UIcon name="i-lucide-arrow-up-right" class="size-3.5" />
|
||||
</a>
|
||||
</section>
|
||||
</template>
|
||||
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user