Files
l-ui/internal/agent/update_test.go
T
Muse e5d42224aa decouple agent version line from panel version
Agent display version now comes from the agent line's own source
(config.agentDisplayVersion injection + defaultAgentDisplayVersion
constant, currently A2.3.0) instead of being derived from the panel's
displayVersion. Masters resolve the agent line's latest from each
release's agent-version.txt marker (selfupdate.ResolveLatestAgentTarget,
legacy tag derivation as fallback for pre-marker releases): update
intents target the marker under the panel tag, panel-only releases
produce no intent, and the nodes page badges agent rows against
their own line via PanelUpdateInfo.displayLatestAgentVersion.

Windows agent frozen at A2.2.1: release discipline in docs/release.md
+ scripts/release-build.sh (agent assets reused verbatim when the
agent code is unchanged, marker always emitted, no Windows exe),
install-agent.ps1 pinned at V2.4.0, and the A2.2.1 protocol shapes
locked by TestAgentLegacyWindows221Contract.

Agent update tests now derive their targets from the live agent
line instead of a hardcoded A2.0.x the line has passed.
2026-10-23 21:47:10 +00:00

220 lines
6.8 KiB
Go

package agent
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"sync/atomic"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/config"
"github.com/mhsanaei/3x-ui/v3/internal/selfupdate"
)
// nextAgentTarget returns an intent target one patch above the test
// binary's own agent-line version. The update tests must ride the
// agent line wherever it currently stands (A2.3.0 since the version
// decoupling) instead of hardcoding a version the line has already
// passed — a hardcoded "newer" target silently degrades into an
// already-current skip when the default agent version moves.
func nextAgentTarget(t *testing.T) string {
t.Helper()
parts, ok := config.ParseDisplayVersion(config.GetAgentDisplayVersion())
if !ok {
t.Fatalf("agent display version %q does not parse", config.GetAgentDisplayVersion())
}
return fmt.Sprintf("A%d.%d.%d", parts[0], parts[1], parts[2]+1)
}
// Item 20: the agent consumes the master's update intent, downloads the
// release asset for its architecture, verifies the sha256 sidecar, swaps
// the binary keeping a .bak, and re-execs. Failures must leave the old
// binary running and produce a "failed" report.
func fakeReleaseServer(t *testing.T, payload []byte, goodSum bool, hits *atomic.Int32) *httptest.Server {
t.Helper()
// The agent requests the standalone agent asset (agent/panel
// split); the fake release only serves that name.
asset, err := selfupdate.AgentAssetName(runtime.GOARCH)
if err != nil {
t.Fatal(err)
}
sum := sha256.Sum256(payload)
if !goodSum {
sum = sha256.Sum256([]byte("something else"))
}
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if hits != nil {
hits.Add(1)
}
switch {
case strings.HasSuffix(r.URL.Path, asset+".sha256"):
_, _ = w.Write([]byte(hex.EncodeToString(sum[:]) + " " + asset + "\n"))
case strings.HasSuffix(r.URL.Path, asset):
_, _ = w.Write(payload)
default:
http.NotFound(w, r)
}
}))
}
func newUpdateTestAgent(t *testing.T, masterURL string) (*Agent, string) {
t.Helper()
dir := t.TempDir()
exe := filepath.Join(dir, "xui-agent")
if err := os.WriteFile(exe, []byte("old-binary"), 0o755); err != nil {
t.Fatal(err)
}
a := &Agent{
config: &Config{MasterURL: masterURL, Token: "tok", NodeName: "n"},
httpClient: http.DefaultClient,
exePathOverride: exe,
}
return a, exe
}
func stubExec(t *testing.T, err error) *atomic.Int32 {
t.Helper()
calls := &atomic.Int32{}
orig := execSelf
execSelf = func(string) error {
calls.Add(1)
return err
}
t.Cleanup(func() { execSelf = orig })
return calls
}
func TestAgentUpdateSwapsAndRestarts(t *testing.T) {
srv := fakeReleaseServer(t, []byte("new-binary"), true, nil)
defer srv.Close()
a, exe := newUpdateTestAgent(t, srv.URL)
execCalls := stubExec(t, nil)
a.runUpdate(updateIntent{RequestedAt: 42, Target: nextAgentTarget(t), Tag: "V2.0.1", BaseURL: srv.URL + "/"})
got, _ := os.ReadFile(exe)
if string(got) != "new-binary" {
t.Fatalf("exe after update = %q, want new-binary", got)
}
bak, _ := os.ReadFile(exe + ".bak")
if string(bak) != "old-binary" {
t.Fatalf(".bak = %q, want old-binary", bak)
}
if execCalls.Load() != 1 {
t.Fatalf("execSelf calls = %d, want 1", execCalls.Load())
}
if rep := a.currentUpdateReport(); rep == nil || rep.State != "swapped" {
t.Fatalf("report = %+v, want swapped", rep)
}
}
func TestAgentUpdateBadChecksumKeepsOldBinary(t *testing.T) {
srv := fakeReleaseServer(t, []byte("new-binary"), false, nil)
defer srv.Close()
a, exe := newUpdateTestAgent(t, srv.URL)
execCalls := stubExec(t, nil)
a.runUpdate(updateIntent{RequestedAt: 43, Target: nextAgentTarget(t), Tag: "V2.0.1", BaseURL: srv.URL + "/"})
got, _ := os.ReadFile(exe)
if string(got) != "old-binary" {
t.Fatalf("exe after failed update = %q, want old-binary", got)
}
if _, err := os.Stat(exe + ".bak"); !os.IsNotExist(err) {
t.Fatal("no .bak may be created when verification fails")
}
if execCalls.Load() != 0 {
t.Fatal("execSelf must not run when verification fails")
}
rep := a.currentUpdateReport()
if rep == nil || rep.State != "failed" || !strings.Contains(rep.Error, "sha256 mismatch") {
t.Fatalf("report = %+v, want failed with sha256 mismatch", rep)
}
}
func TestAgentUpdateAlreadyCurrentSkipsDownload(t *testing.T) {
var hits atomic.Int32
srv := fakeReleaseServer(t, []byte("new-binary"), true, &hits)
defer srv.Close()
a, exe := newUpdateTestAgent(t, srv.URL)
stubExec(t, nil)
// The intent target equals the test binary's own agent-line
// version: already current, whatever the line currently is.
a.runUpdate(updateIntent{RequestedAt: 44, Target: config.GetAgentDisplayVersion(), Tag: "V2.0.0", BaseURL: srv.URL + "/"})
if hits.Load() != 0 {
t.Fatalf("release server hit %d times for an already-current agent", hits.Load())
}
got, _ := os.ReadFile(exe)
if string(got) != "old-binary" {
t.Fatalf("exe = %q, want untouched old-binary", got)
}
if rep := a.currentUpdateReport(); rep == nil || rep.State != "current" {
t.Fatalf("report = %+v, want current", rep)
}
}
func TestAgentUpdateExecFailureRollsBack(t *testing.T) {
srv := fakeReleaseServer(t, []byte("new-binary"), true, nil)
defer srv.Close()
a, exe := newUpdateTestAgent(t, srv.URL)
stubExec(t, errExecBoom)
a.runUpdate(updateIntent{RequestedAt: 45, Target: nextAgentTarget(t), Tag: "V2.0.1", BaseURL: srv.URL + "/"})
got, _ := os.ReadFile(exe)
if string(got) != "old-binary" {
t.Fatalf("exe after exec failure = %q, want rolled-back old-binary", got)
}
if rep := a.currentUpdateReport(); rep == nil || rep.State != "failed" {
t.Fatalf("report = %+v, want failed", rep)
}
}
func TestAgentUpdateSkippedOnUnsupportedOS(t *testing.T) {
orig := selfUpdateSupported
selfUpdateSupported = false
t.Cleanup(func() { selfUpdateSupported = orig })
var hits atomic.Int32
srv := fakeReleaseServer(t, []byte("new-binary"), true, &hits)
defer srv.Close()
a, exe := newUpdateTestAgent(t, srv.URL)
intent := &updateIntent{RequestedAt: 46, Target: "A2.0.1", Tag: "V2.0.1", BaseURL: srv.URL + "/"}
a.maybeHandleUpdate(intent)
// A repeated delivery of the same intent is also a no-op.
a.maybeHandleUpdate(intent)
if hits.Load() != 0 {
t.Fatalf("release server hit %d times on an unsupported OS, want 0", hits.Load())
}
got, _ := os.ReadFile(exe)
if string(got) != "old-binary" {
t.Fatalf("exe = %q, want untouched old-binary", got)
}
a.updateMu.Lock()
handled, running := a.updateHandled, a.updateRunning
a.updateMu.Unlock()
if handled != 46 || running {
t.Fatalf("handled=%d running=%v, want handled=46 running=false", handled, running)
}
if rep := a.currentUpdateReport(); rep != nil {
t.Fatalf("report = %+v, want none for a skipped intent", rep)
}
}
var errExecBoom = &execBoomError{}
type execBoomError struct{}
func (*execBoomError) Error() string { return "exec boom" }