1
0

gateway_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. package discord
  2. import (
  3. "context"
  4. "encoding/json"
  5. "io"
  6. "net"
  7. "net/http"
  8. "net/http/httptest"
  9. "strings"
  10. "sync"
  11. "testing"
  12. "time"
  13. "github.com/gorilla/websocket"
  14. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  15. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  16. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  17. )
  18. type mockXrayRestart struct {
  19. restarted bool
  20. err error
  21. }
  22. func (m *mockXrayRestart) RestartXray(force bool) error {
  23. m.restarted = true
  24. return m.err
  25. }
  26. func TestGatewayClient_EndToEndCommands(t *testing.T) {
  27. settingService := setupTestDB(t)
  28. _ = settingService.SetDiscordBotEnable(true)
  29. _ = settingService.SetDiscordBotToken("test-gw-token")
  30. _ = settingService.SetDiscordChannelId("ch-12345")
  31. _ = settingService.SetDiscordAdminIds("u1")
  32. var sentMessages []MessagePayload
  33. var mu sync.Mutex
  34. restServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  35. var p MessagePayload
  36. _ = json.NewDecoder(r.Body).Decode(&p)
  37. mu.Lock()
  38. sentMessages = append(sentMessages, p)
  39. mu.Unlock()
  40. w.WriteHeader(http.StatusOK)
  41. _, _ = w.Write([]byte(`{"id": "msg-sent"}`))
  42. }))
  43. defer restServer.Close()
  44. discordSvc := NewDiscordService(settingService)
  45. discordSvc.SetBaseURL(restServer.URL)
  46. discordSvc.SetHTTPClient(restServer.Client())
  47. upgrader := websocket.Upgrader{}
  48. wsConnected := make(chan struct{})
  49. wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  50. conn, err := upgrader.Upgrade(w, r, nil)
  51. if err != nil {
  52. return
  53. }
  54. defer conn.Close()
  55. // 1. Send Op 10 Hello
  56. hello := GatewayPayload{
  57. Op: opHello,
  58. D: []byte(`{"heartbeat_interval": 500}`),
  59. }
  60. _ = conn.WriteJSON(hello)
  61. // 2. Read Op 2 Identify
  62. var ident GatewayPayload
  63. _ = conn.ReadJSON(&ident)
  64. close(wsConnected)
  65. // 3. Send !help message
  66. helpMsg := MessageCreateData{
  67. ID: "m1",
  68. ChannelID: "ch-12345",
  69. Content: "!help",
  70. Author: struct {
  71. ID string `json:"id"`
  72. Username string `json:"username"`
  73. Bot bool `json:"bot"`
  74. }{ID: "u1", Username: "Alice", Bot: false},
  75. }
  76. helpBytes, _ := json.Marshal(helpMsg)
  77. _ = conn.WriteJSON(GatewayPayload{
  78. Op: opDispatch,
  79. T: "MESSAGE_CREATE",
  80. D: helpBytes,
  81. })
  82. time.Sleep(50 * time.Millisecond)
  83. // 4. Send !status message
  84. statusMsg := MessageCreateData{
  85. ID: "m2",
  86. ChannelID: "ch-12345",
  87. Content: "!status",
  88. Author: struct {
  89. ID string `json:"id"`
  90. Username string `json:"username"`
  91. Bot bool `json:"bot"`
  92. }{ID: "u1", Username: "Alice", Bot: false},
  93. }
  94. statusBytes, _ := json.Marshal(statusMsg)
  95. _ = conn.WriteJSON(GatewayPayload{
  96. Op: opDispatch,
  97. T: "MESSAGE_CREATE",
  98. D: statusBytes,
  99. })
  100. time.Sleep(50 * time.Millisecond)
  101. // 5. Send message from a bot (must be ignored)
  102. botMsg := MessageCreateData{
  103. ID: "m3",
  104. ChannelID: "ch-12345",
  105. Content: "!status",
  106. Author: struct {
  107. ID string `json:"id"`
  108. Username string `json:"username"`
  109. Bot bool `json:"bot"`
  110. }{ID: "u2", Username: "OtherBot", Bot: true},
  111. }
  112. botBytes, _ := json.Marshal(botMsg)
  113. _ = conn.WriteJSON(GatewayPayload{
  114. Op: opDispatch,
  115. T: "MESSAGE_CREATE",
  116. D: botBytes,
  117. })
  118. time.Sleep(50 * time.Millisecond)
  119. // 6. Send !usage for existing client
  120. usageMsg := MessageCreateData{
  121. ID: "m4",
  122. ChannelID: "ch-12345",
  123. Content: "!usage [email protected]",
  124. Author: struct {
  125. ID string `json:"id"`
  126. Username string `json:"username"`
  127. Bot bool `json:"bot"`
  128. }{ID: "u1", Username: "Alice", Bot: false},
  129. }
  130. usageBytes, _ := json.Marshal(usageMsg)
  131. _ = conn.WriteJSON(GatewayPayload{
  132. Op: opDispatch,
  133. T: "MESSAGE_CREATE",
  134. D: usageBytes,
  135. })
  136. time.Sleep(50 * time.Millisecond)
  137. // 7. Send !restart command
  138. restartMsg := MessageCreateData{
  139. ID: "m5",
  140. ChannelID: "ch-12345",
  141. Content: "!restart",
  142. Author: struct {
  143. ID string `json:"id"`
  144. Username string `json:"username"`
  145. Bot bool `json:"bot"`
  146. }{ID: "u1", Username: "Alice", Bot: false},
  147. }
  148. restartBytes, _ := json.Marshal(restartMsg)
  149. _ = conn.WriteJSON(GatewayPayload{
  150. Op: opDispatch,
  151. T: "MESSAGE_CREATE",
  152. D: restartBytes,
  153. })
  154. // Keep connection alive until closed
  155. for {
  156. var p GatewayPayload
  157. if err := conn.ReadJSON(&p); err != nil {
  158. break
  159. }
  160. }
  161. }))
  162. defer wsServer.Close()
  163. mockServer := &mockServerProvider{
  164. status: &service.Status{
  165. Uptime: 10000,
  166. Loads: []float64{0.1, 0.2, 0.3},
  167. TcpCount: 5,
  168. UdpCount: 2,
  169. },
  170. }
  171. mockInbound := &mockInboundProvider{
  172. inbounds: []*model.Inbound{
  173. {
  174. Id: 1,
  175. Remark: "VLESS-Test",
  176. Port: 8443,
  177. Protocol: "vless",
  178. Enable: true,
  179. ClientStats: []xray.ClientTraffic{
  180. {
  181. Email: "[email protected]",
  182. Enable: true,
  183. Up: 1024,
  184. Down: 2048,
  185. Total: 10485760,
  186. },
  187. },
  188. },
  189. },
  190. }
  191. mockXray := &mockXrayRestart{}
  192. wsURL := "ws" + strings.TrimPrefix(wsServer.URL, "http")
  193. gw := NewGatewayClient(discordSvc, settingService, mockServer, mockInbound, mockXray)
  194. gw.SetGatewayURL(wsURL)
  195. ctx, cancel := context.WithCancel(context.Background())
  196. defer cancel()
  197. if err := gw.Start(ctx); err != nil {
  198. t.Fatalf("gw.Start failed: %v", err)
  199. }
  200. select {
  201. case <-wsConnected:
  202. case <-time.After(3 * time.Second):
  203. t.Fatal("timed out waiting for WS connection")
  204. }
  205. // Wait for dispatches to be processed
  206. time.Sleep(300 * time.Millisecond)
  207. gw.Stop()
  208. if gw.IsRunning() {
  209. t.Error("expected gateway not to be running after Stop")
  210. }
  211. mu.Lock()
  212. msgs := make([]MessagePayload, len(sentMessages))
  213. copy(msgs, sentMessages)
  214. mu.Unlock()
  215. // We expect:
  216. // 1. !help response embed
  217. // 2. !status response embed
  218. // (bot message ignored)
  219. // 3. !usage response embed
  220. // 4. !restart "Restarting..." and "Restarted successfully"
  221. if len(msgs) < 4 {
  222. t.Fatalf("expected at least 4 message responses, got %d: %+v", len(msgs), msgs)
  223. }
  224. foundHelp := false
  225. foundStatus := false
  226. foundUsage := false
  227. for _, m := range msgs {
  228. for _, e := range m.Embeds {
  229. if strings.Contains(e.Title, "Discord Bot Commands") {
  230. foundHelp = true
  231. }
  232. if strings.Contains(e.Title, "Server Status") {
  233. foundStatus = true
  234. }
  235. if strings.Contains(e.Title, "Client Usage: [email protected]") {
  236. foundUsage = true
  237. }
  238. }
  239. }
  240. if !foundHelp {
  241. t.Error("expected help embed to be sent")
  242. }
  243. if !foundStatus {
  244. t.Error("expected status embed to be sent")
  245. }
  246. if !foundUsage {
  247. t.Error("expected usage embed to be sent")
  248. }
  249. if !mockXray.restarted {
  250. t.Error("expected Xray core to be restarted")
  251. }
  252. }
  253. func TestGatewayRequestedHeartbeatDoesNotRaceTicker(t *testing.T) {
  254. settingService := setupTestDB(t)
  255. _ = settingService.SetDiscordBotEnable(true)
  256. _ = settingService.SetDiscordBotToken("test-gw-token")
  257. var once sync.Once
  258. flooded := make(chan struct{})
  259. upgrader := websocket.Upgrader{}
  260. wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  261. conn, err := upgrader.Upgrade(w, r, nil)
  262. if err != nil {
  263. return
  264. }
  265. defer conn.Close()
  266. // 10ms, not 1ms: Discord answers every heartbeat and the client now drops a
  267. // socket it hears nothing back on, so the ACK needs room to arrive.
  268. _ = conn.WriteJSON(GatewayPayload{Op: opHello, D: []byte(`{"heartbeat_interval": 10}`)})
  269. // Two server goroutines write, so they share one writer: gorilla panics on
  270. // concurrent writes, and this test is about the CLIENT's two writers.
  271. var writeMu sync.Mutex
  272. writeJSON := func(v any) error {
  273. writeMu.Lock()
  274. defer writeMu.Unlock()
  275. return conn.WriteJSON(v)
  276. }
  277. readErr := make(chan error, 1)
  278. go func() {
  279. for {
  280. var payload GatewayPayload
  281. if err := conn.ReadJSON(&payload); err != nil {
  282. readErr <- err
  283. return
  284. }
  285. // Discord answers every heartbeat; without this the zombie check
  286. // closes the socket a millisecond into the flood below.
  287. if payload.Op == opHeartbeat {
  288. if err := writeJSON(GatewayPayload{Op: opHeartbeatACK}); err != nil {
  289. readErr <- err
  290. return
  291. }
  292. }
  293. }
  294. }()
  295. // Op 1 from the server makes the read loop write while the ticker writes too.
  296. for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
  297. if err := writeJSON(GatewayPayload{Op: opHeartbeat}); err != nil {
  298. break
  299. }
  300. // Leave the client room to drain the flood and answer: a saturated
  301. // socket delays the ACK this test now depends on.
  302. time.Sleep(time.Millisecond)
  303. }
  304. select {
  305. case err := <-readErr:
  306. t.Errorf("server read a broken client frame during the flood: %v", err)
  307. default:
  308. }
  309. once.Do(func() { close(flooded) })
  310. }))
  311. defer wsServer.Close()
  312. gw := NewGatewayClient(NewDiscordService(settingService), settingService, nil, nil, nil)
  313. gw.SetGatewayURL("ws" + strings.TrimPrefix(wsServer.URL, "http"))
  314. ctx, cancel := context.WithCancel(context.Background())
  315. defer cancel()
  316. if err := gw.Start(ctx); err != nil {
  317. t.Fatalf("gw.Start failed: %v", err)
  318. }
  319. defer gw.Stop()
  320. select {
  321. case <-flooded:
  322. case <-time.After(5 * time.Second):
  323. t.Fatal("timed out waiting for the heartbeat flood to finish")
  324. }
  325. }
  326. func TestGatewayStopsOnNonReconnectableCloseCode(t *testing.T) {
  327. settingService := setupTestDB(t)
  328. _ = settingService.SetDiscordBotEnable(true)
  329. _ = settingService.SetDiscordBotToken("test-gw-token")
  330. var mu sync.Mutex
  331. dials := 0
  332. upgrader := websocket.Upgrader{}
  333. wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  334. conn, err := upgrader.Upgrade(w, r, nil)
  335. if err != nil {
  336. return
  337. }
  338. defer conn.Close()
  339. mu.Lock()
  340. dials++
  341. mu.Unlock()
  342. _ = conn.WriteJSON(GatewayPayload{Op: opHello, D: []byte(`{"heartbeat_interval": 45000}`)})
  343. var ident GatewayPayload
  344. _ = conn.ReadJSON(&ident)
  345. closeMsg := websocket.FormatCloseMessage(4014, "Disallowed intent(s).")
  346. _ = conn.WriteControl(websocket.CloseMessage, closeMsg, time.Now().Add(time.Second))
  347. }))
  348. defer wsServer.Close()
  349. gw := NewGatewayClient(NewDiscordService(settingService), settingService, nil, nil, nil)
  350. gw.SetGatewayURL("ws" + strings.TrimPrefix(wsServer.URL, "http"))
  351. ctx, cancel := context.WithCancel(context.Background())
  352. defer cancel()
  353. if err := gw.Start(ctx); err != nil {
  354. t.Fatalf("gw.Start failed: %v", err)
  355. }
  356. defer gw.Stop()
  357. for deadline := time.Now().Add(2 * time.Second); gw.IsRunning() && time.Now().Before(deadline); {
  358. time.Sleep(20 * time.Millisecond)
  359. }
  360. if gw.IsRunning() {
  361. t.Fatal("gateway still running after close code 4014, which Discord marks non-reconnectable")
  362. }
  363. mu.Lock()
  364. defer mu.Unlock()
  365. if dials != 1 {
  366. t.Fatalf("gateway dialed %d times, want 1", dials)
  367. }
  368. }
  369. func TestGatewayDialsThroughPanelEgressProxy(t *testing.T) {
  370. settingService := setupTestDB(t)
  371. _ = settingService.SetDiscordBotEnable(true)
  372. _ = settingService.SetDiscordBotToken("test-gw-token")
  373. identified := make(chan struct{}, 1)
  374. upgrader := websocket.Upgrader{}
  375. wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  376. conn, err := upgrader.Upgrade(w, r, nil)
  377. if err != nil {
  378. return
  379. }
  380. defer conn.Close()
  381. _ = conn.WriteJSON(GatewayPayload{Op: opHello, D: []byte(`{"heartbeat_interval": 45000}`)})
  382. var ident GatewayPayload
  383. if conn.ReadJSON(&ident) == nil {
  384. select {
  385. case identified <- struct{}{}:
  386. default:
  387. }
  388. }
  389. for {
  390. if _, _, err := conn.ReadMessage(); err != nil {
  391. return
  392. }
  393. }
  394. }))
  395. defer wsServer.Close()
  396. var mu sync.Mutex
  397. tunneledTo := ""
  398. proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  399. if r.Method != http.MethodConnect {
  400. http.Error(w, "CONNECT only", http.StatusMethodNotAllowed)
  401. return
  402. }
  403. mu.Lock()
  404. tunneledTo = r.Host
  405. mu.Unlock()
  406. upstream, err := net.Dial("tcp", r.Host)
  407. if err != nil {
  408. http.Error(w, err.Error(), http.StatusBadGateway)
  409. return
  410. }
  411. defer upstream.Close()
  412. client, _, err := w.(http.Hijacker).Hijack()
  413. if err != nil {
  414. return
  415. }
  416. defer client.Close()
  417. _, _ = client.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
  418. go func() { _, _ = io.Copy(upstream, client) }()
  419. _, _ = io.Copy(client, upstream)
  420. }))
  421. defer proxy.Close()
  422. gw := NewGatewayClient(NewDiscordService(settingService), settingService, nil, nil, nil)
  423. gw.SetGatewayURL("ws" + strings.TrimPrefix(wsServer.URL, "http"))
  424. gw.egressProxyURL = func() string { return proxy.URL }
  425. ctx, cancel := context.WithCancel(context.Background())
  426. defer cancel()
  427. if err := gw.Start(ctx); err != nil {
  428. t.Fatalf("gw.Start failed: %v", err)
  429. }
  430. defer gw.Stop()
  431. select {
  432. case <-identified:
  433. case <-time.After(3 * time.Second):
  434. t.Fatal("timed out waiting for the gateway to identify")
  435. }
  436. mu.Lock()
  437. defer mu.Unlock()
  438. if want := strings.TrimPrefix(wsServer.URL, "http://"); tunneledTo != want {
  439. t.Fatalf("gateway tunneled to %q through the panel egress proxy, want %q", tunneledTo, want)
  440. }
  441. }
  442. func TestGatewayCommandsRequireListedAdmin(t *testing.T) {
  443. cases := []struct {
  444. name string
  445. adminIDs string
  446. author string
  447. wantRestart bool
  448. }{
  449. {"listed admin", "111, 222", "222", true},
  450. {"unlisted member", "111", "999", false},
  451. {"empty list allows nobody", "", "111", false},
  452. }
  453. for _, tc := range cases {
  454. t.Run(tc.name, func(t *testing.T) {
  455. settingService := setupTestDB(t)
  456. _ = settingService.SetDiscordBotToken("token")
  457. _ = settingService.SetDiscordChannelId("ch-1")
  458. _ = settingService.SetDiscordAdminIds(tc.adminIDs)
  459. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  460. w.WriteHeader(http.StatusOK)
  461. }))
  462. defer server.Close()
  463. svc := NewDiscordService(settingService)
  464. svc.SetBaseURL(server.URL)
  465. svc.SetHTTPClient(server.Client())
  466. restarter := &mockXrayRestart{}
  467. msg := MessageCreateData{ChannelID: "ch-1", Content: "!restart"}
  468. msg.Author.ID = tc.author
  469. NewGatewayClient(svc, settingService, nil, nil, restarter).handleMessage(context.Background(), msg)
  470. if restarter.restarted != tc.wantRestart {
  471. t.Fatalf("author %q with admin list %q: restarted = %v, want %v", tc.author, tc.adminIDs, restarter.restarted, tc.wantRestart)
  472. }
  473. })
  474. }
  475. }