1
0

panel_test.go 11 KB

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