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