local_creds_test.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 test
  19. import (
  20. "context"
  21. "fmt"
  22. "net"
  23. "strings"
  24. "testing"
  25. "time"
  26. "google.golang.org/grpc"
  27. "google.golang.org/grpc/codes"
  28. "google.golang.org/grpc/credentials"
  29. "google.golang.org/grpc/credentials/local"
  30. "google.golang.org/grpc/peer"
  31. "google.golang.org/grpc/status"
  32. testpb "google.golang.org/grpc/test/grpc_testing"
  33. )
  34. func testLocalCredsE2ESucceed(network, address string) error {
  35. ss := &stubServer{
  36. emptyCall: func(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
  37. pr, ok := peer.FromContext(ctx)
  38. if !ok {
  39. return nil, status.Error(codes.DataLoss, "Failed to get peer from ctx")
  40. }
  41. // Check security level
  42. info := pr.AuthInfo.(local.Info)
  43. secLevel := info.CommonAuthInfo.SecurityLevel
  44. switch network {
  45. case "unix":
  46. if secLevel != credentials.PrivacyAndIntegrity {
  47. return nil, status.Errorf(codes.Unauthenticated, "Wrong security level: got %q, want %q", secLevel, credentials.PrivacyAndIntegrity)
  48. }
  49. case "tcp":
  50. if secLevel != credentials.NoSecurity {
  51. return nil, status.Errorf(codes.Unauthenticated, "Wrong security level: got %q, want %q", secLevel, credentials.NoSecurity)
  52. }
  53. }
  54. return &testpb.Empty{}, nil
  55. },
  56. }
  57. sopts := []grpc.ServerOption{grpc.Creds(local.NewCredentials())}
  58. s := grpc.NewServer(sopts...)
  59. defer s.Stop()
  60. testpb.RegisterTestServiceServer(s, ss)
  61. lis, err := net.Listen(network, address)
  62. if err != nil {
  63. return fmt.Errorf("Failed to create listener: %v", err)
  64. }
  65. go s.Serve(lis)
  66. var cc *grpc.ClientConn
  67. lisAddr := lis.Addr().String()
  68. switch network {
  69. case "unix":
  70. cc, err = grpc.Dial(lisAddr, grpc.WithTransportCredentials(local.NewCredentials()), grpc.WithContextDialer(
  71. func(ctx context.Context, addr string) (net.Conn, error) {
  72. return net.Dial("unix", addr)
  73. }))
  74. case "tcp":
  75. cc, err = grpc.Dial(lisAddr, grpc.WithTransportCredentials(local.NewCredentials()))
  76. default:
  77. return fmt.Errorf("unsupported network %q", network)
  78. }
  79. if err != nil {
  80. return fmt.Errorf("Failed to dial server: %v, %v", err, lisAddr)
  81. }
  82. defer cc.Close()
  83. c := testpb.NewTestServiceClient(cc)
  84. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  85. defer cancel()
  86. if _, err = c.EmptyCall(ctx, &testpb.Empty{}); err != nil {
  87. return fmt.Errorf("EmptyCall(_, _) = _, %v; want _, <nil>", err)
  88. }
  89. return nil
  90. }
  91. func (s) TestLocalCredsLocalhost(t *testing.T) {
  92. if err := testLocalCredsE2ESucceed("tcp", "localhost:0"); err != nil {
  93. t.Fatalf("Failed e2e test for localhost: %v", err)
  94. }
  95. }
  96. func (s) TestLocalCredsUDS(t *testing.T) {
  97. addr := fmt.Sprintf("/tmp/grpc_fullstck_test%d", time.Now().UnixNano())
  98. if err := testLocalCredsE2ESucceed("unix", addr); err != nil {
  99. t.Fatalf("Failed e2e test for UDS: %v", err)
  100. }
  101. }
  102. type connWrapper struct {
  103. net.Conn
  104. remote net.Addr
  105. }
  106. func (c connWrapper) RemoteAddr() net.Addr {
  107. return c.remote
  108. }
  109. type lisWrapper struct {
  110. net.Listener
  111. remote net.Addr
  112. }
  113. func spoofListener(l net.Listener, remote net.Addr) net.Listener {
  114. return &lisWrapper{l, remote}
  115. }
  116. func (l *lisWrapper) Accept() (net.Conn, error) {
  117. c, err := l.Listener.Accept()
  118. if err != nil {
  119. return nil, err
  120. }
  121. return connWrapper{c, l.remote}, nil
  122. }
  123. func spoofDialer(addr net.Addr) func(target string, t time.Duration) (net.Conn, error) {
  124. return func(t string, d time.Duration) (net.Conn, error) {
  125. c, err := net.DialTimeout("tcp", t, d)
  126. if err != nil {
  127. return nil, err
  128. }
  129. return connWrapper{c, addr}, nil
  130. }
  131. }
  132. func testLocalCredsE2EFail(dopts []grpc.DialOption) error {
  133. ss := &stubServer{
  134. emptyCall: func(context.Context, *testpb.Empty) (*testpb.Empty, error) {
  135. return &testpb.Empty{}, nil
  136. },
  137. }
  138. sopts := []grpc.ServerOption{grpc.Creds(local.NewCredentials())}
  139. s := grpc.NewServer(sopts...)
  140. defer s.Stop()
  141. testpb.RegisterTestServiceServer(s, ss)
  142. lis, err := net.Listen("tcp", "localhost:0")
  143. if err != nil {
  144. return fmt.Errorf("Failed to create listener: %v", err)
  145. }
  146. var fakeClientAddr, fakeServerAddr net.Addr
  147. fakeClientAddr = &net.IPAddr{
  148. IP: net.ParseIP("10.8.9.10"),
  149. Zone: "",
  150. }
  151. fakeServerAddr = &net.IPAddr{
  152. IP: net.ParseIP("10.8.9.11"),
  153. Zone: "",
  154. }
  155. go s.Serve(spoofListener(lis, fakeClientAddr))
  156. cc, err := grpc.Dial(lis.Addr().String(), append(dopts, grpc.WithDialer(spoofDialer(fakeServerAddr)))...)
  157. if err != nil {
  158. return fmt.Errorf("Failed to dial server: %v, %v", err, lis.Addr().String())
  159. }
  160. defer cc.Close()
  161. c := testpb.NewTestServiceClient(cc)
  162. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  163. defer cancel()
  164. _, err = c.EmptyCall(ctx, &testpb.Empty{})
  165. return err
  166. }
  167. func isExpected(got, want error) bool {
  168. return status.Code(got) == status.Code(want) && strings.Contains(status.Convert(got).Message(), status.Convert(want).Message())
  169. }
  170. func (s) TestLocalCredsClientFail(t *testing.T) {
  171. // Use local creds at client-side which should lead to client-side failure.
  172. opts := []grpc.DialOption{grpc.WithTransportCredentials(local.NewCredentials())}
  173. want := status.Error(codes.Unavailable, "transport: authentication handshake failed: local credentials rejected connection to non-local address")
  174. if err := testLocalCredsE2EFail(opts); !isExpected(err, want) {
  175. t.Fatalf("testLocalCredsE2EFail() = %v; want %v", err, want)
  176. }
  177. }
  178. func (s) TestLocalCredsServerFail(t *testing.T) {
  179. // Use insecure at client-side which should lead to server-side failure.
  180. opts := []grpc.DialOption{grpc.WithInsecure()}
  181. if err := testLocalCredsE2EFail(opts); status.Code(err) != codes.Unavailable {
  182. t.Fatalf("testLocalCredsE2EFail() = %v; want %v", err, codes.Unavailable)
  183. }
  184. }