Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 39 ยท Interceptors and Security

TLS and Mutual TLS for gRPC

Secure gRPC with TLS and mutual TLS: certificates, CAs, server and client credentials in Go, and a runnable in-memory mTLS handshake using the standard library.

By default a gRPC channel is just HTTP/2 over a plain TCP connection: anyone on the network path can read and change the messages. Real deployments use TLS (Transport Layer Security) so that the connection is encrypted and the client can be sure it is talking to the real server. Inside a company, services often go one step further with mutual TLS (mTLS), where the server also verifies the client's certificate, so each side proves its identity.

TLS is not specific to gRPC; it is the same technology behind HTTPS. What gRPC adds is a clean way to plug credentials into a server and a client. And, good news for this lesson, Go's standard library contains a complete TLS implementation, so the runnable examples below perform a real mTLS handshake.

The grpc-go library itself is not available on this site, so the gRPC calls are read-only. The TLS parts (certificates, handshake, verification) are real and run on the Go runner using crypto/tls and crypto/x509.

What TLS gives you

  • Confidentiality: messages are encrypted.
  • Integrity: tampering is detected.
  • Server authentication: the server proves it owns a certificate issued by an authority the client trusts, and the certificate matches the name you dialed.
  • Client authentication (mTLS only): the client proves its identity with its own certificate.
sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: ClientHello
    S-->>C: ServerHello + server certificate
    Note over C: verify chain to trusted CA<br/>and check the server name
    S-->>C: CertificateRequest (mTLS only)
    C->>S: client certificate + proof
    Note over S: verify client chain to CA
    C->>S: encrypted HTTP/2 + gRPC calls

The handshake happens once per connection; gRPC then reuses the connection for many calls.

Certificates in a minute

A certificate binds a public key to a name and is signed by a certificate authority (CA). Clients carry a list of CAs they trust. In production you get certificates from a public CA (Let's Encrypt) for internet-facing servers, or from a private CA (an internal PKI, cert-manager, Vault, a service mesh) for service-to-service traffic. For development you can create your own throwaway CA, which is what the next block does.

Server credentials in Go (real API)

Go
creds, err := credentials.NewServerTLSFromFile("server.crt", "server.key")
if err != nil {
    log.Fatal(err)
}
srv := grpc.NewServer(grpc.Creds(creds))

Client credentials in Go (real API)

Go
// Trust the system roots (public CA):
creds := credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12})

// Or trust a private CA:
creds, err := credentials.NewClientTLSFromFile("ca.crt", "")

conn, err := grpc.NewClient("users.internal:443", grpc.WithTransportCredentials(creds))

The second argument of NewClientTLSFromFile overrides the server name used to verify the certificate; leave it empty to use the dialed host. Never replace verification with InsecureSkipVerify: true outside a throwaway test; it removes the whole point of TLS. grpc.WithTransportCredentials(insecure.NewCredentials()) is the explicit opt-out for local development.

mTLS in Go (real API)

Go
cert, _ := tls.LoadX509KeyPair("server.crt", "server.key")
caPEM, _ := os.ReadFile("ca.crt")
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(caPEM)

serverCfg := &tls.Config{
    Certificates: []tls.Certificate{cert},
    ClientAuth:   tls.RequireAndVerifyClientCert,
    ClientCAs:    pool,
    MinVersion:   tls.VersionTLS13,
}
srv := grpc.NewServer(grpc.Creds(credentials.NewTLS(serverCfg)))

A handler can then read who the client is from the connection: peer.FromContext(ctx) gives AuthInfo, a credentials.TLSInfo whose State.PeerCertificates[0].Subject.CommonName (or better, a URI SAN such as a SPIFFE ID) names the caller. An interceptor can turn that into an authorization check.

A real mTLS handshake you can run

This program creates a private CA, issues a server and a client certificate, starts a TLS server on loopback, and connects with and without a client certificate.

Go Mutual TLS with a private CA

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You should see the first connection succeed and all three others rejected: no certificate, a certificate from a CA the server does not trust, and a server name that the server certificate does not cover. Under TLS 1.3 a client can finish its own handshake a moment before the server rejects it, which is why the program reads once from the connection before judging.

Rotation and revocation

Certificates expire, and that is a feature: short lifetimes limit the damage of a leaked key. Plan for rotation from day one. Load certificates through tls.Config.GetCertificate / GetClientCertificate callbacks, or reload files when they change, so a renewal does not need a restart. Revocation (CRLs, OCSP) is awkward in practice; most service meshes rely on very short-lived certificates (hours) instead.

Where TLS is terminated

  • In the service (shown above): simplest, end-to-end encryption.
  • At a proxy or load balancer (Envoy, nginx, cloud LB): the proxy holds the certificates; traffic behind it may be plain or re-encrypted. See load balancing.
  • In a service mesh sidecar: the mesh does mTLS for you, and your code uses plaintext on localhost.

Whatever you choose, gRPC needs HTTP/2, so the proxy must support it end to end (ALPN h2).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does mutual TLS add compared with ordinary TLS?

    In mTLS both sides present and verify certificates, so each proves its identity.
  2. 2. Why is InsecureSkipVerify: true dangerous in production?

    Without verification the client accepts any certificate, defeating server authentication.
  3. 3. In the demo, why does the rogue certificate fail?

    The server's ClientCAs pool contains only demo-ca; a certificate from evil-ca cannot be verified.
  4. 4. What is a good way to limit damage from a leaked private key?

    Short lifetimes shrink the window in which a stolen key is useful, as long as renewal is automated.

Summary

  • TLS encrypts a gRPC channel and authenticates the server; mTLS also authenticates the client.
  • Server side: credentials.NewServerTLSFromFile or credentials.NewTLS(cfg) with grpc.Creds; client side: grpc.WithTransportCredentials.
  • For mTLS set ClientAuth: tls.RequireAndVerifyClientCert and a ClientCAs pool; read the caller from peer.FromContext.
  • Never skip verification in production; use insecure.NewCredentials() only for local development.
  • Prefer short-lived certificates with automatic rotation, and make sure proxies speak HTTP/2.

Next: Token Authentication