Files
l-ui/internal/agent/update_test.go
T

275 lines
8.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)
}
}
// ITEM-P3 rider: runUpdate must stop the sing-box core as well as
// xray before execSelf replaces the image. Pre-fix only xray was
// stopped, leaving the old sing-box orphaned on the inbound ports —
// the new image's core then died on bind every poll cycle and the
// orphan kept serving a stale config. The fake core is a real
// process so "stopped" is observable, and the exec stub records
// whether the core was already down at exec time (ordering matters:
// stopping after exec would be stopping in the wrong process).
func TestAgentUpdateStopsSingboxCoreBeforeExec(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("fake core is a shell script")
}
srv := fakeReleaseServer(t, []byte("new-binary"), true, nil)
defer srv.Close()
a, _ := newUpdateTestAgent(t, srv.URL)
dir := t.TempDir()
corePath := filepath.Join(dir, "sing-box")
if err := os.WriteFile(corePath, []byte("#!/bin/sh\nexec sleep 3600\n"), 0o755); err != nil {
t.Fatal(err)
}
cfgPath := filepath.Join(dir, "sb.json")
if err := os.WriteFile(cfgPath, []byte("{}"), 0o644); err != nil {
t.Fatal(err)
}
a.sbProc = &singboxProcess{}
if err := a.sbProc.start(corePath, cfgPath, filepath.Join(dir, "sb.log")); err != nil {
t.Fatalf("start fake core: %v", err)
}
if !a.singboxRunning() {
t.Fatal("fake sing-box core is not running")
}
t.Cleanup(func() { a.stopSingbox() })
var sbRunningAtExec atomic.Bool
orig := execSelf
execSelf = func(string) error {
sbRunningAtExec.Store(a.singboxRunning())
return nil
}
t.Cleanup(func() { execSelf = orig })
a.runUpdate(updateIntent{RequestedAt: 47, Target: nextAgentTarget(t), Tag: "V2.0.1", BaseURL: srv.URL + "/"})
if sbRunningAtExec.Load() {
t.Fatal("sing-box core was still running when execSelf fired")
}
if a.singboxRunning() {
t.Fatal("sing-box core is still running after the update")
}
if rep := a.currentUpdateReport(); rep == nil || rep.State != "swapped" {
t.Fatalf("report = %+v, want swapped", rep)
}
}
var errExecBoom = &execBoomError{}
type execBoomError struct{}
func (*execBoomError) Error() string { return "exec boom" }