Open3

GoのgRPCクライアントでTLS証明書の情報を取得する

fujiwarafujiwara

GoのgRPCクライアント("google.golang.org/grpc.ClientConn")でサーバーにアクセスしたときのTLS接続情報(具体的には証明書の有効期限)を取得したい。
(HTTPsの場合、http.Response には TLS *tls.ConnectionState があるのでそこから取れる)

  1. grpc/peer.Peer の変数を作って CallerOption にする。
  2. gRPC呼び出し時に CallerOption を指定する
  3. peer.AuthInfo を credentials.TLSInfo にcastすると https://pkg.go.dev/google.golang.org/grpc/credentials#TLSInfo State tls.ConnectionState があるのでそこから取れる
fujiwarafujiwara
  1. https://github.com/fujiwara/grpchealth/blob/34911ae6e9e6a9eae860dccf131c72be4f3c4830/client.go#L55-L58
  2. https://github.com/fujiwara/grpchealth/blob/34911ae6e9e6a9eae860dccf131c72be4f3c4830/client.go#L60
  3. https://github.com/fujiwara/grpchealth/blob/34911ae6e9e6a9eae860dccf131c72be4f3c4830/client.go#L73-L85
var pe peer.Peer
callerOpts := []grpc.CallOption{
	grpc.Peer(&pe), // 1.
}
resp, err := client.Check(ctx, req, callerOpts...) // 2.
if err != nil {
	return err
}
if pe.AuthInfo != nil {
	if tlsInfo, ok := pe.AuthInfo.(credentials.TLSInfo); ok { // 3.
		if len(tlsInfo.State.PeerCertificates) > 0 {
			cert := tlsInfo.State.PeerCertificates[0]
			slog.Info("Peer certificate information",
				"subject", cert.Subject,
				"issuer", cert.Issuer,
				"notBefore", cert.NotBefore,
				"notAfter", cert.NotAfter,
			)
		}
	}
}