panel_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. package panel
  2. import (
  3. "fmt"
  4. "os"
  5. "runtime"
  6. "sync"
  7. "sync/atomic"
  8. "testing"
  9. "time"
  10. "github.com/mhsanaei/3x-ui/v3/internal/config"
  11. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  12. )
  13. func TestIsNewerVersion(t *testing.T) {
  14. cases := []struct {
  15. latest string
  16. current string
  17. want bool
  18. }{
  19. {"v2.9.4", "2.9.3", true},
  20. {"v2.10.0", "2.9.9", true},
  21. {"v2.9.3", "2.9.3", false},
  22. {"v2.9.2", "2.9.3", false},
  23. {"v3.0.0", "2.9.3", true},
  24. }
  25. for _, tc := range cases {
  26. if got := isNewerVersion(tc.latest, tc.current); got != tc.want {
  27. t.Fatalf("isNewerVersion(%q, %q) = %v, want %v", tc.latest, tc.current, got, tc.want)
  28. }
  29. }
  30. }
  31. func TestCompareVersionStringsRejectsUnexpectedFormats(t *testing.T) {
  32. if _, ok := compareVersionStrings("latest", "2.9.3"); ok {
  33. t.Fatal("expected non-semver latest tag to be rejected")
  34. }
  35. if _, ok := compareVersionStrings("v2.9", "2.9.3"); ok {
  36. t.Fatal("expected short version to be rejected")
  37. }
  38. }
  39. func TestShellQuote(t *testing.T) {
  40. if got := shellQuote("/usr/bin/curl"); got != "'/usr/bin/curl'" {
  41. t.Fatalf("unexpected quote result: %s", got)
  42. }
  43. if got := shellQuote("/tmp/a'b"); got != "'/tmp/a'\\''b'" {
  44. t.Fatalf("unexpected quote result with single quote: %s", got)
  45. }
  46. }
  47. // TestUpdateProxyEnvVars covers the bug this function fixes: ambient proxy
  48. // vars must reach update.sh's systemd-run child, which inherits nothing.
  49. func TestUpdateProxyEnvVars(t *testing.T) {
  50. allKeys := []string{"https_proxy", "HTTPS_PROXY", "all_proxy", "ALL_PROXY", "http_proxy", "HTTP_PROXY", "no_proxy", "NO_PROXY"}
  51. clearAll := func(t *testing.T) {
  52. t.Helper()
  53. for _, key := range allKeys {
  54. t.Setenv(key, "")
  55. }
  56. }
  57. t.Run("nothing set returns nil", func(t *testing.T) {
  58. clearAll(t)
  59. if got := updateProxyEnvVars(); got != nil {
  60. t.Fatalf("updateProxyEnvVars() = %v, want nil", got)
  61. }
  62. })
  63. t.Run("forwards each set var under its own name", func(t *testing.T) {
  64. clearAll(t)
  65. t.Setenv("https_proxy", "socks5://127.0.0.1:10808")
  66. t.Setenv("no_proxy", "10.0.0.0/8,localhost")
  67. got := updateProxyEnvVars()
  68. want := []string{"https_proxy=socks5://127.0.0.1:10808", "no_proxy=10.0.0.0/8,localhost"}
  69. if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
  70. t.Fatalf("updateProxyEnvVars() = %v, want %v", got, want)
  71. }
  72. })
  73. // A deliberately HTTP-only proxy config must not silently gain HTTPS traffic.
  74. t.Run("http_proxy is not promoted to https_proxy", func(t *testing.T) {
  75. clearAll(t)
  76. t.Setenv("http_proxy", "http://127.0.0.1:8080")
  77. got := updateProxyEnvVars()
  78. want := []string{"http_proxy=http://127.0.0.1:8080"}
  79. if len(got) != len(want) || got[0] != want[0] {
  80. t.Fatalf("updateProxyEnvVars() = %v, want %v", got, want)
  81. }
  82. })
  83. }
  84. func TestExtractReleaseCommit(t *testing.T) {
  85. full := "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b"
  86. cases := []struct {
  87. name string
  88. release service.Release
  89. want string
  90. }{
  91. {
  92. name: "from body marker",
  93. release: service.Release{Body: "Rolling build\n\ncommit=" + full + "\nbuilt=2026-06-24T00:00:00Z"},
  94. want: full,
  95. },
  96. {
  97. name: "body marker is case-insensitive and wins over target",
  98. release: service.Release{Body: "COMMIT=" + full, TargetCommitish: "deadbeef"},
  99. want: full,
  100. },
  101. {
  102. name: "fallback to target commit sha",
  103. release: service.Release{Body: "no marker here", TargetCommitish: full},
  104. want: full,
  105. },
  106. {
  107. name: "branch target is not a commit",
  108. release: service.Release{Body: "no marker", TargetCommitish: "main"},
  109. want: "",
  110. },
  111. }
  112. for _, tc := range cases {
  113. if got := extractReleaseCommit(&tc.release); got != tc.want {
  114. t.Fatalf("%s: extractReleaseCommit = %q, want %q", tc.name, got, tc.want)
  115. }
  116. }
  117. }
  118. func TestCommitsEqual(t *testing.T) {
  119. full := "1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b"
  120. cases := []struct {
  121. a, b string
  122. want bool
  123. }{
  124. {"1a2b3c4d", full, true}, // injected 8-char prefix matches full release sha
  125. {full, "1a2b3c4d", true}, // order independent
  126. {"1A2B3C4D", full, true}, // case insensitive
  127. {"deadbeef", full, false}, // different commit
  128. {"", full, false}, // empty current never matches
  129. {"1a2b3c4d", "", false}, // empty latest never matches
  130. }
  131. for _, tc := range cases {
  132. if got := commitsEqual(tc.a, tc.b); got != tc.want {
  133. t.Fatalf("commitsEqual(%q, %q) = %v, want %v", tc.a, tc.b, got, tc.want)
  134. }
  135. }
  136. }
  137. func TestShortCommit(t *testing.T) {
  138. if got := shortCommit("1a2b3c4d5e6f7a8b"); got != "1a2b3c4d" {
  139. t.Fatalf("shortCommit truncation = %q, want %q", got, "1a2b3c4d")
  140. }
  141. if got := shortCommit("abc"); got != "abc" {
  142. t.Fatalf("shortCommit short input = %q, want %q", got, "abc")
  143. }
  144. }
  145. func resetUpdateSlot(t *testing.T) {
  146. t.Helper()
  147. t.Cleanup(func() {
  148. updateMu.Lock()
  149. updateRunning = false
  150. updateRunID = 0
  151. updatePID = 0
  152. updateMu.Unlock()
  153. })
  154. }
  155. // writeStatusFile hand-writes the status file in the exact wire format
  156. // update.sh itself produces (a bare printf, not Go's json.Marshal), since
  157. // that's the real cross-language contract this package reads in production.
  158. func writeStatusFile(t *testing.T, path string, runID int64, state string) {
  159. t.Helper()
  160. body := fmt.Sprintf(`{"runId":"%d","state":"%s","exitCode":0,"finishedAt":%d}`, runID, state, time.Now().Unix())
  161. if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
  162. t.Fatal(err)
  163. }
  164. }
  165. func TestAcquireUpdateSlot(t *testing.T) {
  166. resetUpdateSlot(t)
  167. if !acquireUpdateSlot(1) {
  168. t.Fatal("first acquire: got false, want true")
  169. }
  170. if acquireUpdateSlot(2) {
  171. t.Fatal("second acquire while first is held: got true, want false")
  172. }
  173. releaseUpdateSlot()
  174. if !acquireUpdateSlot(3) {
  175. t.Fatal("acquire after release: got false, want true")
  176. }
  177. releaseUpdateSlot()
  178. }
  179. func TestAcquireUpdateSlotExpiresAfterStaleWindow(t *testing.T) {
  180. resetUpdateSlot(t)
  181. if !acquireUpdateSlot(1) {
  182. t.Fatal("first acquire: got false, want true")
  183. }
  184. updateMu.Lock()
  185. updateStarted = time.Now().Add(-(updateStaleAfter + time.Second))
  186. updateMu.Unlock()
  187. if !acquireUpdateSlot(2) {
  188. t.Fatal("acquire after stale window elapsed: got false, want true")
  189. }
  190. releaseUpdateSlot()
  191. }
  192. // TestAcquireUpdateSlotWaitsForAliveProcessPastStaleWindow is the regression
  193. // test for the concurrency bug an upstream review found: past
  194. // updateStaleAfter, the old logic freed the slot purely on elapsed time, even
  195. // if the process it launched was still genuinely running (not crashed) --
  196. // update.sh's own package-manager step plus several downloads can plausibly
  197. // run long on a slow host with nothing actually wrong. Now a confirmed-alive
  198. // PID keeps the slot held past the stale window.
  199. func TestAcquireUpdateSlotWaitsForAliveProcessPastStaleWindow(t *testing.T) {
  200. if runtime.GOOS != "linux" {
  201. t.Skip("processAlive is a no-op stub on non-Linux; this test only exercises real liveness checking on Linux")
  202. }
  203. resetUpdateSlot(t)
  204. if !acquireUpdateSlot(1) {
  205. t.Fatal("first acquire: got false, want true")
  206. }
  207. recordUpdatePID(os.Getpid()) // the test process itself: guaranteed alive
  208. updateMu.Lock()
  209. updateStarted = time.Now().Add(-(updateStaleAfter + time.Second))
  210. updateMu.Unlock()
  211. if acquireUpdateSlot(2) {
  212. t.Fatal("acquire past the stale window while the recorded PID is still alive: got true, want false")
  213. }
  214. releaseUpdateSlot()
  215. }
  216. // TestAcquireUpdateSlotHardCeilingOverridesLiveness confirms the absolute
  217. // backstop: even a confirmed-alive process can't hold the slot forever, so a
  218. // genuinely wedged run can't lock out retries permanently.
  219. func TestAcquireUpdateSlotHardCeilingOverridesLiveness(t *testing.T) {
  220. if runtime.GOOS != "linux" {
  221. t.Skip("processAlive is a no-op stub on non-Linux; this test only exercises real liveness checking on Linux")
  222. }
  223. resetUpdateSlot(t)
  224. if !acquireUpdateSlot(1) {
  225. t.Fatal("first acquire: got false, want true")
  226. }
  227. recordUpdatePID(os.Getpid())
  228. updateMu.Lock()
  229. updateStarted = time.Now().Add(-(updateHardCeiling + time.Second))
  230. updateMu.Unlock()
  231. if !acquireUpdateSlot(2) {
  232. t.Fatal("acquire past the hard ceiling despite a live PID: got false, want true")
  233. }
  234. releaseUpdateSlot()
  235. }
  236. // TestAcquireUpdateSlotReleasesOnTerminalStatus is the regression test for the
  237. // bug adversarial review found: a fast failure used to still lock out retries
  238. // for the full updateStaleAfter window, because acquireUpdateSlot only looked
  239. // at the in-memory started-at timestamp, never at the status file's own
  240. // terminal state.
  241. func TestAcquireUpdateSlotReleasesOnTerminalStatus(t *testing.T) {
  242. t.Setenv("XUI_DB_FOLDER", t.TempDir())
  243. resetUpdateSlot(t)
  244. path := config.GetUpdateStatusFilePath()
  245. if !acquireUpdateSlot(111) {
  246. t.Fatal("first acquire: got false, want true")
  247. }
  248. writeStatusFile(t, path, 111, updateStateFailed)
  249. if !acquireUpdateSlot(222) {
  250. t.Fatal("acquire after the in-flight run reported failed: got false, want true (should not wait out updateStaleAfter)")
  251. }
  252. releaseUpdateSlot()
  253. }
  254. // TestAcquireUpdateSlotIgnoresStaleUnrelatedStatus confirms the terminal-state
  255. // check is scoped to the run it actually launched: a status file left behind
  256. // by some earlier, unrelated run (different runID) must not be mistaken for
  257. // this run finishing.
  258. func TestAcquireUpdateSlotIgnoresStaleUnrelatedStatus(t *testing.T) {
  259. t.Setenv("XUI_DB_FOLDER", t.TempDir())
  260. resetUpdateSlot(t)
  261. path := config.GetUpdateStatusFilePath()
  262. writeStatusFile(t, path, 999, updateStateSuccess)
  263. if !acquireUpdateSlot(111) {
  264. t.Fatal("first acquire: got false, want true")
  265. }
  266. if acquireUpdateSlot(222) {
  267. t.Fatal("acquire while status file only reflects an unrelated older runID: got true, want false")
  268. }
  269. releaseUpdateSlot()
  270. }
  271. // TestAcquireUpdateSlotConcurrency proves the check-then-set is actually
  272. // atomic under real concurrent access, not just correct when called
  273. // sequentially. A prior version of this test suite only ever called
  274. // acquireUpdateSlot from a single goroutine, so it gave no signal if the
  275. // mutex's core promise (only one concurrent launch wins) were broken.
  276. func TestAcquireUpdateSlotConcurrency(t *testing.T) {
  277. resetUpdateSlot(t)
  278. const attempts = 200
  279. var wins atomic.Int32
  280. var wg sync.WaitGroup
  281. wg.Add(attempts)
  282. for i := range attempts {
  283. go func(runID int64) {
  284. defer wg.Done()
  285. if acquireUpdateSlot(runID) {
  286. wins.Add(1)
  287. }
  288. }(int64(i))
  289. }
  290. wg.Wait()
  291. if got := wins.Load(); got != 1 {
  292. t.Fatalf("concurrent acquireUpdateSlot: %d of %d attempts won, want exactly 1", got, attempts)
  293. }
  294. releaseUpdateSlot()
  295. }
  296. func TestGetUpdateStatus(t *testing.T) {
  297. t.Setenv("XUI_DB_FOLDER", t.TempDir())
  298. path := config.GetUpdateStatusFilePath()
  299. svc := &PanelService{}
  300. if got := svc.GetUpdateStatus(); got.State != updateStatePending {
  301. t.Fatalf("missing status file: State = %q, want %q", got.State, updateStatePending)
  302. }
  303. writeStatusFile(t, path, 1735689600123456789, updateStateSuccess)
  304. got := svc.GetUpdateStatus()
  305. if got.RunID != "1735689600123456789" {
  306. t.Fatalf("RunID = %q, want %q (must round-trip as a decimal string, not a JSON number, or it loses precision past 2^53 in JS)", got.RunID, "1735689600123456789")
  307. }
  308. if got.State != updateStateSuccess {
  309. t.Fatalf("State = %q, want %q", got.State, updateStateSuccess)
  310. }
  311. if err := os.WriteFile(path, []byte("not json"), 0o644); err != nil {
  312. t.Fatal(err)
  313. }
  314. if got := svc.GetUpdateStatus(); got.State != updateStatePending {
  315. t.Fatalf("corrupt status file: State = %q, want %q", got.State, updateStatePending)
  316. }
  317. writeStatusFile(t, path, 1, "some-unrecognized-state")
  318. if got := svc.GetUpdateStatus(); got.State != updateStatePending {
  319. t.Fatalf("unrecognized state normalizes to pending: State = %q, want %q", got.State, updateStatePending)
  320. }
  321. }