check_client_ip_job_integration_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. package job
  2. import (
  3. "encoding/json"
  4. "log"
  5. "os"
  6. "path/filepath"
  7. "sync"
  8. "testing"
  9. "time"
  10. "github.com/op/go-logging"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
  15. )
  16. // 3x-ui logger must be initialised once before any code path that can
  17. // log a warning. otherwise log.Warningf panics on a nil logger.
  18. var loggerInitOnce sync.Once
  19. // setupIntegrationDB wires a temp sqlite db and log folder so
  20. // updateInboundClientIps can run end to end. closes the db before
  21. // TempDir cleanup so windows doesn't complain about the file being in
  22. // use.
  23. func setupIntegrationDB(t *testing.T) {
  24. t.Helper()
  25. loggerInitOnce.Do(func() {
  26. xuilogger.InitLogger(logging.ERROR)
  27. })
  28. dbDir := t.TempDir()
  29. logDir := t.TempDir()
  30. t.Setenv("XUI_DB_FOLDER", dbDir)
  31. t.Setenv("XUI_LOG_FOLDER", logDir)
  32. // updateInboundClientIps calls log.SetOutput on the package global,
  33. // which would leak to other tests in the same binary.
  34. origLogWriter := log.Writer()
  35. origLogFlags := log.Flags()
  36. t.Cleanup(func() {
  37. log.SetOutput(origLogWriter)
  38. log.SetFlags(origLogFlags)
  39. })
  40. dbtest.InitDB(t, filepath.Join(dbDir, "x-ui.db"))
  41. }
  42. // enforceIpLimitForTest runs the same two steps processObserved does: select
  43. // inside the transaction, publish only once it would have committed.
  44. func (j *CheckClientIpJob) enforceIpLimitForTest(t *testing.T, row *model.InboundClientIps, inbound *model.Inbound, email string, limit int, live []IPWithTimestamp, observedAreLive bool) (banned bool, published []IPWithTimestamp) {
  45. t.Helper()
  46. candidates, keptLive := j.updateInboundClientIps(database.GetDB(), row, inbound, email, limit, live, true, observedAreLive)
  47. actionable := j.selectAdvancedSinceLastBan(email, candidates)
  48. done := j.publishBans([]pendingBan{{inbound: inbound, email: email, candidates: candidates, keptLive: keptLive}})
  49. if len(done) == 0 {
  50. return false, nil
  51. }
  52. return true, actionable
  53. }
  54. // seed an inbound whose settings json has a single client with the
  55. // given email and ip limit.
  56. func seedInboundWithClient(t *testing.T, tag, email string, limitIp int) {
  57. t.Helper()
  58. seedInboundOnlyWithClient(t, tag, email, limitIp)
  59. }
  60. func seedInboundOnlyWithClient(t *testing.T, tag, email string, limitIp int) *model.Inbound {
  61. t.Helper()
  62. settings := map[string]any{
  63. "clients": []map[string]any{
  64. {
  65. "email": email,
  66. "limitIp": limitIp,
  67. "enable": true,
  68. },
  69. },
  70. }
  71. settingsJSON, err := json.Marshal(settings)
  72. if err != nil {
  73. t.Fatalf("marshal settings: %v", err)
  74. }
  75. inbound := &model.Inbound{
  76. Tag: tag,
  77. Enable: true,
  78. Protocol: model.VLESS,
  79. Port: 4321,
  80. Settings: string(settingsJSON),
  81. }
  82. if err := database.GetDB().Create(inbound).Error; err != nil {
  83. t.Fatalf("seed inbound: %v", err)
  84. }
  85. return inbound
  86. }
  87. func seedLinkedInboundWithClient(t *testing.T, tag, email string, limitIp int) *model.Inbound {
  88. t.Helper()
  89. inbound := seedInboundOnlyWithClient(t, tag, email, limitIp)
  90. client := &model.ClientRecord{Email: email, LimitIP: limitIp}
  91. if err := database.GetDB().Create(client).Error; err != nil {
  92. t.Fatalf("seed client record: %v", err)
  93. }
  94. link := &model.ClientInbound{ClientId: client.Id, InboundId: inbound.Id}
  95. if err := database.GetDB().Create(link).Error; err != nil {
  96. t.Fatalf("seed client inbound link: %v", err)
  97. }
  98. return inbound
  99. }
  100. // seed an InboundClientIps row with the given blob.
  101. func seedClientIps(t *testing.T, email string, ips []IPWithTimestamp) *model.InboundClientIps {
  102. t.Helper()
  103. blob, err := json.Marshal(ips)
  104. if err != nil {
  105. t.Fatalf("marshal ips: %v", err)
  106. }
  107. row := &model.InboundClientIps{
  108. ClientEmail: email,
  109. Ips: string(blob),
  110. }
  111. if err := database.GetDB().Create(row).Error; err != nil {
  112. t.Fatalf("seed InboundClientIps: %v", err)
  113. }
  114. return row
  115. }
  116. // read the persisted blob and parse it back.
  117. func readClientIps(t *testing.T, email string) []IPWithTimestamp {
  118. t.Helper()
  119. row := &model.InboundClientIps{}
  120. if err := database.GetDB().Where("client_email = ?", email).First(row).Error; err != nil {
  121. t.Fatalf("read InboundClientIps for %s: %v", email, err)
  122. }
  123. if row.Ips == "" {
  124. return nil
  125. }
  126. var out []IPWithTimestamp
  127. if err := json.Unmarshal([]byte(row.Ips), &out); err != nil {
  128. t.Fatalf("unmarshal Ips blob %q: %v", row.Ips, err)
  129. }
  130. return out
  131. }
  132. // make a lookup map so asserts don't depend on slice order.
  133. func ipSet(entries []IPWithTimestamp) map[string]int64 {
  134. out := make(map[string]int64, len(entries))
  135. for _, e := range entries {
  136. out[e.IP] = e.Timestamp
  137. }
  138. return out
  139. }
  140. // With the access-log fallback removed, an unavailable online-stats API (xray
  141. // down, as in this unit test) must make Run a clean no-op: no fail2ban probe, no
  142. // ban log, and no inbound_client_ips rows — never a crash or partial work.
  143. func TestRun_NoOpWhenOnlineApiUnavailable(t *testing.T) {
  144. setupIntegrationDB(t)
  145. t.Setenv("XUI_ENABLE_FAIL2BAN", "true")
  146. marker := fakeFail2BanClient(t)
  147. const email = "no-api-user"
  148. seedInboundWithClient(t, "inbound-no-api", email, 1)
  149. NewCheckClientIpJob().Run()
  150. if _, err := os.Stat(marker); !os.IsNotExist(err) {
  151. t.Fatalf("fail2ban-client should not have been probed when the online API is unavailable, stat error: %v", err)
  152. }
  153. if info, err := os.Stat(readIpLimitLogPath()); err == nil && info.Size() > 0 {
  154. body, _ := os.ReadFile(readIpLimitLogPath())
  155. t.Fatalf("3xipl.log should be empty when Run no-ops, got:\n%s", body)
  156. }
  157. var count int64
  158. if err := database.GetDB().Model(&model.InboundClientIps{}).Where("client_email = ?", email).Count(&count).Error; err != nil {
  159. t.Fatalf("count InboundClientIps: %v", err)
  160. }
  161. if count != 0 {
  162. t.Fatalf("no IP-limit rows should be persisted when Run no-ops, got %d", count)
  163. }
  164. }
  165. // #4091 repro: client has limit=3, db still holds 3 idle ips from a
  166. // few minutes ago, only one live ip is actually connecting. pre-fix:
  167. // live ip got banned every tick and never appeared in the panel.
  168. // post-fix: no ban, live ip persisted, historical ips still visible.
  169. func TestUpdateInboundClientIps_LiveIpNotBannedByStillFreshHistoricals(t *testing.T) {
  170. setupIntegrationDB(t)
  171. const email = "pr4091-repro"
  172. seedInboundWithClient(t, "inbound-pr4091", email, 3)
  173. now := time.Now().Unix()
  174. // idle but still within the 30min staleness window.
  175. row := seedClientIps(t, email, []IPWithTimestamp{
  176. {IP: "10.0.0.1", Timestamp: now - 20*60},
  177. {IP: "10.0.0.2", Timestamp: now - 15*60},
  178. {IP: "10.0.0.3", Timestamp: now - 10*60},
  179. })
  180. j := NewCheckClientIpJob()
  181. // the one that's actually connecting (user's 128.71.x.x).
  182. live := []IPWithTimestamp{
  183. {IP: "128.71.1.1", Timestamp: now},
  184. }
  185. inbound, err := j.getInboundByEmail(email)
  186. if err != nil {
  187. t.Fatalf("getInboundByEmail: %v", err)
  188. }
  189. banned, published := j.enforceIpLimitForTest(t, row, inbound, email, 3, live, false)
  190. if banned {
  191. t.Fatalf("banned must be false with 1 live ip under limit 3")
  192. }
  193. if len(published) != 0 {
  194. t.Fatalf("published bans must be empty, got %v", published)
  195. }
  196. persisted := ipSet(readClientIps(t, email))
  197. for _, want := range []string{"128.71.1.1", "10.0.0.1", "10.0.0.2", "10.0.0.3"} {
  198. if _, ok := persisted[want]; !ok {
  199. t.Errorf("expected %s to be persisted in inbound_client_ips.ips; got %v", want, persisted)
  200. }
  201. }
  202. if got := persisted["128.71.1.1"]; got != now {
  203. t.Errorf("live ip timestamp should match the scan timestamp %d, got %d", now, got)
  204. }
  205. // 3xipl.log must not contain a ban line.
  206. if info, err := os.Stat(readIpLimitLogPath()); err == nil && info.Size() > 0 {
  207. body, _ := os.ReadFile(readIpLimitLogPath())
  208. t.Fatalf("3xipl.log should be empty when no ips are banned, got:\n%s", body)
  209. }
  210. }
  211. // opposite invariant: when several ips are actually live and exceed
  212. // the limit, the oldest connection is dropped and the most recent one
  213. // keeps the slot (last-IP-wins policy from #3735, restored in #4699).
  214. func TestUpdateInboundClientIps_ExcessLiveIpIsStillBanned(t *testing.T) {
  215. setupIntegrationDB(t)
  216. const email = "pr4091-abuse"
  217. seedInboundWithClient(t, "inbound-pr4091-abuse", email, 1)
  218. now := time.Now().Unix()
  219. row := seedClientIps(t, email, []IPWithTimestamp{
  220. {IP: "10.1.0.1", Timestamp: now - 60}, // original connection
  221. })
  222. j := NewCheckClientIpJob()
  223. // both live, limit=1. use distinct timestamps so sort-by-timestamp
  224. // is deterministic: 10.1.0.1 is the original (older) and must get
  225. // banned; 192.0.2.9 joined later and keeps the slot (last IP wins).
  226. live := []IPWithTimestamp{
  227. {IP: "10.1.0.1", Timestamp: now - 5},
  228. {IP: "192.0.2.9", Timestamp: now},
  229. }
  230. inbound, err := j.getInboundByEmail(email)
  231. if err != nil {
  232. t.Fatalf("getInboundByEmail: %v", err)
  233. }
  234. banned, published := j.enforceIpLimitForTest(t, row, inbound, email, 1, live, false)
  235. if !banned {
  236. t.Fatalf("banned must be true when the live set exceeds the limit")
  237. }
  238. if len(published) != 1 || published[0].IP != "10.1.0.1" {
  239. t.Fatalf("expected 10.1.0.1 to be banned; published = %v", published)
  240. }
  241. persisted := ipSet(readClientIps(t, email))
  242. if _, ok := persisted["192.0.2.9"]; !ok {
  243. t.Errorf("newest IP 192.0.2.9 must still be persisted; got %v", persisted)
  244. }
  245. if _, ok := persisted["10.1.0.1"]; ok {
  246. t.Errorf("banned IP 10.1.0.1 must NOT be persisted; got %v", persisted)
  247. }
  248. // 3xipl.log must contain the ban line in the exact fail2ban format.
  249. body, err := os.ReadFile(readIpLimitLogPath())
  250. if err != nil {
  251. t.Fatalf("read 3xipl.log: %v", err)
  252. }
  253. wantSubstr := "[LIMIT_IP] Email = pr4091-abuse || Disconnecting OLD IP = 10.1.0.1"
  254. if !contains(string(body), wantSubstr) {
  255. t.Fatalf("3xipl.log missing expected ban line %q\nfull log:\n%s", wantSubstr, body)
  256. }
  257. }
  258. // #4800: per-client IP tracking must populate even when no client has an IP
  259. // limit. processObserved records observed IPs for the panel regardless of any
  260. // limit; only enforcement is gated, so a limit-free install still shows IPs. No
  261. // ban may be written since there's no limit.
  262. func TestProcessObserved_CollectsIpsWithoutLimit(t *testing.T) {
  263. setupIntegrationDB(t)
  264. const email = "no-limit-user"
  265. seedInboundWithClient(t, "inbound-no-limit", email, 0) // limitIp = 0
  266. observed := map[string]map[string]int64{
  267. email: {"203.0.113.10": time.Now().Unix()},
  268. }
  269. NewCheckClientIpJob().processObserved(observed, true, true)
  270. ips := readClientIps(t, email)
  271. if len(ips) != 1 || ips[0].IP != "203.0.113.10" {
  272. t.Fatalf("expected the observed IP to be collected without a limit, got %v", ips)
  273. }
  274. if info, err := os.Stat(readIpLimitLogPath()); err == nil && info.Size() > 0 {
  275. body, _ := os.ReadFile(readIpLimitLogPath())
  276. t.Fatalf("3xipl.log should be empty with no limit set, got:\n%s", body)
  277. }
  278. }
  279. // #4963: an observed IP for a renamed/deleted client (its email no longer maps
  280. // to any inbound) must not create or resurrect an inbound_client_ips row, and
  281. // must drop any orphan left behind — instead of erroring every run.
  282. func TestProcessObserved_StaleEmailIsSkippedAndOrphanDropped(t *testing.T) {
  283. setupIntegrationDB(t)
  284. const staleEmail = "renamed-away"
  285. // No inbound references staleEmail. Pre-seed an orphan tracking row to
  286. // confirm the job removes it rather than leaving it to error forever.
  287. seedClientIps(t, staleEmail, []IPWithTimestamp{{IP: "203.0.113.5", Timestamp: time.Now().Unix()}})
  288. observed := map[string]map[string]int64{
  289. staleEmail: {"203.0.113.5": time.Now().Unix()},
  290. }
  291. NewCheckClientIpJob().processObserved(observed, true, true)
  292. var count int64
  293. if err := database.GetDB().Model(&model.InboundClientIps{}).Where("client_email = ?", staleEmail).Count(&count).Error; err != nil {
  294. t.Fatalf("count InboundClientIps: %v", err)
  295. }
  296. if count != 0 {
  297. t.Fatalf("stale-email orphan row should be deleted, got %d row(s)", count)
  298. }
  299. }
  300. // readIpLimitLogPath reads the 3xipl.log path the same way the job
  301. // does via xray.GetIPLimitLogPath but without importing xray here
  302. // just for the path helper (which would pull a lot more deps into the
  303. // test binary). The env-derived log folder is deterministic.
  304. func readIpLimitLogPath() string {
  305. folder := os.Getenv("XUI_LOG_FOLDER")
  306. if folder == "" {
  307. folder = filepath.Join(".", "log")
  308. }
  309. return filepath.Join(folder, "3xipl.log")
  310. }
  311. func contains(haystack, needle string) bool {
  312. for i := 0; i+len(needle) <= len(haystack); i++ {
  313. if haystack[i:i+len(needle)] == needle {
  314. return true
  315. }
  316. }
  317. return false
  318. }
  319. // the exact clients/client_inbounds relation must win over the substring scan,
  320. // so a client is resolved to its own inbound even when another inbound holds a
  321. // superstring email.
  322. func TestGetInboundByEmailUsesClientInboundLink(t *testing.T) {
  323. setupIntegrationDB(t)
  324. want := seedLinkedInboundWithClient(t, "linked-inbound", "[email protected]", 1)
  325. seedInboundOnlyWithClient(t, "other-inbound", "[email protected]", 1)
  326. got, err := (&CheckClientIpJob{}).getInboundByEmail("[email protected]")
  327. if err != nil {
  328. t.Fatalf("getInboundByEmail returned error: %v", err)
  329. }
  330. if got.Id != want.Id {
  331. t.Fatalf("getInboundByEmail returned inbound %d, want %d", got.Id, want.Id)
  332. }
  333. }
  334. // the substring fallback must still verify the exact email inside settings, so
  335. // "[email protected]" does not match an inbound holding "[email protected]".
  336. func TestGetInboundByEmailRejectsSubstringFallbackMatch(t *testing.T) {
  337. setupIntegrationDB(t)
  338. seedInboundOnlyWithClient(t, "substring-only", "[email protected]", 1)
  339. if got, err := (&CheckClientIpJob{}).getInboundByEmail("[email protected]"); err == nil {
  340. t.Fatalf("substring email matched inbound %d; want no exact match", got.Id)
  341. }
  342. }
  343. // hasLimitIp gates every 10s scan on the normalized clients table: a bare
  344. // "limitIp":0 in settings JSON (which the old LIKE scan matched and parsed)
  345. // must not enable enforcement, while a single clients.limit_ip > 0 row must.
  346. func TestHasLimitIp_ProbesClientRecords(t *testing.T) {
  347. setupIntegrationDB(t)
  348. j := &CheckClientIpJob{}
  349. if j.hasLimitIp() {
  350. t.Fatal("hasLimitIp = true on an empty database")
  351. }
  352. seedLinkedInboundWithClient(t, "no-limit", "[email protected]", 0)
  353. if j.hasLimitIp() {
  354. t.Fatal("hasLimitIp = true with only limit_ip=0 clients")
  355. }
  356. limited := &model.ClientRecord{Email: "[email protected]", LimitIP: 2}
  357. if err := database.GetDB().Create(limited).Error; err != nil {
  358. t.Fatalf("seed limited client: %v", err)
  359. }
  360. if !j.hasLimitIp() {
  361. t.Fatal("hasLimitIp = false with a limit_ip=2 client present")
  362. }
  363. }
  364. // The mirror of TestUpdateInboundClientIps_ExcessLiveIpIsStillBanned: with the
  365. // older address on the operator's allowlist nothing may be banned, it must not
  366. // consume the limit, and no fail2ban line may be written for it (#5378).
  367. func TestUpdateInboundClientIps_AllowlistedIpIsNeitherCountedNorBanned(t *testing.T) {
  368. setupIntegrationDB(t)
  369. const email = "issue5378-office"
  370. seedInboundWithClient(t, "inbound-issue5378", email, 1)
  371. now := time.Now().Unix()
  372. row := seedClientIps(t, email, []IPWithTimestamp{
  373. {IP: "203.0.113.10", Timestamp: now - 60},
  374. })
  375. j := NewCheckClientIpJob()
  376. j.allowlist = parseIpLimitAllowlist("203.0.113.0/24")
  377. live := []IPWithTimestamp{
  378. {IP: "203.0.113.10", Timestamp: now - 5},
  379. {IP: "192.0.2.9", Timestamp: now},
  380. }
  381. inbound, err := j.getInboundByEmail(email)
  382. if err != nil {
  383. t.Fatalf("getInboundByEmail: %v", err)
  384. }
  385. banned, published := j.enforceIpLimitForTest(t, row, inbound, email, 1, live, false)
  386. if banned {
  387. t.Fatal("an allowlisted address pushed the client over its limit and something was banned")
  388. }
  389. if len(published) != 0 {
  390. t.Fatalf("published = %v, want none", published)
  391. }
  392. persisted := ipSet(readClientIps(t, email))
  393. for _, ip := range []string{"203.0.113.10", "192.0.2.9"} {
  394. if _, ok := persisted[ip]; !ok {
  395. t.Errorf("%s must still be persisted; got %v", ip, persisted)
  396. }
  397. }
  398. if body, err := os.ReadFile(readIpLimitLogPath()); err == nil {
  399. if contains(string(body), "203.0.113.10") {
  400. t.Fatalf("an allowlisted address reached the fail2ban log:\n%s", body)
  401. }
  402. }
  403. }