server_test.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. /*
  2. *
  3. * Copyright 2020 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package xds
  19. import (
  20. "context"
  21. "errors"
  22. "fmt"
  23. "net"
  24. "reflect"
  25. "strings"
  26. "testing"
  27. "time"
  28. "google.golang.org/grpc"
  29. "google.golang.org/grpc/connectivity"
  30. "google.golang.org/grpc/credentials/insecure"
  31. "google.golang.org/grpc/credentials/tls/certprovider"
  32. "google.golang.org/grpc/credentials/xds"
  33. "google.golang.org/grpc/internal/grpctest"
  34. "google.golang.org/grpc/internal/testutils"
  35. "google.golang.org/grpc/internal/testutils/xds/e2e"
  36. _ "google.golang.org/grpc/xds/internal/httpfilter/router"
  37. xdstestutils "google.golang.org/grpc/xds/internal/testutils"
  38. "google.golang.org/grpc/xds/internal/testutils/fakeclient"
  39. "google.golang.org/grpc/xds/internal/xdsclient"
  40. "google.golang.org/grpc/xds/internal/xdsclient/bootstrap"
  41. "google.golang.org/grpc/xds/internal/xdsclient/xdsresource"
  42. v3corepb "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
  43. v3listenerpb "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3"
  44. v3routepb "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
  45. v3httppb "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3"
  46. v3tlspb "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3"
  47. wrapperspb "github.com/golang/protobuf/ptypes/wrappers"
  48. )
  49. const (
  50. defaultTestTimeout = 5 * time.Second
  51. defaultTestShortTimeout = 10 * time.Millisecond
  52. testServerListenerResourceNameTemplate = "/path/to/resource/%s/%s"
  53. )
  54. var listenerWithFilterChains = &v3listenerpb.Listener{
  55. FilterChains: []*v3listenerpb.FilterChain{
  56. {
  57. FilterChainMatch: &v3listenerpb.FilterChainMatch{
  58. PrefixRanges: []*v3corepb.CidrRange{
  59. {
  60. AddressPrefix: "192.168.0.0",
  61. PrefixLen: &wrapperspb.UInt32Value{
  62. Value: uint32(16),
  63. },
  64. },
  65. },
  66. SourceType: v3listenerpb.FilterChainMatch_SAME_IP_OR_LOOPBACK,
  67. SourcePrefixRanges: []*v3corepb.CidrRange{
  68. {
  69. AddressPrefix: "192.168.0.0",
  70. PrefixLen: &wrapperspb.UInt32Value{
  71. Value: uint32(16),
  72. },
  73. },
  74. },
  75. SourcePorts: []uint32{80},
  76. },
  77. TransportSocket: &v3corepb.TransportSocket{
  78. Name: "envoy.transport_sockets.tls",
  79. ConfigType: &v3corepb.TransportSocket_TypedConfig{
  80. TypedConfig: testutils.MarshalAny(&v3tlspb.DownstreamTlsContext{
  81. CommonTlsContext: &v3tlspb.CommonTlsContext{
  82. TlsCertificateCertificateProviderInstance: &v3tlspb.CommonTlsContext_CertificateProviderInstance{
  83. InstanceName: "identityPluginInstance",
  84. CertificateName: "identityCertName",
  85. },
  86. },
  87. }),
  88. },
  89. },
  90. Filters: []*v3listenerpb.Filter{
  91. {
  92. Name: "filter-1",
  93. ConfigType: &v3listenerpb.Filter_TypedConfig{
  94. TypedConfig: testutils.MarshalAny(&v3httppb.HttpConnectionManager{
  95. RouteSpecifier: &v3httppb.HttpConnectionManager_RouteConfig{
  96. RouteConfig: &v3routepb.RouteConfiguration{
  97. Name: "routeName",
  98. VirtualHosts: []*v3routepb.VirtualHost{{
  99. Domains: []string{"lds.target.good:3333"},
  100. Routes: []*v3routepb.Route{{
  101. Match: &v3routepb.RouteMatch{
  102. PathSpecifier: &v3routepb.RouteMatch_Prefix{Prefix: "/"},
  103. },
  104. Action: &v3routepb.Route_NonForwardingAction{},
  105. }}}}},
  106. },
  107. HttpFilters: []*v3httppb.HttpFilter{e2e.RouterHTTPFilter},
  108. }),
  109. },
  110. },
  111. },
  112. },
  113. },
  114. }
  115. type s struct {
  116. grpctest.Tester
  117. }
  118. func Test(t *testing.T) {
  119. grpctest.RunSubTests(t, s{})
  120. }
  121. type fakeGRPCServer struct {
  122. done chan struct{}
  123. registerServiceCh *testutils.Channel
  124. serveCh *testutils.Channel
  125. stopCh *testutils.Channel
  126. gracefulStopCh *testutils.Channel
  127. }
  128. func (f *fakeGRPCServer) RegisterService(*grpc.ServiceDesc, interface{}) {
  129. f.registerServiceCh.Send(nil)
  130. }
  131. func (f *fakeGRPCServer) Serve(lis net.Listener) error {
  132. f.serveCh.Send(nil)
  133. <-f.done
  134. lis.Close()
  135. return nil
  136. }
  137. func (f *fakeGRPCServer) Stop() {
  138. close(f.done)
  139. f.stopCh.Send(nil)
  140. }
  141. func (f *fakeGRPCServer) GracefulStop() {
  142. close(f.done)
  143. f.gracefulStopCh.Send(nil)
  144. }
  145. func (f *fakeGRPCServer) GetServiceInfo() map[string]grpc.ServiceInfo {
  146. panic("implement me")
  147. }
  148. func newFakeGRPCServer() *fakeGRPCServer {
  149. return &fakeGRPCServer{
  150. done: make(chan struct{}),
  151. registerServiceCh: testutils.NewChannel(),
  152. serveCh: testutils.NewChannel(),
  153. stopCh: testutils.NewChannel(),
  154. gracefulStopCh: testutils.NewChannel(),
  155. }
  156. }
  157. func splitHostPort(hostport string) (string, string) {
  158. addr, port, err := net.SplitHostPort(hostport)
  159. if err != nil {
  160. panic(fmt.Sprintf("listener address %q does not parse: %v", hostport, err))
  161. }
  162. return addr, port
  163. }
  164. func (s) TestNewServer(t *testing.T) {
  165. xdsCreds, err := xds.NewServerCredentials(xds.ServerOptions{FallbackCreds: insecure.NewCredentials()})
  166. if err != nil {
  167. t.Fatalf("failed to create xds server credentials: %v", err)
  168. }
  169. tests := []struct {
  170. desc string
  171. serverOpts []grpc.ServerOption
  172. wantXDSCredsInUse bool
  173. }{
  174. {
  175. desc: "without_xds_creds",
  176. serverOpts: []grpc.ServerOption{grpc.Creds(insecure.NewCredentials())},
  177. },
  178. {
  179. desc: "with_xds_creds",
  180. serverOpts: []grpc.ServerOption{grpc.Creds(xdsCreds)},
  181. wantXDSCredsInUse: true,
  182. },
  183. }
  184. for _, test := range tests {
  185. t.Run(test.desc, func(t *testing.T) {
  186. // The xds package adds a couple of server options (unary and stream
  187. // interceptors) to the server options passed in by the user.
  188. wantServerOpts := len(test.serverOpts) + 2
  189. origNewGRPCServer := newGRPCServer
  190. newGRPCServer = func(opts ...grpc.ServerOption) grpcServer {
  191. if got := len(opts); got != wantServerOpts {
  192. t.Fatalf("%d ServerOptions passed to grpc.Server, want %d", got, wantServerOpts)
  193. }
  194. // Verify that the user passed ServerOptions are forwarded as is.
  195. if !reflect.DeepEqual(opts[2:], test.serverOpts) {
  196. t.Fatalf("got ServerOptions %v, want %v", opts[2:], test.serverOpts)
  197. }
  198. return grpc.NewServer(opts...)
  199. }
  200. defer func() {
  201. newGRPCServer = origNewGRPCServer
  202. }()
  203. s := NewGRPCServer(test.serverOpts...)
  204. defer s.Stop()
  205. if s.xdsCredsInUse != test.wantXDSCredsInUse {
  206. t.Fatalf("xdsCredsInUse is %v, want %v", s.xdsCredsInUse, test.wantXDSCredsInUse)
  207. }
  208. })
  209. }
  210. }
  211. func (s) TestRegisterService(t *testing.T) {
  212. fs := newFakeGRPCServer()
  213. origNewGRPCServer := newGRPCServer
  214. newGRPCServer = func(opts ...grpc.ServerOption) grpcServer { return fs }
  215. defer func() { newGRPCServer = origNewGRPCServer }()
  216. s := NewGRPCServer()
  217. defer s.Stop()
  218. s.RegisterService(&grpc.ServiceDesc{}, nil)
  219. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  220. defer cancel()
  221. if _, err := fs.registerServiceCh.Receive(ctx); err != nil {
  222. t.Fatalf("timeout when expecting RegisterService() to called on grpc.Server: %v", err)
  223. }
  224. }
  225. const (
  226. fakeProvider1Name = "fake-certificate-provider-1"
  227. fakeProvider2Name = "fake-certificate-provider-2"
  228. fakeConfig = "my fake config"
  229. )
  230. var (
  231. fpb1, fpb2 *fakeProviderBuilder
  232. certProviderConfigs map[string]*certprovider.BuildableConfig
  233. )
  234. func init() {
  235. fpb1 = &fakeProviderBuilder{
  236. name: fakeProvider1Name,
  237. buildCh: testutils.NewChannel(),
  238. }
  239. fpb2 = &fakeProviderBuilder{
  240. name: fakeProvider2Name,
  241. buildCh: testutils.NewChannel(),
  242. }
  243. cfg1, _ := fpb1.ParseConfig(fakeConfig + "1111")
  244. cfg2, _ := fpb2.ParseConfig(fakeConfig + "2222")
  245. certProviderConfigs = map[string]*certprovider.BuildableConfig{
  246. "default1": cfg1,
  247. "default2": cfg2,
  248. }
  249. certprovider.Register(fpb1)
  250. certprovider.Register(fpb2)
  251. }
  252. // fakeProviderBuilder builds new instances of fakeProvider and interprets the
  253. // config provided to it as a string.
  254. type fakeProviderBuilder struct {
  255. name string
  256. buildCh *testutils.Channel
  257. }
  258. func (b *fakeProviderBuilder) ParseConfig(config interface{}) (*certprovider.BuildableConfig, error) {
  259. s, ok := config.(string)
  260. if !ok {
  261. return nil, fmt.Errorf("providerBuilder %s received config of type %T, want string", b.name, config)
  262. }
  263. return certprovider.NewBuildableConfig(b.name, []byte(s), func(certprovider.BuildOptions) certprovider.Provider {
  264. b.buildCh.Send(nil)
  265. return &fakeProvider{
  266. Distributor: certprovider.NewDistributor(),
  267. config: s,
  268. }
  269. }), nil
  270. }
  271. func (b *fakeProviderBuilder) Name() string {
  272. return b.name
  273. }
  274. // fakeProvider is an implementation of the Provider interface which provides a
  275. // method for tests to invoke to push new key materials.
  276. type fakeProvider struct {
  277. *certprovider.Distributor
  278. config string
  279. }
  280. // Close helps implement the Provider interface.
  281. func (p *fakeProvider) Close() {
  282. p.Distributor.Stop()
  283. }
  284. // setupOverrides sets up overrides for bootstrap config, new xdsClient creation
  285. // and new gRPC.Server creation.
  286. func setupOverrides(t *testing.T) (*fakeGRPCServer, *testutils.Channel, func()) {
  287. clientCh := testutils.NewChannel()
  288. origNewXDSClient := newXDSClient
  289. newXDSClient = func() (xdsclient.XDSClient, func(), error) {
  290. c := fakeclient.NewClient()
  291. c.SetBootstrapConfig(&bootstrap.Config{
  292. XDSServer: xdstestutils.ServerConfigForAddress(t, "server-address"),
  293. NodeProto: xdstestutils.EmptyNodeProtoV3,
  294. ServerListenerResourceNameTemplate: testServerListenerResourceNameTemplate,
  295. CertProviderConfigs: certProviderConfigs,
  296. })
  297. clientCh.Send(c)
  298. return c, func() {}, nil
  299. }
  300. fs := newFakeGRPCServer()
  301. origNewGRPCServer := newGRPCServer
  302. newGRPCServer = func(opts ...grpc.ServerOption) grpcServer { return fs }
  303. return fs, clientCh, func() {
  304. newXDSClient = origNewXDSClient
  305. newGRPCServer = origNewGRPCServer
  306. }
  307. }
  308. // setupOverridesForXDSCreds overrides only the xdsClient creation with a fake
  309. // one. Tests that use xdsCredentials need a real grpc.Server instead of a fake
  310. // one, because the xDS-enabled server needs to read configured creds from the
  311. // underlying grpc.Server to confirm whether xdsCreds were configured.
  312. func setupOverridesForXDSCreds(t *testing.T, includeCertProviderCfg bool) (*testutils.Channel, func()) {
  313. clientCh := testutils.NewChannel()
  314. origNewXDSClient := newXDSClient
  315. newXDSClient = func() (xdsclient.XDSClient, func(), error) {
  316. c := fakeclient.NewClient()
  317. bc := &bootstrap.Config{
  318. XDSServer: xdstestutils.ServerConfigForAddress(t, "server-address"),
  319. NodeProto: xdstestutils.EmptyNodeProtoV3,
  320. ServerListenerResourceNameTemplate: testServerListenerResourceNameTemplate,
  321. }
  322. if includeCertProviderCfg {
  323. bc.CertProviderConfigs = certProviderConfigs
  324. }
  325. c.SetBootstrapConfig(bc)
  326. clientCh.Send(c)
  327. return c, func() {}, nil
  328. }
  329. return clientCh, func() { newXDSClient = origNewXDSClient }
  330. }
  331. // TestServeSuccess tests the successful case of calling Serve().
  332. // The following sequence of events happen:
  333. // 1. Create a new GRPCServer and call Serve() in a goroutine.
  334. // 2. Make sure an xdsClient is created, and an LDS watch is registered.
  335. // 3. Push an error response from the xdsClient, and make sure that Serve() does
  336. // not exit.
  337. // 4. Push a good response from the xdsClient, and make sure that Serve() on the
  338. // underlying grpc.Server is called.
  339. func (s) TestServeSuccess(t *testing.T) {
  340. fs, clientCh, cleanup := setupOverrides(t)
  341. defer cleanup()
  342. // Create a new xDS-enabled gRPC server and pass it a server option to get
  343. // notified about serving mode changes.
  344. modeChangeCh := testutils.NewChannel()
  345. modeChangeOption := ServingModeCallback(func(addr net.Addr, args ServingModeChangeArgs) {
  346. t.Logf("server mode change callback invoked for listener %q with mode %q and error %v", addr.String(), args.Mode, args.Err)
  347. modeChangeCh.Send(args.Mode)
  348. })
  349. server := NewGRPCServer(modeChangeOption)
  350. defer server.Stop()
  351. lis, err := testutils.LocalTCPListener()
  352. if err != nil {
  353. t.Fatalf("testutils.LocalTCPListener() failed: %v", err)
  354. }
  355. // Call Serve() in a goroutine, and push on a channel when Serve returns.
  356. serveDone := testutils.NewChannel()
  357. go func() {
  358. if err := server.Serve(lis); err != nil {
  359. t.Error(err)
  360. }
  361. serveDone.Send(nil)
  362. }()
  363. // Wait for an xdsClient to be created.
  364. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  365. defer cancel()
  366. c, err := clientCh.Receive(ctx)
  367. if err != nil {
  368. t.Fatalf("error when waiting for new xdsClient to be created: %v", err)
  369. }
  370. client := c.(*fakeclient.Client)
  371. // Wait for a listener watch to be registered on the xdsClient.
  372. name, err := client.WaitForWatchListener(ctx)
  373. if err != nil {
  374. t.Fatalf("error when waiting for a ListenerWatch: %v", err)
  375. }
  376. wantName := strings.Replace(testServerListenerResourceNameTemplate, "%s", lis.Addr().String(), -1)
  377. if name != wantName {
  378. t.Fatalf("LDS watch registered for name %q, want %q", name, wantName)
  379. }
  380. // Push an error to the registered listener watch callback and make sure
  381. // that Serve does not return.
  382. client.InvokeWatchListenerCallback(xdsresource.ListenerUpdate{}, xdsresource.NewErrorf(xdsresource.ErrorTypeResourceNotFound, "LDS resource not found"))
  383. sCtx, sCancel := context.WithTimeout(context.Background(), defaultTestShortTimeout)
  384. defer sCancel()
  385. if _, err := serveDone.Receive(sCtx); err != context.DeadlineExceeded {
  386. t.Fatal("Serve() returned after a bad LDS response")
  387. }
  388. // Make sure the serving mode changes appropriately.
  389. v, err := modeChangeCh.Receive(ctx)
  390. if err != nil {
  391. t.Fatalf("error when waiting for serving mode to change: %v", err)
  392. }
  393. if mode := v.(connectivity.ServingMode); mode != connectivity.ServingModeNotServing {
  394. t.Fatalf("server mode is %q, want %q", mode, connectivity.ServingModeNotServing)
  395. }
  396. // Push a good LDS response, and wait for Serve() to be invoked on the
  397. // underlying grpc.Server.
  398. fcm, err := xdsresource.NewFilterChainManager(listenerWithFilterChains)
  399. if err != nil {
  400. t.Fatalf("xdsclient.NewFilterChainManager() failed with error: %v", err)
  401. }
  402. addr, port := splitHostPort(lis.Addr().String())
  403. client.InvokeWatchListenerCallback(xdsresource.ListenerUpdate{
  404. RouteConfigName: "routeconfig",
  405. InboundListenerCfg: &xdsresource.InboundListenerConfig{
  406. Address: addr,
  407. Port: port,
  408. FilterChains: fcm,
  409. },
  410. }, nil)
  411. if _, err := fs.serveCh.Receive(ctx); err != nil {
  412. t.Fatalf("error when waiting for Serve() to be invoked on the grpc.Server")
  413. }
  414. // Make sure the serving mode changes appropriately.
  415. v, err = modeChangeCh.Receive(ctx)
  416. if err != nil {
  417. t.Fatalf("error when waiting for serving mode to change: %v", err)
  418. }
  419. if mode := v.(connectivity.ServingMode); mode != connectivity.ServingModeServing {
  420. t.Fatalf("server mode is %q, want %q", mode, connectivity.ServingModeServing)
  421. }
  422. // Push an update to the registered listener watch callback with a Listener
  423. // resource whose host:port does not match the actual listening address and
  424. // port. This will push the listener to "not-serving" mode.
  425. client.InvokeWatchListenerCallback(xdsresource.ListenerUpdate{
  426. RouteConfigName: "routeconfig",
  427. InboundListenerCfg: &xdsresource.InboundListenerConfig{
  428. Address: "10.20.30.40",
  429. Port: "666",
  430. FilterChains: fcm,
  431. },
  432. }, nil)
  433. sCtx, sCancel = context.WithTimeout(context.Background(), defaultTestShortTimeout)
  434. defer sCancel()
  435. if _, err := serveDone.Receive(sCtx); err != context.DeadlineExceeded {
  436. t.Fatal("Serve() returned after a bad LDS response")
  437. }
  438. // Make sure the serving mode changes appropriately.
  439. v, err = modeChangeCh.Receive(ctx)
  440. if err != nil {
  441. t.Fatalf("error when waiting for serving mode to change: %v", err)
  442. }
  443. if mode := v.(connectivity.ServingMode); mode != connectivity.ServingModeNotServing {
  444. t.Fatalf("server mode is %q, want %q", mode, connectivity.ServingModeNotServing)
  445. }
  446. }
  447. // TestServeWithStop tests the case where Stop() is called before an LDS update
  448. // is received. This should cause Serve() to exit before calling Serve() on the
  449. // underlying grpc.Server.
  450. func (s) TestServeWithStop(t *testing.T) {
  451. fs, clientCh, cleanup := setupOverrides(t)
  452. defer cleanup()
  453. // Note that we are not deferring the Stop() here since we explicitly call
  454. // it after the LDS watch has been registered.
  455. server := NewGRPCServer()
  456. lis, err := testutils.LocalTCPListener()
  457. if err != nil {
  458. server.Stop()
  459. t.Fatalf("testutils.LocalTCPListener() failed: %v", err)
  460. }
  461. // Call Serve() in a goroutine, and push on a channel when Serve returns.
  462. serveDone := testutils.NewChannel()
  463. go func() {
  464. if err := server.Serve(lis); err != nil {
  465. t.Error(err)
  466. }
  467. serveDone.Send(nil)
  468. }()
  469. // Wait for an xdsClient to be created.
  470. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  471. defer cancel()
  472. c, err := clientCh.Receive(ctx)
  473. if err != nil {
  474. server.Stop()
  475. t.Fatalf("error when waiting for new xdsClient to be created: %v", err)
  476. }
  477. client := c.(*fakeclient.Client)
  478. // Wait for a listener watch to be registered on the xdsClient.
  479. name, err := client.WaitForWatchListener(ctx)
  480. if err != nil {
  481. server.Stop()
  482. t.Fatalf("error when waiting for a ListenerWatch: %v", err)
  483. }
  484. wantName := strings.Replace(testServerListenerResourceNameTemplate, "%s", lis.Addr().String(), -1)
  485. if name != wantName {
  486. server.Stop()
  487. t.Fatalf("LDS watch registered for name %q, wantPrefix %q", name, wantName)
  488. }
  489. // Call Stop() on the server before a listener update is received, and
  490. // expect Serve() to exit.
  491. server.Stop()
  492. if _, err := serveDone.Receive(ctx); err != nil {
  493. t.Fatalf("error when waiting for Serve() to exit")
  494. }
  495. // Make sure that Serve() on the underlying grpc.Server is not called.
  496. sCtx, sCancel := context.WithTimeout(context.Background(), defaultTestShortTimeout)
  497. defer sCancel()
  498. if _, err := fs.serveCh.Receive(sCtx); err != context.DeadlineExceeded {
  499. t.Fatal("Serve() called on underlying grpc.Server")
  500. }
  501. }
  502. // TestServeBootstrapFailure tests the case where xDS bootstrap fails and
  503. // verifies that Serve() exits with a non-nil error.
  504. func (s) TestServeBootstrapFailure(t *testing.T) {
  505. // Since we have not setup fakes for anything, this will attempt to do real
  506. // xDS bootstrap and that will fail because the bootstrap environment
  507. // variable is not set.
  508. server := NewGRPCServer()
  509. defer server.Stop()
  510. lis, err := testutils.LocalTCPListener()
  511. if err != nil {
  512. t.Fatalf("testutils.LocalTCPListener() failed: %v", err)
  513. }
  514. serveDone := testutils.NewChannel()
  515. go func() { serveDone.Send(server.Serve(lis)) }()
  516. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  517. defer cancel()
  518. v, err := serveDone.Receive(ctx)
  519. if err != nil {
  520. t.Fatalf("error when waiting for Serve() to exit: %v", err)
  521. }
  522. if err, ok := v.(error); !ok || err == nil {
  523. t.Fatal("Serve() did not exit with error")
  524. }
  525. }
  526. // TestServeBootstrapConfigInvalid tests the cases where the bootstrap config
  527. // does not contain expected fields. Verifies that the call to Serve() fails.
  528. func (s) TestServeBootstrapConfigInvalid(t *testing.T) {
  529. tests := []struct {
  530. desc string
  531. bootstrapConfig *bootstrap.Config
  532. }{
  533. {
  534. desc: "bootstrap config is missing",
  535. bootstrapConfig: nil,
  536. },
  537. {
  538. desc: "certificate provider config is missing",
  539. bootstrapConfig: &bootstrap.Config{
  540. XDSServer: xdstestutils.ServerConfigForAddress(t, "server-address"),
  541. NodeProto: xdstestutils.EmptyNodeProtoV3,
  542. ServerListenerResourceNameTemplate: testServerListenerResourceNameTemplate,
  543. },
  544. },
  545. {
  546. desc: "server_listener_resource_name_template is missing",
  547. bootstrapConfig: &bootstrap.Config{
  548. XDSServer: xdstestutils.ServerConfigForAddress(t, "server-address"),
  549. NodeProto: xdstestutils.EmptyNodeProtoV3,
  550. CertProviderConfigs: certProviderConfigs,
  551. },
  552. },
  553. }
  554. for _, test := range tests {
  555. t.Run(test.desc, func(t *testing.T) {
  556. // Override the xdsClient creation with one that returns a fake
  557. // xdsClient with the specified bootstrap configuration.
  558. clientCh := testutils.NewChannel()
  559. origNewXDSClient := newXDSClient
  560. newXDSClient = func() (xdsclient.XDSClient, func(), error) {
  561. c := fakeclient.NewClient()
  562. c.SetBootstrapConfig(test.bootstrapConfig)
  563. clientCh.Send(c)
  564. return c, func() {}, nil
  565. }
  566. defer func() { newXDSClient = origNewXDSClient }()
  567. xdsCreds, err := xds.NewServerCredentials(xds.ServerOptions{FallbackCreds: insecure.NewCredentials()})
  568. if err != nil {
  569. t.Fatalf("failed to create xds server credentials: %v", err)
  570. }
  571. server := NewGRPCServer(grpc.Creds(xdsCreds))
  572. defer server.Stop()
  573. lis, err := testutils.LocalTCPListener()
  574. if err != nil {
  575. t.Fatalf("testutils.LocalTCPListener() failed: %v", err)
  576. }
  577. serveDone := testutils.NewChannel()
  578. go func() {
  579. err := server.Serve(lis)
  580. serveDone.Send(err)
  581. }()
  582. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  583. defer cancel()
  584. v, err := serveDone.Receive(ctx)
  585. if err != nil {
  586. t.Fatalf("error when waiting for Serve() to exit: %v", err)
  587. }
  588. if err, ok := v.(error); !ok || err == nil {
  589. t.Fatal("Serve() did not exit with error")
  590. }
  591. })
  592. }
  593. }
  594. // TestServeNewClientFailure tests the case where xds client creation fails and
  595. // verifies that Server() exits with a non-nil error.
  596. func (s) TestServeNewClientFailure(t *testing.T) {
  597. origNewXDSClient := newXDSClient
  598. newXDSClient = func() (xdsclient.XDSClient, func(), error) {
  599. return nil, nil, errors.New("xdsClient creation failed")
  600. }
  601. defer func() { newXDSClient = origNewXDSClient }()
  602. server := NewGRPCServer()
  603. defer server.Stop()
  604. lis, err := testutils.LocalTCPListener()
  605. if err != nil {
  606. t.Fatalf("testutils.LocalTCPListener() failed: %v", err)
  607. }
  608. serveDone := testutils.NewChannel()
  609. go func() {
  610. err := server.Serve(lis)
  611. serveDone.Send(err)
  612. }()
  613. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  614. defer cancel()
  615. v, err := serveDone.Receive(ctx)
  616. if err != nil {
  617. t.Fatalf("error when waiting for Serve() to exit: %v", err)
  618. }
  619. if err, ok := v.(error); !ok || err == nil {
  620. t.Fatal("Serve() did not exit with error")
  621. }
  622. }
  623. // TestHandleListenerUpdate_NoXDSCreds tests the case where an xds-enabled gRPC
  624. // server is not configured with xDS credentials. Verifies that the security
  625. // config received as part of a Listener update is not acted upon.
  626. func (s) TestHandleListenerUpdate_NoXDSCreds(t *testing.T) {
  627. fs, clientCh, cleanup := setupOverrides(t)
  628. defer cleanup()
  629. // Create a server option to get notified about serving mode changes. We don't
  630. // do anything other than throwing a log entry here. But this is required,
  631. // since the server code emits a log entry at the default level (which is
  632. // ERROR) if no callback is registered for serving mode changes. Our
  633. // testLogger fails the test if there is any log entry at ERROR level. It does
  634. // provide an ExpectError() method, but that takes a string and it would be
  635. // painful to construct the exact error message expected here. Instead this
  636. // works just fine.
  637. modeChangeOpt := ServingModeCallback(func(addr net.Addr, args ServingModeChangeArgs) {
  638. t.Logf("Serving mode for listener %q changed to %q, err: %v", addr.String(), args.Mode, args.Err)
  639. })
  640. server := NewGRPCServer(modeChangeOpt)
  641. defer server.Stop()
  642. lis, err := testutils.LocalTCPListener()
  643. if err != nil {
  644. t.Fatalf("testutils.LocalTCPListener() failed: %v", err)
  645. }
  646. // Call Serve() in a goroutine, and push on a channel when Serve returns.
  647. serveDone := testutils.NewChannel()
  648. go func() {
  649. if err := server.Serve(lis); err != nil {
  650. t.Error(err)
  651. }
  652. serveDone.Send(nil)
  653. }()
  654. // Wait for an xdsClient to be created.
  655. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  656. defer cancel()
  657. c, err := clientCh.Receive(ctx)
  658. if err != nil {
  659. t.Fatalf("error when waiting for new xdsClient to be created: %v", err)
  660. }
  661. client := c.(*fakeclient.Client)
  662. // Wait for a listener watch to be registered on the xdsClient.
  663. name, err := client.WaitForWatchListener(ctx)
  664. if err != nil {
  665. t.Fatalf("error when waiting for a ListenerWatch: %v", err)
  666. }
  667. wantName := strings.Replace(testServerListenerResourceNameTemplate, "%s", lis.Addr().String(), -1)
  668. if name != wantName {
  669. t.Fatalf("LDS watch registered for name %q, want %q", name, wantName)
  670. }
  671. // Push a good LDS response with security config, and wait for Serve() to be
  672. // invoked on the underlying grpc.Server. Also make sure that certificate
  673. // providers are not created.
  674. fcm, err := xdsresource.NewFilterChainManager(&v3listenerpb.Listener{
  675. FilterChains: []*v3listenerpb.FilterChain{
  676. {
  677. TransportSocket: &v3corepb.TransportSocket{
  678. Name: "envoy.transport_sockets.tls",
  679. ConfigType: &v3corepb.TransportSocket_TypedConfig{
  680. TypedConfig: testutils.MarshalAny(&v3tlspb.DownstreamTlsContext{
  681. CommonTlsContext: &v3tlspb.CommonTlsContext{
  682. TlsCertificateCertificateProviderInstance: &v3tlspb.CommonTlsContext_CertificateProviderInstance{
  683. InstanceName: "identityPluginInstance",
  684. CertificateName: "identityCertName",
  685. },
  686. },
  687. }),
  688. },
  689. },
  690. Filters: []*v3listenerpb.Filter{
  691. {
  692. Name: "filter-1",
  693. ConfigType: &v3listenerpb.Filter_TypedConfig{
  694. TypedConfig: testutils.MarshalAny(&v3httppb.HttpConnectionManager{
  695. RouteSpecifier: &v3httppb.HttpConnectionManager_RouteConfig{
  696. RouteConfig: &v3routepb.RouteConfiguration{
  697. Name: "routeName",
  698. VirtualHosts: []*v3routepb.VirtualHost{{
  699. Domains: []string{"lds.target.good:3333"},
  700. Routes: []*v3routepb.Route{{
  701. Match: &v3routepb.RouteMatch{
  702. PathSpecifier: &v3routepb.RouteMatch_Prefix{Prefix: "/"},
  703. },
  704. Action: &v3routepb.Route_NonForwardingAction{},
  705. }}}}},
  706. },
  707. HttpFilters: []*v3httppb.HttpFilter{e2e.RouterHTTPFilter},
  708. }),
  709. },
  710. },
  711. },
  712. },
  713. },
  714. })
  715. if err != nil {
  716. t.Fatalf("xdsclient.NewFilterChainManager() failed with error: %v", err)
  717. }
  718. addr, port := splitHostPort(lis.Addr().String())
  719. client.InvokeWatchListenerCallback(xdsresource.ListenerUpdate{
  720. RouteConfigName: "routeconfig",
  721. InboundListenerCfg: &xdsresource.InboundListenerConfig{
  722. Address: addr,
  723. Port: port,
  724. FilterChains: fcm,
  725. },
  726. }, nil)
  727. if _, err := fs.serveCh.Receive(ctx); err != nil {
  728. t.Fatalf("error when waiting for Serve() to be invoked on the grpc.Server")
  729. }
  730. // Make sure the security configuration is not acted upon.
  731. if err := verifyCertProviderNotCreated(); err != nil {
  732. t.Fatal(err)
  733. }
  734. }
  735. // TestHandleListenerUpdate_ErrorUpdate tests the case where an xds-enabled gRPC
  736. // server is configured with xDS credentials, but receives a Listener update
  737. // with an error. Verifies that no certificate providers are created.
  738. func (s) TestHandleListenerUpdate_ErrorUpdate(t *testing.T) {
  739. clientCh, cleanup := setupOverridesForXDSCreds(t, true)
  740. defer cleanup()
  741. xdsCreds, err := xds.NewServerCredentials(xds.ServerOptions{FallbackCreds: insecure.NewCredentials()})
  742. if err != nil {
  743. t.Fatalf("failed to create xds server credentials: %v", err)
  744. }
  745. server := NewGRPCServer(grpc.Creds(xdsCreds))
  746. defer server.Stop()
  747. lis, err := testutils.LocalTCPListener()
  748. if err != nil {
  749. t.Fatalf("testutils.LocalTCPListener() failed: %v", err)
  750. }
  751. // Call Serve() in a goroutine, and push on a channel when Serve returns.
  752. serveDone := testutils.NewChannel()
  753. go func() {
  754. if err := server.Serve(lis); err != nil {
  755. t.Error(err)
  756. }
  757. serveDone.Send(nil)
  758. }()
  759. // Wait for an xdsClient to be created.
  760. ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
  761. defer cancel()
  762. c, err := clientCh.Receive(ctx)
  763. if err != nil {
  764. t.Fatalf("error when waiting for new xdsClient to be created: %v", err)
  765. }
  766. client := c.(*fakeclient.Client)
  767. // Wait for a listener watch to be registered on the xdsClient.
  768. name, err := client.WaitForWatchListener(ctx)
  769. if err != nil {
  770. t.Fatalf("error when waiting for a ListenerWatch: %v", err)
  771. }
  772. wantName := strings.Replace(testServerListenerResourceNameTemplate, "%s", lis.Addr().String(), -1)
  773. if name != wantName {
  774. t.Fatalf("LDS watch registered for name %q, want %q", name, wantName)
  775. }
  776. // Push an error to the registered listener watch callback and make sure
  777. // that Serve does not return.
  778. client.InvokeWatchListenerCallback(xdsresource.ListenerUpdate{}, errors.New("LDS error"))
  779. sCtx, sCancel := context.WithTimeout(context.Background(), defaultTestShortTimeout)
  780. defer sCancel()
  781. if _, err := serveDone.Receive(sCtx); err != context.DeadlineExceeded {
  782. t.Fatal("Serve() returned after a bad LDS response")
  783. }
  784. // Also make sure that no certificate providers are created.
  785. if err := verifyCertProviderNotCreated(); err != nil {
  786. t.Fatal(err)
  787. }
  788. }
  789. func verifyCertProviderNotCreated() error {
  790. sCtx, sCancel := context.WithTimeout(context.Background(), defaultTestShortTimeout)
  791. defer sCancel()
  792. if _, err := fpb1.buildCh.Receive(sCtx); err != context.DeadlineExceeded {
  793. return errors.New("certificate provider created when no xDS creds were specified")
  794. }
  795. sCtx, sCancel = context.WithTimeout(context.Background(), defaultTestShortTimeout)
  796. defer sCancel()
  797. if _, err := fpb2.buildCh.Receive(sCtx); err != context.DeadlineExceeded {
  798. return errors.New("certificate provider created when no xDS creds were specified")
  799. }
  800. return nil
  801. }