1
0

command_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package command_test
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. "github.com/golang/mock/gomock"
  7. "github.com/google/go-cmp/cmp"
  8. "github.com/google/go-cmp/cmp/cmpopts"
  9. "github.com/xtls/xray-core/app/router"
  10. . "github.com/xtls/xray-core/app/router/command"
  11. "github.com/xtls/xray-core/app/stats"
  12. "github.com/xtls/xray-core/common"
  13. "github.com/xtls/xray-core/common/matcher/domain"
  14. "github.com/xtls/xray-core/common/matcher/geoip"
  15. "github.com/xtls/xray-core/common/net"
  16. "github.com/xtls/xray-core/features/routing"
  17. "github.com/xtls/xray-core/testing/mocks"
  18. "google.golang.org/grpc"
  19. "google.golang.org/grpc/test/bufconn"
  20. )
  21. func TestServiceSubscribeRoutingStats(t *testing.T) {
  22. c := stats.NewChannel(&stats.ChannelConfig{
  23. SubscriberLimit: 1,
  24. BufferSize: 0,
  25. Blocking: true,
  26. })
  27. common.Must(c.Start())
  28. defer c.Close()
  29. lis := bufconn.Listen(1024 * 1024)
  30. bufDialer := func(context.Context, string) (net.Conn, error) {
  31. return lis.Dial()
  32. }
  33. testCases := []*RoutingContext{
  34. {InboundTag: "in", OutboundTag: "out"},
  35. {TargetIPs: [][]byte{{1, 2, 3, 4}}, TargetPort: 8080, OutboundTag: "out"},
  36. {TargetDomain: "example.com", TargetPort: 443, OutboundTag: "out"},
  37. {SourcePort: 9999, TargetPort: 9999, OutboundTag: "out"},
  38. {Network: net.Network_UDP, OutboundGroupTags: []string{"outergroup", "innergroup"}, OutboundTag: "out"},
  39. {Protocol: "bittorrent", OutboundTag: "blocked"},
  40. {User: "[email protected]", OutboundTag: "out"},
  41. {SourceIPs: [][]byte{{127, 0, 0, 1}}, Attributes: map[string]string{"attr": "value"}, OutboundTag: "out"},
  42. }
  43. errCh := make(chan error)
  44. nextPub := make(chan struct{})
  45. // Server goroutine
  46. go func() {
  47. server := grpc.NewServer()
  48. RegisterRoutingServiceServer(server, NewRoutingServer(nil, c))
  49. errCh <- server.Serve(lis)
  50. }()
  51. // Publisher goroutine
  52. go func() {
  53. publishTestCases := func() error {
  54. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  55. defer cancel()
  56. for { // Wait until there's one subscriber in routing stats channel
  57. if len(c.Subscribers()) > 0 {
  58. break
  59. }
  60. if ctx.Err() != nil {
  61. return ctx.Err()
  62. }
  63. }
  64. for _, tc := range testCases {
  65. c.Publish(context.Background(), AsRoutingRoute(tc))
  66. time.Sleep(time.Millisecond)
  67. }
  68. return nil
  69. }
  70. if err := publishTestCases(); err != nil {
  71. errCh <- err
  72. }
  73. // Wait for next round of publishing
  74. <-nextPub
  75. if err := publishTestCases(); err != nil {
  76. errCh <- err
  77. }
  78. }()
  79. // Client goroutine
  80. go func() {
  81. defer lis.Close()
  82. conn, err := grpc.DialContext(context.Background(), "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure())
  83. if err != nil {
  84. errCh <- err
  85. return
  86. }
  87. defer conn.Close()
  88. client := NewRoutingServiceClient(conn)
  89. // Test retrieving all fields
  90. testRetrievingAllFields := func() error {
  91. streamCtx, streamClose := context.WithCancel(context.Background())
  92. // Test the unsubscription of stream works well
  93. defer func() {
  94. streamClose()
  95. timeOutCtx, timeout := context.WithTimeout(context.Background(), time.Second)
  96. defer timeout()
  97. for { // Wait until there's no subscriber in routing stats channel
  98. if len(c.Subscribers()) == 0 {
  99. break
  100. }
  101. if timeOutCtx.Err() != nil {
  102. t.Error("unexpected subscribers not decreased in channel", timeOutCtx.Err())
  103. }
  104. }
  105. }()
  106. stream, err := client.SubscribeRoutingStats(streamCtx, &SubscribeRoutingStatsRequest{})
  107. if err != nil {
  108. return err
  109. }
  110. for _, tc := range testCases {
  111. msg, err := stream.Recv()
  112. if err != nil {
  113. return err
  114. }
  115. if r := cmp.Diff(msg, tc, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
  116. t.Error(r)
  117. }
  118. }
  119. // Test that double subscription will fail
  120. errStream, err := client.SubscribeRoutingStats(context.Background(), &SubscribeRoutingStatsRequest{
  121. FieldSelectors: []string{"ip", "port", "domain", "outbound"},
  122. })
  123. if err != nil {
  124. return err
  125. }
  126. if _, err := errStream.Recv(); err == nil {
  127. t.Error("unexpected successful subscription")
  128. }
  129. return nil
  130. }
  131. // Test retrieving only a subset of fields
  132. testRetrievingSubsetOfFields := func() error {
  133. streamCtx, streamClose := context.WithCancel(context.Background())
  134. defer streamClose()
  135. stream, err := client.SubscribeRoutingStats(streamCtx, &SubscribeRoutingStatsRequest{
  136. FieldSelectors: []string{"ip", "port", "domain", "outbound"},
  137. })
  138. if err != nil {
  139. return err
  140. }
  141. // Send nextPub signal to start next round of publishing
  142. close(nextPub)
  143. for _, tc := range testCases {
  144. msg, err := stream.Recv()
  145. if err != nil {
  146. return err
  147. }
  148. stat := &RoutingContext{ // Only a subset of stats is retrieved
  149. SourceIPs: tc.SourceIPs,
  150. TargetIPs: tc.TargetIPs,
  151. SourcePort: tc.SourcePort,
  152. TargetPort: tc.TargetPort,
  153. TargetDomain: tc.TargetDomain,
  154. OutboundGroupTags: tc.OutboundGroupTags,
  155. OutboundTag: tc.OutboundTag,
  156. }
  157. if r := cmp.Diff(msg, stat, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
  158. t.Error(r)
  159. }
  160. }
  161. return nil
  162. }
  163. if err := testRetrievingAllFields(); err != nil {
  164. errCh <- err
  165. }
  166. if err := testRetrievingSubsetOfFields(); err != nil {
  167. errCh <- err
  168. }
  169. errCh <- nil // Client passed all tests successfully
  170. }()
  171. // Wait for goroutines to complete
  172. select {
  173. case <-time.After(2 * time.Second):
  174. t.Fatal("Test timeout after 2s")
  175. case err := <-errCh:
  176. if err != nil {
  177. t.Fatal(err)
  178. }
  179. }
  180. }
  181. func TestSerivceTestRoute(t *testing.T) {
  182. c := stats.NewChannel(&stats.ChannelConfig{
  183. SubscriberLimit: 1,
  184. BufferSize: 16,
  185. Blocking: true,
  186. })
  187. common.Must(c.Start())
  188. defer c.Close()
  189. r := new(router.Router)
  190. mockCtl := gomock.NewController(t)
  191. defer mockCtl.Finish()
  192. common.Must(r.Init(&router.Config{
  193. Rule: []*router.RoutingRule{
  194. {
  195. InboundTag: []string{"in"},
  196. TargetTag: &router.RoutingRule_Tag{Tag: "out"},
  197. },
  198. {
  199. Protocol: []string{"bittorrent"},
  200. TargetTag: &router.RoutingRule_Tag{Tag: "blocked"},
  201. },
  202. {
  203. PortList: &net.PortList{Range: []*net.PortRange{{From: 8080, To: 8080}}},
  204. TargetTag: &router.RoutingRule_Tag{Tag: "out"},
  205. },
  206. {
  207. SourcePortList: &net.PortList{Range: []*net.PortRange{{From: 9999, To: 9999}}},
  208. TargetTag: &router.RoutingRule_Tag{Tag: "out"},
  209. },
  210. {
  211. Domain: []*domain.Domain{{Type: domain.MatchingType_Subdomain, Value: "com"}},
  212. TargetTag: &router.RoutingRule_Tag{Tag: "out"},
  213. },
  214. {
  215. SourceGeoip: []*geoip.GeoIP{{CountryCode: "private", Cidr: []*geoip.CIDR{{Ip: []byte{127, 0, 0, 0}, Prefix: 8}}}},
  216. TargetTag: &router.RoutingRule_Tag{Tag: "out"},
  217. },
  218. {
  219. UserEmail: []string{"[email protected]"},
  220. TargetTag: &router.RoutingRule_Tag{Tag: "out"},
  221. },
  222. {
  223. Networks: []net.Network{net.Network_UDP, net.Network_TCP},
  224. TargetTag: &router.RoutingRule_Tag{Tag: "out"},
  225. },
  226. },
  227. }, mocks.NewDNSClient(mockCtl), mocks.NewOutboundManager(mockCtl)))
  228. lis := bufconn.Listen(1024 * 1024)
  229. bufDialer := func(context.Context, string) (net.Conn, error) {
  230. return lis.Dial()
  231. }
  232. errCh := make(chan error)
  233. // Server goroutine
  234. go func() {
  235. server := grpc.NewServer()
  236. RegisterRoutingServiceServer(server, NewRoutingServer(r, c))
  237. errCh <- server.Serve(lis)
  238. }()
  239. // Client goroutine
  240. go func() {
  241. defer lis.Close()
  242. conn, err := grpc.DialContext(context.Background(), "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure())
  243. if err != nil {
  244. errCh <- err
  245. }
  246. defer conn.Close()
  247. client := NewRoutingServiceClient(conn)
  248. testCases := []*RoutingContext{
  249. {InboundTag: "in", OutboundTag: "out"},
  250. {TargetIPs: [][]byte{{1, 2, 3, 4}}, TargetPort: 8080, OutboundTag: "out"},
  251. {TargetDomain: "example.com", TargetPort: 443, OutboundTag: "out"},
  252. {SourcePort: 9999, TargetPort: 9999, OutboundTag: "out"},
  253. {Network: net.Network_UDP, Protocol: "bittorrent", OutboundTag: "blocked"},
  254. {User: "[email protected]", OutboundTag: "out"},
  255. {SourceIPs: [][]byte{{127, 0, 0, 1}}, Attributes: map[string]string{"attr": "value"}, OutboundTag: "out"},
  256. }
  257. // Test simple TestRoute
  258. testSimple := func() error {
  259. for _, tc := range testCases {
  260. route, err := client.TestRoute(context.Background(), &TestRouteRequest{RoutingContext: tc})
  261. if err != nil {
  262. return err
  263. }
  264. if r := cmp.Diff(route, tc, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
  265. t.Error(r)
  266. }
  267. }
  268. return nil
  269. }
  270. // Test TestRoute with special options
  271. testOptions := func() error {
  272. sub, err := c.Subscribe()
  273. if err != nil {
  274. return err
  275. }
  276. for _, tc := range testCases {
  277. route, err := client.TestRoute(context.Background(), &TestRouteRequest{
  278. RoutingContext: tc,
  279. FieldSelectors: []string{"ip", "port", "domain", "outbound"},
  280. PublishResult: true,
  281. })
  282. if err != nil {
  283. return err
  284. }
  285. stat := &RoutingContext{ // Only a subset of stats is retrieved
  286. SourceIPs: tc.SourceIPs,
  287. TargetIPs: tc.TargetIPs,
  288. SourcePort: tc.SourcePort,
  289. TargetPort: tc.TargetPort,
  290. TargetDomain: tc.TargetDomain,
  291. OutboundGroupTags: tc.OutboundGroupTags,
  292. OutboundTag: tc.OutboundTag,
  293. }
  294. if r := cmp.Diff(route, stat, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
  295. t.Error(r)
  296. }
  297. select { // Check that routing result has been published to statistics channel
  298. case msg, received := <-sub:
  299. if route, ok := msg.(routing.Route); received && ok {
  300. if r := cmp.Diff(AsProtobufMessage(nil)(route), tc, cmpopts.IgnoreUnexported(RoutingContext{})); r != "" {
  301. t.Error(r)
  302. }
  303. } else {
  304. t.Error("unexpected failure in receiving published routing result for testcase", tc)
  305. }
  306. case <-time.After(100 * time.Millisecond):
  307. t.Error("unexpected failure in receiving published routing result", tc)
  308. }
  309. }
  310. return nil
  311. }
  312. if err := testSimple(); err != nil {
  313. errCh <- err
  314. }
  315. if err := testOptions(); err != nil {
  316. errCh <- err
  317. }
  318. errCh <- nil // Client passed all tests successfully
  319. }()
  320. // Wait for goroutines to complete
  321. select {
  322. case <-time.After(2 * time.Second):
  323. t.Fatal("Test timeout after 2s")
  324. case err := <-errCh:
  325. if err != nil {
  326. t.Fatal(err)
  327. }
  328. }
  329. }