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