← history for internal/grpc/grpc-tls.go
6ad223b7internal/grpc/grpc-tls.go39 lines⬡ raw↓ download
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package grpc

import (
	"context"
	"crypto/x509"
	"errors"

	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/peer"
)

// For grpc TLS client implementation, see:
// https://medium.com/@mertkimyonsen/securing-grpc-connection-with-ssl-tls-certificate-using-go-db3852fe89dd

func GetClientCN(ctx context.Context) (string, error) {
	peerInfo, ok := peer.FromContext(ctx)
	if !ok {
		return "", errors.New("could not extract common name: missing peer information")
	}

	tlsInfo, ok := peerInfo.AuthInfo.(credentials.TLSInfo)
	if !ok {
		return "", errors.New("could not extract common name: peer is not using TLS")
	}

	certificates := tlsInfo.State.PeerCertificates
	if len(certificates) == 0 {
		return "", errors.New("could not extract common name: missing peer certificate")
	}

	return extractCommonName(certificates), nil
}

func extractCommonName(certificates []*x509.Certificate) string {
	if len(certificates) > 0 {
		return certificates[0].Subject.CommonName
	}
	panic("Could not extract common name")
}