util.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2017 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package grpcproxy
  15. import (
  16. "context"
  17. "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
  18. "google.golang.org/grpc"
  19. "google.golang.org/grpc/metadata"
  20. )
  21. func getAuthTokenFromClient(ctx context.Context) string {
  22. md, ok := metadata.FromIncomingContext(ctx)
  23. if ok {
  24. ts, ok := md[rpctypes.TokenFieldNameGRPC]
  25. if ok {
  26. return ts[0]
  27. }
  28. }
  29. return ""
  30. }
  31. func withClientAuthToken(ctx, ctxWithToken context.Context) context.Context {
  32. token := getAuthTokenFromClient(ctxWithToken)
  33. if token != "" {
  34. ctx = context.WithValue(ctx, rpctypes.TokenFieldNameGRPC, token)
  35. }
  36. return ctx
  37. }
  38. type proxyTokenCredential struct {
  39. token string
  40. }
  41. func (cred *proxyTokenCredential) RequireTransportSecurity() bool {
  42. return false
  43. }
  44. func (cred *proxyTokenCredential) GetRequestMetadata(ctx context.Context, s ...string) (map[string]string, error) {
  45. return map[string]string{
  46. rpctypes.TokenFieldNameGRPC: cred.token,
  47. }, nil
  48. }
  49. func AuthUnaryClientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
  50. token := getAuthTokenFromClient(ctx)
  51. if token != "" {
  52. tokenCred := &proxyTokenCredential{token}
  53. opts = append(opts, grpc.PerRPCCredentials(tokenCred))
  54. }
  55. return invoker(ctx, method, req, reply, cc, opts...)
  56. }
  57. func AuthStreamClientInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
  58. tokenif := ctx.Value(rpctypes.TokenFieldNameGRPC)
  59. if tokenif != nil {
  60. tokenCred := &proxyTokenCredential{tokenif.(string)}
  61. opts = append(opts, grpc.PerRPCCredentials(tokenCred))
  62. }
  63. return streamer(ctx, desc, cc, method, opts...)
  64. }