1
0

check_client_ip_job_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. package job
  2. import (
  3. "os"
  4. "path/filepath"
  5. "reflect"
  6. "runtime"
  7. "testing"
  8. "time"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  11. )
  12. func TestMergeClientIps_EvictsStaleOldEntries(t *testing.T) {
  13. // #4077: after a ban expires, a single IP that reconnects used to get
  14. // banned again immediately because a long-disconnected IP stayed in the
  15. // DB with an ancient timestamp and kept "protecting" itself against
  16. // eviction. Guard against that regression here.
  17. old := []IPWithTimestamp{
  18. {IP: "1.1.1.1", Timestamp: 100}, // stale — client disconnected long ago
  19. {IP: "2.2.2.2", Timestamp: 1900}, // fresh — still connecting
  20. }
  21. new := []IPWithTimestamp{
  22. {IP: "2.2.2.2", Timestamp: 2000}, // same IP, newer log line
  23. }
  24. got := mergeClientIps(old, new, 1000, false)
  25. want := map[string]int64{"2.2.2.2": 2000}
  26. if !reflect.DeepEqual(got, want) {
  27. t.Fatalf("stale 1.1.1.1 should have been dropped\ngot: %v\nwant: %v", got, want)
  28. }
  29. }
  30. func TestMergeClientIps_KeepsFreshOldEntriesUnchanged(t *testing.T) {
  31. // Backwards-compat: entries that aren't stale are still carried forward,
  32. // so enforcement survives access-log rotation.
  33. old := []IPWithTimestamp{
  34. {IP: "1.1.1.1", Timestamp: 1500},
  35. }
  36. got := mergeClientIps(old, nil, 1000, false)
  37. want := map[string]int64{"1.1.1.1": 1500}
  38. if !reflect.DeepEqual(got, want) {
  39. t.Fatalf("fresh old IP should have been retained\ngot: %v\nwant: %v", got, want)
  40. }
  41. }
  42. func TestMergeClientIps_PrefersLaterTimestampForSameIp(t *testing.T) {
  43. old := []IPWithTimestamp{{IP: "1.1.1.1", Timestamp: 1500}}
  44. new := []IPWithTimestamp{{IP: "1.1.1.1", Timestamp: 1700}}
  45. got := mergeClientIps(old, new, 1000, false)
  46. if got["1.1.1.1"] != 1700 {
  47. t.Fatalf("expected latest timestamp 1700, got %d", got["1.1.1.1"])
  48. }
  49. }
  50. func TestMergeClientIps_DropsStaleNewEntries(t *testing.T) {
  51. // A log line with a clock-skewed old timestamp must not resurrect a
  52. // stale IP past the cutoff.
  53. new := []IPWithTimestamp{{IP: "1.1.1.1", Timestamp: 500}}
  54. got := mergeClientIps(nil, new, 1000, false)
  55. if len(got) != 0 {
  56. t.Fatalf("stale new IP should have been dropped, got %v", got)
  57. }
  58. }
  59. func TestMergeClientIps_NoStaleCutoffStillWorks(t *testing.T) {
  60. // Defensive: a zero cutoff (e.g. during very first run on a fresh
  61. // install) must not over-evict.
  62. old := []IPWithTimestamp{{IP: "1.1.1.1", Timestamp: 100}}
  63. new := []IPWithTimestamp{{IP: "2.2.2.2", Timestamp: 200}}
  64. got := mergeClientIps(old, new, 0, false)
  65. want := map[string]int64{"1.1.1.1": 100, "2.2.2.2": 200}
  66. if !reflect.DeepEqual(got, want) {
  67. t.Fatalf("zero cutoff should keep everything\ngot: %v\nwant: %v", got, want)
  68. }
  69. }
  70. func TestMergeClientIps_LiveObservationsBypassStaleCutoff(t *testing.T) {
  71. // online-API mode: lastSeen is set when the connection was dispatched, so
  72. // a connection held open for hours has an "old" timestamp while being live
  73. // by definition. It must survive the stale cutoff.
  74. new := []IPWithTimestamp{{IP: "1.1.1.1", Timestamp: 500}} // opened long ago, still connected
  75. got := mergeClientIps(nil, new, 1000, true)
  76. want := map[string]int64{"1.1.1.1": 500}
  77. if !reflect.DeepEqual(got, want) {
  78. t.Fatalf("live observation must bypass the stale cutoff\ngot: %v\nwant: %v", got, want)
  79. }
  80. }
  81. func TestMergeClientIps_LiveModeStillEvictsStaleOldEntries(t *testing.T) {
  82. // the bypass applies only to this scan's observations — persisted entries
  83. // from past scans still age out as before.
  84. old := []IPWithTimestamp{{IP: "2.2.2.2", Timestamp: 100}}
  85. new := []IPWithTimestamp{{IP: "1.1.1.1", Timestamp: 2000}}
  86. got := mergeClientIps(old, new, 1000, true)
  87. want := map[string]int64{"1.1.1.1": 2000}
  88. if !reflect.DeepEqual(got, want) {
  89. t.Fatalf("stale db entry must still be evicted in live mode\ngot: %v\nwant: %v", got, want)
  90. }
  91. }
  92. func TestSelectIpsToBan(t *testing.T) {
  93. live := []IPWithTimestamp{ // sorted oldest-first, as partitionLiveIps returns
  94. {IP: "A", Timestamp: 100},
  95. {IP: "B", Timestamp: 200},
  96. {IP: "C", Timestamp: 300},
  97. }
  98. // over the limit: oldest connections are banned, newest keep the slots
  99. kept, banned := selectIpsToBan(live, 1)
  100. if got := collectIps(kept); !reflect.DeepEqual(got, []string{"C"}) {
  101. t.Fatalf("newest ip must keep the slot, got %v", got)
  102. }
  103. if got := collectIps(banned); !reflect.DeepEqual(got, []string{"A", "B"}) {
  104. t.Fatalf("older ips must be banned oldest-first, got %v", got)
  105. }
  106. // at the limit: nothing banned
  107. kept, banned = selectIpsToBan(live, 3)
  108. if len(banned) != 0 || len(kept) != 3 {
  109. t.Fatalf("at-limit set must not ban, kept=%v banned=%v", kept, banned)
  110. }
  111. // under the limit: nothing banned
  112. kept, banned = selectIpsToBan(live[:1], 3)
  113. if len(banned) != 0 || len(kept) != 1 {
  114. t.Fatalf("under-limit set must not ban, kept=%v banned=%v", kept, banned)
  115. }
  116. // defensive: non-positive limit never reaches enforcement, but must not panic
  117. if _, banned := selectIpsToBan(live, 0); banned != nil {
  118. t.Fatalf("zero limit must not ban, got %v", banned)
  119. }
  120. }
  121. func collectIps(entries []IPWithTimestamp) []string {
  122. out := make([]string, 0, len(entries))
  123. for _, e := range entries {
  124. out = append(out, e.IP)
  125. }
  126. return out
  127. }
  128. func TestPartitionLiveIps_SingleLiveNotStarvedByStillFreshHistoricals(t *testing.T) {
  129. // #4091: db holds A, B, C from minutes ago (still in the 30min
  130. // window) but they're not connecting anymore. only D is. old code
  131. // merged all four, sorted ascending, kept [A,B,C] and banned D
  132. // every tick. pin the new rule: only live ips count toward the limit.
  133. ipMap := map[string]int64{
  134. "A": 1000,
  135. "B": 1100,
  136. "C": 1200,
  137. "D": 2000,
  138. }
  139. observed := map[string]bool{"D": true}
  140. live, historical := partitionLiveIps(ipMap, observed)
  141. if got := collectIps(live); !reflect.DeepEqual(got, []string{"D"}) {
  142. t.Fatalf("live set should only contain the ip observed this scan\ngot: %v\nwant: [D]", got)
  143. }
  144. if got := collectIps(historical); !reflect.DeepEqual(got, []string{"A", "B", "C"}) {
  145. t.Fatalf("historical set should contain db-only ips in ascending order\ngot: %v\nwant: [A B C]", got)
  146. }
  147. }
  148. func TestPartitionLiveIps_ConcurrentLiveIpsSortedAscending(t *testing.T) {
  149. // when several ips are really live, partition returns them all in the
  150. // live set sorted ascending by timestamp. updateInboundClientIps then
  151. // keeps the newest and bans the oldest (last-IP-wins, #4699).
  152. ipMap := map[string]int64{
  153. "A": 5000,
  154. "B": 5500,
  155. }
  156. observed := map[string]bool{"A": true, "B": true}
  157. live, historical := partitionLiveIps(ipMap, observed)
  158. if got := collectIps(live); !reflect.DeepEqual(got, []string{"A", "B"}) {
  159. t.Fatalf("both live ips should be in the live set, ascending\ngot: %v\nwant: [A B]", got)
  160. }
  161. if len(historical) != 0 {
  162. t.Fatalf("no historical ips expected, got %v", historical)
  163. }
  164. }
  165. func TestGetInboundByEmailFallbackIgnoresProtocolScalarFields(t *testing.T) {
  166. dbDir := t.TempDir()
  167. t.Setenv("XUI_DB_FOLDER", dbDir)
  168. if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
  169. t.Fatalf("InitDB: %v", err)
  170. }
  171. t.Cleanup(func() { _ = database.CloseDB() })
  172. inbound := &model.Inbound{
  173. UserId: 1,
  174. Tag: "vless-limit-fallback",
  175. Enable: true,
  176. Port: 43002,
  177. Protocol: model.VLESS,
  178. Settings: `{
  179. "clients": [{"email": "[email protected]", "id": "11111111-1111-1111-1111-111111111111", "limitIp": 2}],
  180. "decryption": "none",
  181. "encryption": "none",
  182. "fallbacks": []
  183. }`,
  184. }
  185. if err := database.GetDB().Create(inbound).Error; err != nil {
  186. t.Fatalf("create inbound: %v", err)
  187. }
  188. got, err := (&CheckClientIpJob{}).getInboundByEmail("[email protected]")
  189. if err != nil {
  190. t.Fatalf("getInboundByEmail: %v", err)
  191. }
  192. if got.Id != inbound.Id {
  193. t.Fatalf("inbound id = %d, want %d", got.Id, inbound.Id)
  194. }
  195. }
  196. func TestPartitionLiveIps_EmptyScanLeavesDbIntact(t *testing.T) {
  197. // quiet tick: nothing observed => nothing live. everything merged
  198. // is historical. keeps the panel from wiping recent-but-idle ips.
  199. ipMap := map[string]int64{
  200. "A": 1000,
  201. "B": 1100,
  202. }
  203. observed := map[string]bool{}
  204. live, historical := partitionLiveIps(ipMap, observed)
  205. if len(live) != 0 {
  206. t.Fatalf("no live ips expected, got %v", live)
  207. }
  208. if got := collectIps(historical); !reflect.DeepEqual(got, []string{"A", "B"}) {
  209. t.Fatalf("all merged entries should flow to historical\ngot: %v\nwant: [A B]", got)
  210. }
  211. }
  212. func TestPartitionLiveIps_RecentSyncedIpIsLive(t *testing.T) {
  213. // Synced IPs from other nodes within 2 minutes should be counted as live
  214. // even if they weren't observed in the local scan.
  215. now := time.Now().Unix()
  216. ipMap := map[string]int64{
  217. "A": now - 30, // synced 30s ago -> live
  218. "B": now - 150, // synced 2m30s ago -> historical
  219. }
  220. observed := map[string]bool{}
  221. live, historical := partitionLiveIps(ipMap, observed)
  222. if got := collectIps(live); !reflect.DeepEqual(got, []string{"A"}) {
  223. t.Fatalf("recent IP should be live\ngot: %v\nwant: [A]", got)
  224. }
  225. if got := collectIps(historical); !reflect.DeepEqual(got, []string{"B"}) {
  226. t.Fatalf("older IP should be historical\ngot: %v\nwant: [B]", got)
  227. }
  228. }
  229. func TestCheckFail2BanInstalled_DisabledEnvSkipsClientProbe(t *testing.T) {
  230. t.Setenv("XUI_ENABLE_FAIL2BAN", "false")
  231. marker := fakeFail2BanClient(t)
  232. if (&CheckClientIpJob{}).checkFail2BanInstalled() {
  233. t.Fatal("fail2ban should be unavailable when XUI_ENABLE_FAIL2BAN=false")
  234. }
  235. if _, err := os.Stat(marker); !os.IsNotExist(err) {
  236. t.Fatalf("fail2ban-client should not have been executed, stat error: %v", err)
  237. }
  238. }
  239. func TestCheckFail2BanInstalled_EmptyEnvSkipsClientProbe(t *testing.T) {
  240. t.Setenv("XUI_ENABLE_FAIL2BAN", "")
  241. marker := fakeFail2BanClient(t)
  242. if (&CheckClientIpJob{}).checkFail2BanInstalled() {
  243. t.Fatal("fail2ban should be unavailable when XUI_ENABLE_FAIL2BAN is empty")
  244. }
  245. if _, err := os.Stat(marker); !os.IsNotExist(err) {
  246. t.Fatalf("fail2ban-client should not have been executed, stat error: %v", err)
  247. }
  248. }
  249. func TestIsFail2BanEnabled_DefaultsToEnabledWhenUnset(t *testing.T) {
  250. value, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN")
  251. os.Unsetenv("XUI_ENABLE_FAIL2BAN")
  252. t.Cleanup(func() {
  253. if ok {
  254. os.Setenv("XUI_ENABLE_FAIL2BAN", value)
  255. } else {
  256. os.Unsetenv("XUI_ENABLE_FAIL2BAN")
  257. }
  258. })
  259. if !isFail2BanEnabled() {
  260. t.Fatal("fail2ban should default to enabled when XUI_ENABLE_FAIL2BAN is unset")
  261. }
  262. }
  263. func TestCheckFail2BanInstalled_EnabledEnvProbesClient(t *testing.T) {
  264. t.Setenv("XUI_ENABLE_FAIL2BAN", "true")
  265. marker := fakeFail2BanClient(t)
  266. if !(&CheckClientIpJob{}).checkFail2BanInstalled() {
  267. t.Fatal("fail2ban should be available when the client probe succeeds")
  268. }
  269. if _, err := os.Stat(marker); err != nil {
  270. t.Fatalf("fail2ban-client should have been executed: %v", err)
  271. }
  272. }
  273. func fakeFail2BanClient(t *testing.T) string {
  274. t.Helper()
  275. dir := t.TempDir()
  276. marker := filepath.Join(dir, "probe-called")
  277. fakeClient := filepath.Join(dir, "fail2ban-client")
  278. script := "#!/bin/sh\n: > \"$FAIL2BAN_PROBE_MARKER\"\nexit 0\n"
  279. if runtime.GOOS == "windows" {
  280. fakeClient += ".bat"
  281. script = "@echo off\ntype nul > \"%FAIL2BAN_PROBE_MARKER%\"\nexit /b 0\n"
  282. }
  283. if err := os.WriteFile(fakeClient, []byte(script), 0o755); err != nil {
  284. t.Fatalf("write fake fail2ban-client: %v", err)
  285. }
  286. t.Setenv("FAIL2BAN_PROBE_MARKER", marker)
  287. t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
  288. return marker
  289. }