github.com/blend/go-sdk@v1.20220411.3/grpcutil/client_common_name.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package grpcutil
     9  
    10  import (
    11  	"context"
    12  
    13  	"google.golang.org/grpc/credentials"
    14  	"google.golang.org/grpc/peer"
    15  )
    16  
    17  type peerInfoCommonNameKey struct{}
    18  
    19  // WithClientCommonName adds a client common name to a context as a value.
    20  // This value will supercede parsing the value.
    21  func WithClientCommonName(ctx context.Context, commonName string) context.Context {
    22  	return context.WithValue(ctx, peerInfoCommonNameKey{}, commonName)
    23  }
    24  
    25  // GetClientCommonName fetches the client common name from the context.
    26  func GetClientCommonName(ctx context.Context) (clientCommonName string) {
    27  	if typed, ok := ctx.Value(peerInfoCommonNameKey{}).(string); ok {
    28  		return typed
    29  	}
    30  	if peer, ok := peer.FromContext(ctx); ok {
    31  		if tlsInfo, ok := peer.AuthInfo.(credentials.TLSInfo); ok {
    32  			if len(tlsInfo.State.VerifiedChains) > 0 && len(tlsInfo.State.VerifiedChains[0]) > 0 {
    33  				clientCommonName = tlsInfo.State.VerifiedChains[0][0].Subject.CommonName
    34  			}
    35  		}
    36  	}
    37  	return
    38  }