diff --git a/.github/workflows/self-update.yml b/.github/workflows/self-update.yml index 582cb0eb..7cf44629 100644 --- a/.github/workflows/self-update.yml +++ b/.github/workflows/self-update.yml @@ -1,9 +1,9 @@ name: Self-update on: push: - paths: ['internal/update/**', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml'] + paths: ['internal/update/**', 'internal/app/update_restart*', 'internal/security/auth*', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/i18n/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml'] pull_request: - paths: ['internal/update/**', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml'] + paths: ['internal/update/**', 'internal/app/update_restart*', 'internal/security/auth*', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/i18n/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml'] permissions: contents: read jobs: @@ -23,7 +23,7 @@ jobs: - uses: actions/setup-node@v4 with: node-version: '22' - - run: go test -race ./internal/update ./internal/config ./internal/handler ./cmd/server ./internal/workflow + - run: go test -race ./internal/update ./internal/app ./internal/security ./internal/config ./internal/handler ./cmd/server ./internal/workflow - run: go build ./... - name: Frontend regression tests shell: bash diff --git a/cmd/server/main.go b/cmd/server/main.go index b2581e5e..1c4d2e4a 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -22,6 +22,7 @@ import ( ) func main() { + updateSessions := app.TakeUpdateSessionHandoff() var configPath = flag.String("config", "config.yaml", "Path to the configuration file") var httpsBootstrap = flag.Bool("https", false, "Enable HTTPS for the main site; uses an in-memory self-signed certificate when no cert/key is configured") var httpBootstrap = flag.Bool("http", false, "Force plain HTTP for the main site, overriding TLS settings in the configuration file") @@ -160,6 +161,7 @@ func main() { if err != nil { log.Fatal("应用初始化失败", "error", err) } + application.RestoreUpdateSessions(updateSessions) // 在后台监听信号 go func() { diff --git a/docs/en-US/developer-guide.md b/docs/en-US/developer-guide.md index 3f376c94..e1576a1a 100644 --- a/docs/en-US/developer-guide.md +++ b/docs/en-US/developer-guide.md @@ -153,7 +153,7 @@ match the files on disk, recovery refuses to overwrite them. ### Switching to the new binary On macOS and Linux, when started from the `cyberstrike-ai` binary alongside its config, the console -sends `restart: true` by default. After a successful build and binary swap, the service closes its +sends `restart: true` as soon as you click **One-Click Update**. After a successful build and binary swap, the service closes its application resources and executes the new binary with the same PID, arguments, environment and working directory. Installations that cannot switch in place return `400` on an explicit restart request. CLI updates and REST updates without `restart: true` only replace files on disk. @@ -163,11 +163,12 @@ the binary identity captured at startup (size + nanosecond mtime) with what is o update, a rollback or a CLI run swapped the file without a restart, `needsRestart` is true, `binaryBuiltAt` says when it was built, and the console grows a persistent banner with **Restart now** (`POST /api/system/update/restart`; `409 nothing_pending` when there is nothing to activate, `409` -while a job runs, `400` when unavailable). The console uses the `autoRestart` field as its default. +while a job runs, `400` when unavailable). The console checks `canRestart` before requesting automatic activation. **The page reloads automatically.** The console polls the session validation endpoint every two -seconds for the new boot marker. Sessions live in memory, so users sign in again after the switch. -Leaving the console stops the polling. +seconds for the new boot marker. When both versions support session handoff, existing sessions keep +their original expiration and permissions are loaded from the current RBAC store. The first upgrade +from an older version may still require sign-in. Leaving the console stops the polling. ## Adding a Business Module diff --git a/docs/en-US/plugin-development.md b/docs/en-US/plugin-development.md index 6d20a015..262ea2e8 100644 --- a/docs/en-US/plugin-development.md +++ b/docs/en-US/plugin-development.md @@ -46,7 +46,7 @@ Server `POST /api/auth/login` returns `{ token, expires_at }`. There is **no ref | Local check | Re-check `expires_at` + `GET /api/auth/validate` every 30s | | Server probe | Immediate probe when DevTools panel becomes visible | | Unreachable | Show warning; keep token during transient outage | -| 401/403 | Clear token (server restart clears in-memory sessions) | +| 401/403 | Clear token and require re-authentication | | Before Send | `ensureAuthReady()` before SSE | | Permissions | `optional_host_permissions` — request origin on Validate | diff --git a/docs/zh-CN/deployment.md b/docs/zh-CN/deployment.md index 58c1def9..2f179e63 100644 --- a/docs/zh-CN/deployment.md +++ b/docs/zh-CN/deployment.md @@ -189,9 +189,9 @@ SQLite 热备份时最好先停止服务,或至少复制 `*.db`、`*.db-wal` 并被页面标出,装好 go 后再点一次「一键更新」即补编译。 细节见 [开发者指南](developer-guide.md) 的「一键更新」一节。 -在 macOS/Linux 上,从配置文件同目录的 `cyberstrike-ai` 启动时,控制台默认在构建成功后自动切换到新二进制。 -构建期间旧服务继续提供服务;切换时连接会短暂中断,页面在新服务应答后自动刷新(内存中的登录会话需重新登录)。 -这一步不依赖 systemd 或 launchd;长期部署仍建议用守护进程做开机自启和异常恢复。取消自动切换、或在命令行换过 +在 macOS/Linux 上,从配置文件同目录的 `cyberstrike-ai` 启动时,点击「一键更新」后,控制台在构建成功时自动切换到新二进制。 +构建期间旧服务继续提供服务;切换时连接会短暂中断,页面在新服务应答后自动刷新并沿用仍然有效的登录会话。 +这一步不依赖 systemd 或 launchd;长期部署仍建议用守护进程做开机自启和异常恢复。通过 API 或命令行换过 二进制后,可以在支持自动切换的安装上用控制台的「立即重启服务」启用磁盘上的版本。 更新源是 `config.yaml` `update` 段里的**一个仓库地址**(`repo`),也可以直接在控制台「一键更新」页填写保存: diff --git a/docs/zh-CN/developer-guide.md b/docs/zh-CN/developer-guide.md index 06251a3e..025cf680 100644 --- a/docs/zh-CN/developer-guide.md +++ b/docs/zh-CN/developer-guide.md @@ -143,17 +143,17 @@ update: ### 切换到新二进制 -macOS/Linux 上,从配置文件同目录的 `cyberstrike-ai` 启动时,控制台默认发送 `restart: true`。 +macOS/Linux 上,从配置文件同目录的 `cyberstrike-ai` 启动时,点击「一键更新」直接发送 `restart: true`,无需二次确认。 只有成功构建并换入二进制才会切换:服务先关闭应用资源,再用相同 PID、启动参数、环境和工作目录执行新二进制。 不支持的启动方式不提供自动切换;REST 显式请求重启时返回 `400`。REST 不传该字段和 CLI 更新都只换磁盘文件。 **待生效状态是持久的、可补重启。** 状态接口对比"启动时记下的二进制身份(大小 + 纳秒 mtime)"与磁盘 现值:更新、回滚或 CLI 换过二进制而没重启时,`needsRestart` 为真、`binaryBuiltAt` 给出构建时间, 控制台顶部出现常驻横幅与「立即重启服务」(`POST /api/system/update/restart`;没有待生效版本时 -`409 nothing_pending`、有任务在跑 `409`、不支持时 `400`)。控制台根据 `autoRestart` 决定默认值。 +`409 nothing_pending`、有任务在跑 `409`、不支持时 `400`)。控制台根据 `canRestart` 决定能否自动切换。 **重启后页面自动刷新。** 控制台每 2 秒通过会话验证接口探测服务启动标记,收到新标记才刷新。 -现有登录会话保存在内存中,切换后需要重新登录。离开控制台则停止探测。 +支持会话交接的两个版本之间切换时,有效登录保持原来的到期时间,权限从新进程的 RBAC 存储重新加载。首次从旧版升级时可能需要重新登录。离开控制台则停止探测。 ## 数据库 diff --git a/internal/app/app.go b/internal/app/app.go index 6382736f..34f8a703 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -705,6 +705,17 @@ func (a *App) Run() error { return a.RunWithContext(context.Background()) } +// RestoreUpdateSessions consumes the handoff before the new HTTP listener starts. +func (a *App) RestoreUpdateSessions(handoff *os.File) { + if handoff == nil { + return + } + defer handoff.Close() + if err := a.auth.RestoreRestartSessions(handoff); err != nil { + a.logger.Warn("无法恢复更新前的登录会话", zap.Error(err)) + } +} + // RunWithContext 启动应用,支持通过 context 取消来优雅关闭 func (a *App) RunWithContext(ctx context.Context) error { // 启动MCP服务器(如果启用) diff --git a/internal/app/update_restart_other.go b/internal/app/update_restart_other.go index 9a7b82e8..dc621f5a 100644 --- a/internal/app/update_restart_other.go +++ b/internal/app/update_restart_other.go @@ -2,4 +2,8 @@ package app +import "os" + +func TakeUpdateSessionHandoff() *os.File { return nil } + func (a *App) updateRestart(string) func() (func(), error) { return nil } diff --git a/internal/app/update_restart_unix.go b/internal/app/update_restart_unix.go index 1d0678f1..94b31add 100644 --- a/internal/app/update_restart_unix.go +++ b/internal/app/update_restart_unix.go @@ -4,8 +4,12 @@ package app import ( "fmt" + "io" "os" "path/filepath" + "strconv" + "strings" + "syscall" "cyberstrike-ai/internal/update" @@ -13,6 +17,47 @@ import ( "golang.org/x/sys/unix" ) +const updateSessionsEnv = "CYBERSTRIKE_UPDATE_SESSIONS_FD" + +// TakeUpdateSessionHandoff claims the descriptor left by an in-place exec. +// Do this before startup runs any subprocesses. +func TakeUpdateSessionHandoff() *os.File { + value := os.Getenv(updateSessionsEnv) + if value == "" { + return nil + } + _ = os.Unsetenv(updateSessionsEnv) + pid, rawFD, ok := strings.Cut(value, ":") + fd, err := strconv.Atoi(rawFD) + if !ok || pid != strconv.Itoa(os.Getpid()) || err != nil || fd < 3 { + return nil + } + var stat unix.Stat_t + if err := unix.Fstat(fd, &stat); err != nil || stat.Mode&unix.S_IFMT != unix.S_IFREG || stat.Nlink != 0 { + return nil + } + unix.CloseOnExec(fd) + return os.NewFile(uintptr(fd), "update-sessions") +} + +func writeUpdateSessionHandoff(payload []byte) (*os.File, error) { + f, err := os.CreateTemp("", "cyberstrike-update-sessions-*") + if err != nil { + return nil, err + } + // The private file has no path by the time it contains session data. + if err = os.Remove(f.Name()); err == nil { + if _, err = f.Write(payload); err == nil { + _, err = f.Seek(0, io.SeekStart) + } + } + if err != nil { + _ = f.Close() + return nil, err + } + return f, nil +} + // updateRestart only replaces the executable this instance was started from. // For example, go run and installs with a separate config directory must not // start a different executable just because the updater wrote one there. @@ -49,7 +94,33 @@ func (a *App) updateRestart(root string) func() (func(), error) { a.Shutdown() // Keep the same PID, arguments, environment and working directory. // This works both in a terminal and under an existing supervisor. - if err := unix.Exec(path, os.Args, os.Environ()); err != nil { + exec := func(payload []byte) error { + env := os.Environ() + if len(payload) != 0 { + f, err := writeUpdateSessionHandoff(payload) + if err == nil { + fd := f.Fd() + // Prevent a concurrent subprocess from inheriting the descriptor. + syscall.ForkLock.Lock() + defer syscall.ForkLock.Unlock() + defer f.Close() + _, err = unix.FcntlInt(fd, unix.F_SETFD, 0) + if err == nil { + env = append(env, fmt.Sprintf("%s=%d:%d", updateSessionsEnv, os.Getpid(), fd)) + return unix.Exec(path, os.Args, env) + } + } + a.logger.Warn("无法交接登录会话,继续切换版本", zap.Error(err)) + } + return unix.Exec(path, os.Args, env) + } + var err error + if a.auth != nil { + err = a.auth.HandoffSessions(exec) + } else { + err = exec(nil) + } + if err != nil { a.logger.Error("无法启动更新后的二进制", zap.Error(err)) _ = a.logger.Sync() os.Exit(1) diff --git a/internal/app/update_restart_unix_test.go b/internal/app/update_restart_unix_test.go index 9ba8e215..1dbcdf55 100644 --- a/internal/app/update_restart_unix_test.go +++ b/internal/app/update_restart_unix_test.go @@ -13,16 +13,19 @@ import ( "testing" "time" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/security" "cyberstrike-ai/internal/update" + + "go.uber.org/zap" ) -func TestStandaloneUpdateRestartExecsReplacement(t *testing.T) { +func copyRestartTestBinary(t *testing.T, binary string) { + t.Helper() self, err := os.Executable() if err != nil { t.Fatal(err) } - root := t.TempDir() - binary := filepath.Join(root, update.Binary) src, err := os.Open(self) if err != nil { t.Fatal(err) @@ -39,6 +42,12 @@ func TestStandaloneUpdateRestartExecsReplacement(t *testing.T) { if copyErr != nil { t.Fatal(copyErr) } +} + +func TestStandaloneUpdateRestartExecsReplacement(t *testing.T) { + root := t.TempDir() + binary := filepath.Join(root, update.Binary) + copyRestartTestBinary(t, binary) replacement := filepath.Join(root, "next") if err := os.WriteFile(replacement, []byte("#!/bin/sh\nprintf 'replacement:%s:%s:%s:%s\\n' \"$$\" \"$PWD\" \"$CSAI_RESTART_TEST\" \"$1\"\n"), 0o755); err != nil { t.Fatal(err) @@ -64,6 +73,83 @@ func TestStandaloneUpdateRestartExecsReplacement(t *testing.T) { } } +func TestUpdateRestartExecsWithLiveSessions(t *testing.T) { + root := t.TempDir() + binary := filepath.Join(root, update.Binary) + copyRestartTestBinary(t, binary) + copyRestartTestBinary(t, filepath.Join(root, "next")) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, binary, "-test.run=^TestUpdateSessionHandoffChild$") + cmd.Dir = root + cmd.Env = []string{"CSAI_RESTART_TEST=handoff"} + out, err := cmd.CombinedOutput() + if err != nil || !strings.Contains(string(out), "session handoff verified") { + t.Fatalf("session handoff helper: %v\n%s", err, out) + } +} + +func TestUpdateSessionHandoffChild(t *testing.T) { + if os.Getenv("CSAI_RESTART_TEST") != "handoff" { + return + } + handoff := TakeUpdateSessionHandoff() + db, err := database.NewDB("test.db", zap.NewNop()) + if err != nil { + t.Fatal(err) + } + a := App{auth: security.NewAuthManager(12), db: db} + defer a.Shutdown() + password, err := a.auth.AttachRBACStore(db) + if err != nil { + t.Fatal(err) + } + if token := os.Getenv("CSAI_RESTART_TEST_TOKEN"); token != "" { + if handoff == nil || os.Getenv(updateSessionsEnv) != "" { + t.Fatal("replacement did not claim the private handoff") + } + a.RestoreUpdateSessions(handoff) + session, ok := a.auth.ValidateToken(token) + if !ok || session.Token != token || session.UserID != "admin" || !session.Permissions["update:apply"] || + session.ExpiresAt.Format(time.RFC3339Nano) != os.Getenv("CSAI_RESTART_TEST_EXPIRY") { + t.Fatal("replacement lost login, permissions or original expiration") + } + if _, ok := a.auth.ValidateToken(os.Getenv("CSAI_RESTART_TEST_REVOKED")); ok { + t.Fatal("replacement accepted a logged-out session") + } + fmt.Println("session handoff verified") + return + } + + token, expires, err := a.auth.Authenticate("admin", password) + if err != nil { + t.Fatal(err) + } + revoked, _, err := a.auth.Authenticate("admin", password) + if err != nil { + t.Fatal(err) + } + a.auth.RevokeToken(revoked) + // The test replacement needs the original client credentials to exercise validation. + t.Setenv("CSAI_RESTART_TEST_TOKEN", token) + t.Setenv("CSAI_RESTART_TEST_EXPIRY", expires.Format(time.RFC3339Nano)) + t.Setenv("CSAI_RESTART_TEST_REVOKED", revoked) + + prepare := a.updateRestart(".") + if prepare == nil { + t.Fatal("standalone install did not offer restart") + } + if err := os.Rename("next", update.Binary); err != nil { + t.Fatal(err) + } + restart, err := prepare() + if err != nil { + t.Fatal(err) + } + restart() + t.Fatal("exec returned instead of switching executables") +} + func TestUpdateRestartChild(t *testing.T) { if os.Getenv("CSAI_RESTART_TEST") != "standalone" { return diff --git a/internal/security/auth_manager.go b/internal/security/auth_manager.go index 48f25f77..6f15c04f 100644 --- a/internal/security/auth_manager.go +++ b/internal/security/auth_manager.go @@ -1,6 +1,7 @@ package security import ( + "crypto/sha256" "database/sql" "errors" "strings" @@ -28,15 +29,20 @@ type Session struct { Permissions map[string]bool PermissionScopes map[string]string Scope string + userUpdatedAt time.Time } +type sessionDigest = [sha256.Size]byte + +func tokenDigest(token string) sessionDigest { return sha256.Sum256([]byte(token)) } + // AuthManager manages password-based authentication and session lifecycle. type AuthManager struct { sessionDuration time.Duration db *database.DB mu sync.RWMutex - sessions map[string]Session + sessions map[sessionDigest]Session // Changes when cached authorization is revoked, including while a login // is resolving access outside mu. accessVersion uint64 @@ -50,7 +56,7 @@ func NewAuthManager(sessionDurationHours int) *AuthManager { return &AuthManager{ sessionDuration: time.Duration(sessionDurationHours) * time.Hour, - sessions: make(map[string]Session), + sessions: make(map[sessionDigest]Session), } } @@ -111,7 +117,9 @@ func (a *AuthManager) publishSession(session Session, version uint64) bool { if a.accessVersion != version { return false } - a.sessions[session.Token] = session + digest := tokenDigest(session.Token) + session.Token = "" + a.sessions[digest] = session return true } @@ -144,21 +152,30 @@ func (a *AuthManager) authenticateSession(username, password string) (Session, e if err != nil { return Session{}, err } + if !access.User.Enabled || access.User.PasswordHash != user.PasswordHash { + return Session{}, ErrInvalidPassword + } + session := sessionForAccess(access, expiresAt) + session.Token = token + return session, nil +} + +func sessionForAccess(access *database.RBACAccess, expiresAt time.Time) Session { roleIDs := make([]string, 0, len(access.Roles)) for _, role := range access.Roles { roleIDs = append(roleIDs, role.ID) } return Session{ - Token: token, ExpiresAt: expiresAt, - UserID: user.ID, - Username: user.Username, - DisplayName: user.DisplayName, + UserID: access.User.ID, + Username: access.User.Username, + DisplayName: access.User.DisplayName, Roles: roleIDs, Permissions: access.Permissions, PermissionScopes: access.PermissionScopes, Scope: access.Scope, - }, nil + userUpdatedAt: access.User.UpdatedAt, + } } func (s Session) ScopeFor(permission string) string { @@ -174,8 +191,9 @@ func (a *AuthManager) ValidateToken(token string) (Session, bool) { return Session{}, false } + digest := tokenDigest(token) a.mu.RLock() - session, ok := a.sessions[token] + session, ok := a.sessions[digest] a.mu.RUnlock() if !ok { return Session{}, false @@ -183,11 +201,12 @@ func (a *AuthManager) ValidateToken(token string) (Session, bool) { if time.Now().After(session.ExpiresAt) { a.mu.Lock() - delete(a.sessions, token) + delete(a.sessions, digest) a.mu.Unlock() return Session{}, false } + session.Token = token return session, true } @@ -247,7 +266,7 @@ func (a *AuthManager) RevokeToken(token string) { } a.mu.Lock() - delete(a.sessions, token) + delete(a.sessions, tokenDigest(token)) a.mu.Unlock() } @@ -289,7 +308,7 @@ func (a *AuthManager) RevokeRoleSessions(roleID string) { func (a *AuthManager) RevokeAllSessions() { a.mu.Lock() a.accessVersion++ - a.sessions = make(map[string]Session) + a.sessions = make(map[sessionDigest]Session) a.mu.Unlock() } diff --git a/internal/security/auth_restart.go b/internal/security/auth_restart.go new file mode 100644 index 00000000..2248a40d --- /dev/null +++ b/internal/security/auth_restart.go @@ -0,0 +1,78 @@ +package security + +import ( + "database/sql" + "encoding/json" + "errors" + "io" + "time" + + "cyberstrike-ai/internal/database" +) + +type restartSession struct { + Digest sessionDigest + UserID string + ExpiresAt time.Time + UserUpdatedAt time.Time +} + +// HandoffSessions runs the update exec with the session map locked. A logout or +// revocation cannot complete in the old process after its token is handed off. +// The payload contains token digests only, and is passed through a private descriptor. +func (a *AuthManager) HandoffSessions(exec func([]byte) error) error { + a.mu.Lock() + defer a.mu.Unlock() + now := time.Now() + var active []restartSession + for digest, s := range a.sessions { + if s.ExpiresAt.After(now) { + active = append(active, restartSession{digest, s.UserID, s.ExpiresAt, s.userUpdatedAt}) + } + } + if len(active) == 0 { + return exec(nil) + } + payload, err := json.Marshal(active) + if err != nil { + return err + } + return exec(payload) +} + +// RestoreRestartSessions is called before the replacement starts serving. +// Rebuild access from the current RBAC store and keep the original expiration. +func (a *AuthManager) RestoreRestartSessions(r io.Reader) error { + var saved []restartSession + if err := json.NewDecoder(r).Decode(&saved); err != nil { + return err + } + a.mu.Lock() + defer a.mu.Unlock() + if a.db == nil { + return errors.New("authentication store is not configured") + } + accessByUser := make(map[string]*database.RBACAccess) + restored := make(map[sessionDigest]Session, len(saved)) + now := time.Now() + for _, entry := range saved { + if !entry.ExpiresAt.After(now) { + continue + } + access, loaded := accessByUser[entry.UserID] + if !loaded { + var err error + access, err = a.db.ResolveRBACAccess(entry.UserID) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return err + } + accessByUser[entry.UserID] = access + } + if access == nil || !access.User.Enabled || !access.User.UpdatedAt.Equal(entry.UserUpdatedAt) { + continue + } + restored[entry.Digest] = sessionForAccess(access, entry.ExpiresAt) + } + a.sessions = restored + return nil +} diff --git a/internal/security/auth_restart_test.go b/internal/security/auth_restart_test.go new file mode 100644 index 00000000..6d3937b7 --- /dev/null +++ b/internal/security/auth_restart_test.go @@ -0,0 +1,65 @@ +package security + +import ( + "bytes" + "path/filepath" + "testing" + "time" + + "cyberstrike-ai/internal/database" + + "go.uber.org/zap" +) + +func TestRestartHandoffRejectsExpiredAndChangedAccounts(t *testing.T) { + db, err := database.NewDB(filepath.Join(t.TempDir(), "auth.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + old := NewAuthManager(12) + password, err := old.AttachRBACStore(db) + if err != nil { + t.Fatal(err) + } + token, _, err := old.Authenticate("admin", password) + if err != nil { + t.Fatal(err) + } + digest := tokenDigest("expired-token") + expired := old.sessions[tokenDigest(token)] + expired.ExpiresAt = time.Now().Add(-time.Second) + old.sessions[digest] = expired + + var handoff []byte + if err := old.HandoffSessions(func(payload []byte) error { + handoff = payload + return nil + }); err != nil { + t.Fatal(err) + } + if len(handoff) == 0 || bytes.Contains(handoff, []byte(token)) { + t.Fatal("handoff must contain only the digest of the active token") + } + next := NewAuthManager(12) + if _, err := next.AttachRBACStore(db); err != nil { + t.Fatal(err) + } + if err := next.RestoreRestartSessions(bytes.NewReader(handoff)); err != nil { + t.Fatal(err) + } + if len(next.sessions) != 1 { + t.Fatalf("restored %d sessions, want exactly the unexpired session", len(next.sessions)) + } + + // Simulate a password change committed to the store before revocation reached the old map. + if err := old.UpdateUserPassword("admin", "changed-test-password"); err != nil { + t.Fatal(err) + } + if err := next.RestoreRestartSessions(bytes.NewReader(handoff)); err != nil { + t.Fatal(err) + } + if _, ok := next.ValidateToken(token); ok { + t.Fatal("restored a session issued before the account changed") + } +} diff --git a/internal/security/auth_role_sessions_test.go b/internal/security/auth_role_sessions_test.go index 3e20fb33..f09ff644 100644 --- a/internal/security/auth_role_sessions_test.go +++ b/internal/security/auth_role_sessions_test.go @@ -14,7 +14,7 @@ func TestRevokeRoleSessionsMatchesSnapshotAndPreservesOthers(t *testing.T) { {Token: "admin", UserID: "admin", Roles: []string{"admin"}}, } { session.ExpiresAt = time.Now().Add(time.Hour) - a.sessions[session.Token] = session + a.sessions[tokenDigest(session.Token)] = session } a.RevokeRoleSessions(" ") if len(a.sessions) != 4 { diff --git a/web/static/css/style.css b/web/static/css/style.css index bc536bee..59e09e1d 100644 --- a/web/static/css/style.css +++ b/web/static/css/style.css @@ -47221,25 +47221,6 @@ html[data-theme="dark"] { --tool-blocked-color: #f4bc62; } margin: 10px 0; } -.update-restart-choice { - display: flex; - align-items: flex-start; - gap: 8px; - font-size: 13px; - color: var(--text-primary); - cursor: pointer; - margin: 4px 0; -} - -.update-restart-choice input { - margin-top: 2px; -} - -.update-restart-preview { - border-left: 3px solid var(--border-color); - padding-left: 10px; -} - .update-blocker-list { margin: 6px 0 0; padding-left: 18px; diff --git a/web/static/i18n/ar-SA.json b/web/static/i18n/ar-SA.json index e6625834..4505adcc 100644 --- a/web/static/i18n/ar-SA.json +++ b/web/static/i18n/ar-SA.json @@ -147,13 +147,8 @@ "blockedLocalEdits": "{{n}} من ملفّات مصدر المنتج معدّلة محلّيًا ولن يستبدلها التحديث: أودِعها أو تراجع عنها أوّلًا.", "blockedDiverged": "السجلّ المحلّي متقدّم بمقدار {{ahead}} إيداع ومتأخّر بمقدار {{behind}}: هذا دمج وليس تنزيلًا، لذا عالجه يدويًا.", "blockedNoUpdate": "مصدر التحديث لا يحتوي على أيّ شيء أحدث من هذا الجهاز (اضغط على التحقّق من التحديثات إن لم تكن قد راجعت بعد).", - "restartChoiceLabel": "التبديل تلقائيًا إلى الإصدار الجديد", "restartNotWired": "لا تدعم طريقة التشغيل الحالية التبديل التلقائي. بعد استبدال الملف التنفيذي، أعد تشغيل الخدمة بالطريقة المعتادة في بيئتك.", "confirmRestartYes": "تظلّ الخدمة متاحة أثناء البناء، ثم تعيد التشغيل لفترة وجيزة للتبديل إلى الإصدار الجديد. تُعاد الصفحة تلقائيًا.", - "confirmRestartNo": "يستمر الإصدار القديم في العمل إلى أن تعيد تشغيل الخدمة.", - "confirmApply": "على وشك التنفيذ: التحديث من {{repo}} إلى {{target}} ({{n}} إيداع جديد، هذا الجهاز عند {{commit}}) -> إعادة بناء الملف الثنائي -> نسخ القديم احتياطيًا واستبداله.", - "confirmBuildPending": "على وشك التنفيذ: بناء الملف الثنائي المفقود للمصدر الموجود بالفعل (هذا الجهاز عند {{commit}}) -> إعادة البناء -> نسخ القديم احتياطيًا واستبدال الملف الثنائي القديم.", - "applyAccepted": "بدأ التحديث (المهمّة {{id}})؛ يتحدّث التقدّم كلّ 1.5 ثانية.", "localChangesTitle": "التغييرات المحلّية", "localChangesHint": "تُحفظ الملفّات المعلّمة كمحتوى محلّي كما هي تمامًا؛ أمّا الملفّات المعلّمة كمصدر منتج فتمنع التحديث التلقائي.", "noLocalChanges": "شجرة العمل نظيفة: لا يوجد ملفّ متتبَّع معدّل أو محذوف.", @@ -182,7 +177,7 @@ "restartRequestedToast": "جارٍ تبديل الإصدار. تُعاد الصفحة عند عودة الخدمة.", "restartFailed": "فشل طلب إعادة التشغيل: {{reason}}", "restartOverlayTitle": "جارٍ إعادة تشغيل الخدمة…", - "restartOverlayBody": "تُعاد الصفحة عند عودة الخدمة. ستحتاج إلى تسجيل الدخول مرة أخرى.", + "restartOverlayBody": "ستُعاد الصفحة تلقائيًا عندما يصبح الإصدار الجديد جاهزًا.", "restartOverlaySlowRunning": "لا تزال الخدمة تستجيب بوصفها العملية القديمة - يبدو أنّ إعادة التشغيل لم تحدث. استخدم الزرّ أدناه لمعاينة الحالة الحالية.", "restartOverlaySlowDown": "لم تعد الخدمة بعد. ستواصل الصفحة المحاولة. راجع سجلّات الخدمة إذا استمر الانقطاع.", "restartOverlayRefresh": "تحديث هذه الصفحة", diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index 82d234fd..2f796f37 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -147,13 +147,8 @@ "blockedLocalEdits": "{{n}} product source files are edited locally and an update will not overwrite them: commit or revert them first.", "blockedDiverged": "Local history is {{ahead}} commits ahead and {{behind}} behind: that is a merge, not a download, so handle it by hand.", "blockedNoUpdate": "The update source has nothing newer than this machine (press Check for updates if you have not looked yet).", - "restartChoiceLabel": "Switch to the new version automatically", "restartNotWired": "This installation cannot switch versions automatically. Restart the service through your deployment setup after the binary is replaced.", "confirmRestartYes": "The service stays available during the build, then briefly restarts to switch versions. This page reloads automatically.", - "confirmRestartNo": "The old version keeps running until you restart the service.", - "confirmApply": "About to run: update from {{repo}} to {{target}} ({{n}} new commits, this machine is at {{commit}}) -> rebuild the binary -> back up and replace the old one.", - "confirmBuildPending": "About to run: build the missing binary for the source already in place (this machine is at {{commit}}) -> rebuild -> back up and replace the old binary.", - "applyAccepted": "Update started (job {{id}}); progress refreshes every 1.5 seconds.", "localChangesTitle": "Local changes", "localChangesHint": "Files marked local content are kept exactly as they are; files marked product source block the automatic update.", "noLocalChanges": "Working tree clean: no tracked file is modified or deleted.", @@ -182,7 +177,7 @@ "restartRequestedToast": "Switching versions. This page reloads when the service is back.", "restartFailed": "Restart request failed: {{reason}}", "restartOverlayTitle": "Restarting the service…", - "restartOverlayBody": "This page reloads when the service is back. You will need to sign in again.", + "restartOverlayBody": "This page will reload automatically when the new version is ready.", "restartOverlaySlowRunning": "The service is still answering as the old process - the restart does not seem to have happened. Use the button below to look at the current state.", "restartOverlaySlowDown": "The service is taking longer to come back. This page will keep trying. Check the service logs if it remains unavailable.", "restartOverlayRefresh": "Refresh this page", diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index 3f0996b1..88aa4f8e 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -147,13 +147,8 @@ "blockedLocalEdits": "{{n}} файлов исходного кода изменены локально, и обновление не будет их перезаписывать: сначала закоммитьте или отмените изменения.", "blockedDiverged": "Локальная история впереди на {{ahead}} коммитов и отстаёт на {{behind}}: это слияние, а не загрузка, разберитесь вручную.", "blockedNoUpdate": "В источнике обновлений нет ничего новее этой машины (нажмите «Проверить обновления», если ещё не смотрели).", - "restartChoiceLabel": "Автоматически перейти на новую версию", "restartNotWired": "Этот способ запуска не поддерживает автоматический переход. После замены файла перезапустите службу штатным способом.", "confirmRestartYes": "Во время сборки служба продолжит работу. Для перехода она кратковременно перезапустится, и страница обновится сама.", - "confirmRestartNo": "Старая версия продолжит работать до перезапуска службы.", - "confirmApply": "Сейчас будет выполнено: обновление из {{repo}} до {{target}} ({{n}} новых коммитов, эта машина на {{commit}}) -> пересборка бинарного файла -> резервная копия и замена старого.", - "confirmBuildPending": "Сейчас будет выполнено: сборка недостающего бинарного файла для уже установленных исходников (эта машина на {{commit}}) -> пересборка -> резервная копия и замена старого бинарного файла.", - "applyAccepted": "Обновление запущено (задача {{id}}); ход обновляется каждые 1,5 секунды.", "localChangesTitle": "Локальные изменения", "localChangesHint": "Файлы, помеченные как локальное содержимое, сохраняются как есть; файлы, помеченные как исходный код продукта, блокируют автоматическое обновление.", "noLocalChanges": "Рабочее дерево чистое: ни один отслеживаемый файл не изменён и не удалён.", @@ -182,7 +177,7 @@ "restartRequestedToast": "Переключаем версию. Страница обновится, когда служба снова будет доступна.", "restartFailed": "Не удалось запросить перезапуск: {{reason}}", "restartOverlayTitle": "Перезапуск службы…", - "restartOverlayBody": "Страница обновится, когда служба снова будет доступна. Потребуется войти заново.", + "restartOverlayBody": "Когда новая версия будет готова, страница обновится автоматически.", "restartOverlaySlowRunning": "Служба по-прежнему отвечает старым процессом — перезапуск, похоже, не произошёл. Нажмите кнопку ниже, чтобы увидеть текущее состояние.", "restartOverlaySlowDown": "Служба пока недоступна. Страница продолжит попытки. Если служба долго не отвечает, проверьте её журналы.", "restartOverlayRefresh": "Обновить страницу", diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index 0289e55e..4b3f585c 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -147,13 +147,8 @@ "blockedLocalEdits": "有 {{n}} 个产品源码文件被本地改过,自动更新不会覆盖它们:先提交或还原。", "blockedDiverged": "本地领先 {{ahead}} 个提交、落后 {{behind}} 个提交:这是合并而不是下载,请先手工处理。", "blockedNoUpdate": "更新源没有比本机更新的提交(还没查过就先点「检查更新」)。", - "restartChoiceLabel": "更新成功后自动切换到新版本", "restartNotWired": "当前启动方式不支持自动切换。换入二进制后,请通过部署方式重启服务。", "confirmRestartYes": "构建期间服务照常运行;新版本就绪后会短暂重启,页面随后自动刷新。", - "confirmRestartNo": "构建完成后仍运行旧版本,待你重启再切换。", - "confirmApply": "将要执行:从更新源 {{repo}} 更新到 {{target}}({{n}} 个新提交,本机当前 {{commit}})→ 重新编译二进制 → 备份并替换旧二进制。", - "confirmBuildPending": "将要执行:为已经就位的源码补上二进制(本机当前 {{commit}})→ 重新编译 → 备份并替换旧二进制。", - "applyAccepted": "更新已开始(任务 {{id}}),进度每 1.5 秒刷新一次。", "localChangesTitle": "本机改动", "localChangesHint": "标为「本机内容」的文件更新后原样保留;标为「产品源码」的文件会阻止自动更新。", "noLocalChanges": "工作树干净:没有被修改或被删除的受跟踪文件。", @@ -182,7 +177,7 @@ "restartRequestedToast": "正在切换版本,服务恢复后页面会自动刷新。", "restartFailed": "重启请求失败:{{reason}}", "restartOverlayTitle": "正在重启服务…", - "restartOverlayBody": "服务恢复后页面会自动刷新。当前登录会话会结束,请重新登录。", + "restartOverlayBody": "切换完成后,页面会自动恢复。", "restartOverlaySlowRunning": "服务仍在以旧进程应答——重启似乎没有发生。可点下方按钮刷新页面查看当前状态。", "restartOverlaySlowDown": "服务仍未恢复,页面会继续重试。如果长时间无法连接,请检查服务日志。", "restartOverlayRefresh": "立即刷新页面", diff --git a/web/static/js/permission-gate-state.test.cjs b/web/static/js/permission-gate-state.test.cjs index 8e72d998..f68b35f8 100644 --- a/web/static/js/permission-gate-state.test.cjs +++ b/web/static/js/permission-gate-state.test.cjs @@ -91,7 +91,7 @@ test('every control the update page disables by state carries the marker the gat console, escapeHtml: (v) => String(v), updateT: (key) => key, - renderUpdateRestartChoice: () => '', + renderUpdateSwitchHint: () => '', renderUpdateChangesTable: () => '
', isUpdateJobRunning: () => true, updateApplyBlockers: (status) => (status.blockingChanges || []).length ? ['blocked'] : [], diff --git a/web/static/js/update-ui.test.cjs b/web/static/js/update-ui.test.cjs index f80bba7a..4c885bd3 100644 --- a/web/static/js/update-ui.test.cjs +++ b/web/static/js/update-ui.test.cjs @@ -14,7 +14,7 @@ const ru = JSON.parse(fs.readFileSync('web/static/i18n/ru-RU.json', 'utf8')); // The only handlers this console is allowed to wire into markup. const HANDLES = ['startUpdateApply', 'checkForUpdates', 'rollbackUpdate', - 'updateRestartChoiceChanged', 'loadUpdateConsole', + 'loadUpdateConsole', 'saveUpdateSource', 'previewAdoptSource', 'confirmAdoptSource', 'startRestartNow', 'refreshUpdatePage']; @@ -168,8 +168,6 @@ function harness(options) { const el = { id, innerHTML: '', - checked: id === 'update-restart-choice' && - /id="update-restart-choice" checked/.test(nodes.get('update-console')?.innerHTML || ''), insertAdjacentHTML(_pos, html) { this.innerHTML = html + this.innerHTML; }, }; // 控制台住在系统设置页的「一键更新」分区里:页面和分区都得是 active,它才算在前台。 @@ -228,6 +226,8 @@ function harness(options) { String, Date, Math, + URLSearchParams, + authToken: 'test-session', escapeHtml(text) { const div = sandbox.document.createElement('div'); div.textContent = text; @@ -302,6 +302,9 @@ function harness(options) { }); }, fetch(url, reqOpts = {}) { + if (url === '/api/system/update/job') { + return sandbox.apiFetch(url, reqOpts); + } fetchProbes.push({ url, opts: reqOpts }); const answer = probeQueue.length > 1 ? probeQueue.shift() : (probeQueue[0] || 'ok'); if (answer === 'down') { @@ -328,6 +331,7 @@ function harness(options) { location: { pathname: '/', hash: '', + search: opts.search || '', replaced: [], reloads: 0, replace(target) { this.replaced.push(target); }, @@ -340,12 +344,11 @@ function harness(options) { vm.runInContext(` this.api = { loadUpdateConsole, checkForUpdates, startUpdateApply, rollbackUpdate, - updateRestartChoiceChanged, pollUpdateJob, renderUpdateConsole, stopUpdatePolling, + pollUpdateJob, renderUpdateConsole, stopUpdatePolling, startRestartNow }; this.vars = { setBusy(v) { updateBusy = v; }, - getRestartChoice() { return updateRestartChoice; }, getPollTimer() { return updatePollTimer; }, getCheckDone() { return updateCheck.done; }, autoCheckDone() { return updateAutoCheckDone; }, @@ -436,7 +439,7 @@ test('the console lives inside the settings page as its own section', () => { 'settings-section-update must live inside page-settings'); assert.match(template, /id="settings-section-update"[\s\S]{0,700}?id="update-console"/); assert.match(template, /id="update-console"/); - assert.match(template, / - +