vitess.io/vitess@v0.16.2/go/vt/grpcclient/client_auth_static.go (about) 1 /* 2 Copyright 2019 The Vitess Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package grpcclient 18 19 import ( 20 "context" 21 "encoding/json" 22 "os" 23 24 "google.golang.org/grpc" 25 "google.golang.org/grpc/credentials" 26 ) 27 28 var ( 29 credsFile string // registered as --grpc_auth_static_client_creds in RegisterFlags 30 // StaticAuthClientCreds implements client interface to be able to WithPerRPCCredentials 31 _ credentials.PerRPCCredentials = (*StaticAuthClientCreds)(nil) 32 ) 33 34 // StaticAuthClientCreds holder for client credentials 35 type StaticAuthClientCreds struct { 36 Username string 37 Password string 38 } 39 40 // GetRequestMetadata gets the request metadata as a map from StaticAuthClientCreds 41 func (c *StaticAuthClientCreds) GetRequestMetadata(context.Context, ...string) (map[string]string, error) { 42 return map[string]string{ 43 "username": c.Username, 44 "password": c.Password, 45 }, nil 46 } 47 48 // RequireTransportSecurity indicates whether the credentials requires transport security. 49 // Given that people can use this with or without TLS, at the moment we are not enforcing 50 // transport security 51 func (c *StaticAuthClientCreds) RequireTransportSecurity() bool { 52 return false 53 } 54 55 // AppendStaticAuth optionally appends static auth credentials if provided. 56 func AppendStaticAuth(opts []grpc.DialOption) ([]grpc.DialOption, error) { 57 if credsFile == "" { 58 return opts, nil 59 } 60 data, err := os.ReadFile(credsFile) 61 if err != nil { 62 return nil, err 63 } 64 clientCreds := &StaticAuthClientCreds{} 65 err = json.Unmarshal(data, clientCreds) 66 if err != nil { 67 return nil, err 68 } 69 creds := grpc.WithPerRPCCredentials(clientCreds) 70 opts = append(opts, creds) 71 return opts, nil 72 } 73 74 func init() { 75 RegisterGRPCDialOptions(AppendStaticAuth) 76 }