Skip to main content

Use ACM Certificate in gRPC Connection

·2 mins

Note: This is the transcription of some notes I took days ago while writing code, so I’m going to keep it really short.

There’s a gRPC server we want to connect to: in order to do so, we need to provide its certificate (stored in AWS Certificate Manager, ACM) to our gRPC client. The first step is to add the relevant modules of the AWS SDK to our project’s dependencies:

go get github.com/aws/aws-sdk-go-v2/config
go get github.com/aws/aws-sdk-go-v2/service/acm

Now (assuming that we already know in which AWS region we’re using ACM and the arn of the certificate itself), we can send a request to ACM using the SDK, as follows:

import (
	"context"
	"crypto/x509"
	"log"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/acm"

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

func main() {
	var arn string     = "arn:..."   // ARN of our certificate
	var region string  = "eu-west-3" // AWS region where our certificate is stored
    var address string = "..."       // URL of the gRPC server

    ctx := context.Background()      // change as needed

	cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region))
	if err != nil {
		log.Fatal(err)
	}
  
	client := acm.NewFromConfig(cfg)
	certificate, err := client.GetCertificate(ctx, &acm.GetCertificateInput{CertificateArn: &arn})
	if err != nil {
		log.Fatal(err)
	}
  
	pool := x509.NewCertPool()
	pool.AppendCertsFromPEM([]byte(*certificate.Certificate))

	creds := credentials.NewClientTLSFromCert(pool, "")
	conn, err := grpc.DialContext(
		ctx,
		address,
		[]grpc.DialOption{
			grpc.WithTransportCredentials(creds),
			// ... any other options we might need
		}...,
	)
	if err != nil {
		log.Fatal(err)
	}

	// use gRPC connection
}