Mutual TLS & Securing Service-to-Service Traffic
"No inherent mutual trust between services: Only authenticated, trusted, and specifically authorized callers or services can access any other service." — Google Cloud, BeyondProd, cloud.google.com/docs/security/beyondprod
Summary: Inside a system, "it came from our network" is not proof of anything. Mutual TLS (mTLS) gives every service a certificate that names it, makes both sides of a connection prove who they are before a byte of application data flows, and turns the certificate into the input for an authorization decision. Focus: Lateral movement and why network location is not identity, mutual TLS and client certificates, the SPIFFE ID in a URI SAN as service identity, a private CA with intermediates and a trust bundle, short-lived certificates and rotation without downtime (hot reload, dual trust), SPIFFE and SPIRE (SVIDs, workload attestation, trust domains, federation), service mesh mTLS (Istio PeerAuthentication STRICT and PERMISSIVE, Linkerd identity, Consul Connect, sidecar and ambient), service tokens with an audience, OAuth client credentials, SigV4 and HMAC request signing, API keys and IP allowlists as weak controls, AuthorizationPolicy and OPA, partner mTLS at the edge with CRL and OCSP, handshake cost and session resumption, certificate expiry outages and clock skew, openssl s_client, PostgreSQL clientcert=verify-full, Kafka SSL client auth, RabbitMQ EXTERNAL, cert-manager, the Kubernetes CSR API, gRPC credentials. Learning goal: For a system of services, decide where mTLS is terminated and who issues certificates, choose identities and lifetimes, write the Go and Laravel code that verifies the peer and checks its identity against a policy, rotate leaves and the CA without an outage, and debug a failed handshake from the command line.
This chapter sits in the Security group, after Authorization: RBAC, ABAC & Zero Trust and Cryptography, TLS, PKI & Secrets (PKI design and secret storage live there; this page only uses them) and before Secure SDLC & Incident Response. The bytes of the TLS handshake, certificate chains, SNI and local certificates are in TLS in Practice; the mesh itself is in Service Mesh & Sidecar Architecture; tokens are in JWT Deep Dive and OAuth 2.0, OIDC & SSO; broker credentials are in Messaging Security; and the Go HTTP/2 and TLS mechanics are in HTTP/2, HTTPS, TLS & mTLS in Go.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why a private network is not a security boundary | Why it exists |
| Where mTLS, SPIFFE and BeyondProd come from | Where it comes from |
| What an attacker does with one compromised pod | Lateral movement |
| Both sides prove who they are | Mutual TLS |
| What goes in the certificate: SAN, URI SAN, SPIFFE ID | Service identity |
| Root, intermediate, trust bundle | A private CA |
| Why lifetimes of minutes beat revocation | Short-lived certificates |
| Changing the CA without an outage | Dual trust |
| SVIDs, attestation, trust domains, federation | SPIFFE and SPIRE |
| Istio, Linkerd, Consul, sidecar, ambient | Service mesh mTLS |
| JWTs, client credentials, SigV4, HMAC, API keys, IP allowlists | Alternatives and complements |
| Identity to policy: AuthorizationPolicy, OPA | Authorization for services |
| Partners and B2B client certificates | mTLS at the edge |
| PostgreSQL, Redis, Kafka, RabbitMQ | Databases and queues |
| cert-manager, CSR API, Secrets | Kubernetes |
| gRPC channel and call credentials | gRPC credentials |
| Handshake cost, resumption, offload | Performance |
| Expiry outages, clock skew | Operational failures |
| BeyondProd and zero trust | Zero trust for services |
openssl s_client and the error messages | Debugging |
| Exact knobs and messages | Mechanics |
| Code | Go, Laravel |
| Classic failures and their fixes | Solving the classic problems |
| Which control for which situation | Choosing |
| Monolith to distributed system | In architecture |
| Commands and measured numbers | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The four questions every service-to-service call must answer.
| Question | Control that answers it | Weak answer | Strong answer |
|---|---|---|---|
| Is anyone listening on the wire? | Encryption in transit | Plain HTTP inside the VPC | TLS 1.3 between every pair of services |
| Is this really the server I meant to call? | Server certificate verification | Skip verification (InsecureSkipVerify, verify => false) | Verify the chain against a private trust bundle and check the server identity |
| Who is calling me? | Client certificate (mTLS), or a service token | Source IP, a shared API key | A certificate whose URI SAN is a SPIFFE ID, or a signed token with an audience |
| May that caller do this? | Authorization policy | "Anyone inside the network may" | Policy on caller identity, method and path (AuthorizationPolicy, OPA, application rules) |
mTLS in five lines.
| Step | What happens | Who does it |
|---|---|---|
| 1 | Each workload gets a key pair and a short-lived certificate naming it | Issuer (cert-manager, SPIRE, mesh CA, Vault) |
| 2 | Server sends its chain and asks for a client certificate | TLS 1.3 CertificateRequest |
| 3 | Client sends its chain and proves it holds the key | Certificate and CertificateVerify |
| 4 | Both verify the chain against the trust bundle and read the identity | tls.Config, Envoy, sidecar |
| 5 | A policy maps identity to allowed operations | AuthorizationPolicy, middleware, OPA |
Where mTLS can live, from least to most automatic.
| Layer | Example | You write | You operate | Typical lifetime of a leaf |
|---|---|---|---|---|
| In the application | Go tls.Config, Laravel Guzzle options | TLS and verification code | Cert files, reload | Hours to days |
| Next to the application | Envoy or NGINX sidecar you configure | Proxy config | Proxy plus cert agent | Hours |
| Service mesh sidecar | Istio, Linkerd, Consul Connect | Policy only | The mesh control plane | 24 hours by default in Linkerd |
| Ambient or node level | Istio ambient ztunnel | Policy only | The mesh, per node | Hours to a day |
| Platform identity | SPIFFE and SPIRE under any of the above | Registration entries | SPIRE servers and agents | 1 hour X.509-SVID by default in SPIRE |
Controls that look like security and are not enough.
| Control | What it really proves | Why it is weak |
|---|---|---|
| IP allowlist | The packet arrived from an address | Addresses are shared, reused, spoofable inside a flat network, and change on every deploy |
| Shared API key | The caller knows a string | No identity, no expiry, leaked in logs and repos, same key on every caller |
| Network segment ("it is in the private subnet") | The caller is somewhere in the subnet | One compromised pod is inside the subnet too |
| Hostname check only | The server's name matches | Says nothing about the client; DNS is not authentication |
Why it exists
For years a service-to-service call inside the data centre was trusted because of where it came from. The firewall was the wall, everything inside it was "us". That model fails the first time one process is compromised: a vulnerable image, a stolen token, a malicious dependency. The attacker is then inside the wall, and every internal service that trusts "anything from inside" trusts the attacker too. Moving sideways from the first foothold to more valuable systems is called lateral movement, and flat internal trust is what makes it cheap.
The cure has two halves. Authentication says who is calling in a way that cannot be forged from the network position alone. Authorization says what that caller may do. mTLS is the most widely deployed answer to the first half, because TLS is already everywhere, the proof is cryptographic, and the identity travels with the connection instead of being a header an attacker can add.
| Trust the network | Trust a verified identity |
|---|---|
| Cheap: no certificates, no policy | Needs an issuer, rotation and policy |
| One compromised pod reaches everything | A compromised pod reaches only what its identity allows |
| Identity is an IP address that changes on every deploy | Identity is a name that follows the workload |
| Audit logs say "10.0.3.17 called" | Audit logs say "billing called orders" |
| Works with nothing and fails silently | Fails loudly (handshake errors) and needs monitoring |
An everyday picture. A building with a guard at the street door and open offices inside is the network-perimeter model: anyone who walks past the guard can open any office. mTLS is a badge reader on every office door that reads your badge (authentication) and checks a list (authorization). The badges expire after a few hours, so a lost one stops working by itself.
Three common misunderstandings, up front
- "mTLS is just TLS with an extra flag." The flag is the easy part. The hard parts are the identity naming scheme, the issuer, rotation, the trust bundle and the policy. A cluster with
ClientAuth: RequireAnyClientCertand no policy accepts any certificate from any CA. - "Encrypted means authenticated." One-way TLS authenticates the server to the client only. The server still has no idea who the client is.
- "The mesh made us secure." A mesh gives you encryption, identity and a place to write policy. Until you write policy (and move from PERMISSIVE to STRICT), traffic is merely better wrapped.
Where it comes from
- TLS client authentication has been in the protocol since SSL 3.0. In TLS 1.3 (RFC 8446) the server asks with a
CertificateRequest, the client answers withCertificateandCertificateVerify, and because the handshake afterServerHellois encrypted, the client certificate is no longer visible to a passive observer as it was in TLS 1.2. Post-handshake client authentication also exists (thepost_handshake_authextension, section 4.2.6 of RFC 8446), which lets a server ask for a certificate after the connection is up; most service-to-service stacks ask in the first handshake and never use it. - X.509 and the certificate profile are in RFC 5280: Subject Alternative Name (section 4.2.1.6), key usage, extended key usage, basic constraints with path length, name constraints, and CRLs.
- Google's internal model is described in BeyondProd: no perimeter reliance, services authenticate each other with Application Layer Transport Security (ALTS), identities are bound to services rather than hosts, and code provenance backs the identity.
- SPIFFE (Secure Production Identity Framework for Everyone) standardised the identity name, the documents that carry it (SVIDs) and the Workload API; SPIRE is its reference implementation. Istio, Linkerd and Consul Connect all converged on short-lived certificates bound to a workload identity; Consul's documentation says its service mesh certificates comply with the SPIFFE X.509 standard.
- Ambient mesh (Istio) moved the L4 mTLS job out of per-pod sidecars into a per-node component (ztunnel), keeping L7 policy in optional waypoint proxies.
The concept catalogue
Network location is not identity: lateral movement Must-know
In plain words: If a service believes a request because of the address it came from, then anything that can send from that address, or from anywhere the firewall also allows, is believed.
Common misunderstanding: "Our services are in a private VPC and a Kubernetes cluster, so the traffic is already protected." Private means unreachable from the internet. It says nothing about the other 400 pods in the same cluster, a compromised CI runner with network access, a sidecar with a vulnerable library, or a leaked kubeconfig that can start a pod.
Definition: Lateral movement is an attacker's step from an already compromised system to another one inside the same network. The defence is to make every hop prove an identity and to allow only the hops the system needs (least privilege between services).
1 attacker exploits a deserialisation bug in "reports" (public-facing, low value)
2 reports can open TCP connections to every service in the cluster
3 reports -> orders: GET /orders?customer=* (orders trusts "anything from inside")
4 reports -> payments: POST /refunds (payments trusts "anything from inside")
5 with mTLS + policy: reports has certificate spiffe://shop.example/ns/prod/sa/reports
6 orders and payments allow only billing and checkout; steps 3 and 4 end in a failed handshake or 403Real scenarios: an SSRF in an image-resizing service that reaches the metadata service and the internal admin API; a leaked read-only token that happens to be accepted by every internal endpoint; a test namespace sharing a flat network with production; a vendor agent running in the cluster.
| Control | Stops lateral movement? | Notes |
|---|---|---|
| Firewalls and Kubernetes NetworkPolicy | Partly | Allow lists by label or CIDR; coarse, no identity; see Firewalls |
| mTLS with identity policy | Yes, per call | Needs issuer, rotation and policy |
| Service tokens with audience | Yes, per call | Replayable if stolen; short expiry and sender-constraint help |
| API key per caller | Weakly | Static, leaks, no rotation story |
Mutual TLS Must-know
In plain words: In normal TLS the client checks the server's certificate. In mutual TLS the server also demands a certificate and checks it, so both ends know who the other is before any request is read.
Common misunderstanding: "Once the handshake succeeds the connection is trusted for everything." The handshake proves a certificate chains to a trusted CA and that the peer holds its key. It does not say the caller may call this method. That is authorization, a separate step.
Definition: Mutual TLS is TLS in which the server sends a certificate request and the client authenticates with an X.509 certificate and a signature over the handshake transcript. Verification on each side has four parts: the chain leads to a trusted root, every certificate is within its validity period, the key usage and extended key usage fit the role (serverAuth for servers, clientAuth for clients), and the identity in the certificate is acceptable to the local policy.
client (billing) server (orders)
1 ClientHello (key_share, signature_algorithms) ------------------>
2 <------------- ServerHello, EncryptedExtensions, CertificateRequest,
Certificate (orders chain), CertificateVerify, Finished
3 verify chain to trust bundle, usage serverAuth, SPIFFE ID of orders
4 Certificate (billing chain), CertificateVerify, Finished ------->
5 verify chain, usage clientAuth, SPIFFE ID of billing
6 application data (HTTP/2 or gRPC) <============================>Real scenarios: two Go services behind no mesh using tls.Config; Envoy sidecars in Istio; a payment processor accepting only client certificates from your data centre; PostgreSQL accepting only application servers that hold a certificate.
| Product | How it requires the client certificate | Setting |
|---|---|---|
Go crypto/tls server | Fails the handshake without a verifiable client certificate | ClientAuth: tls.RequireAndVerifyClientCert plus ClientCAs |
NGINX (ngx_http_ssl_module) | Verifies against a CA file and exposes the result in variables | ssl_verify_client on; ssl_client_certificate ca.pem; |
| Envoy | Requires a client certificate in the downstream TLS context | require_client_certificate: true with a validation context |
| Istio | Sidecar enforces it per workload, namespace or mesh | PeerAuthentication mode: STRICT |
| PostgreSQL | Requests a client certificate on hostssl lines | clientcert=verify-ca or clientcert=verify-full in pg_hba.conf |
| RabbitMQ | Rejects connections without a certificate | ssl_options.verify = verify_peer, ssl_options.fail_if_no_peer_cert = true |
| Kafka broker | Requests a client certificate | ssl.client.auth=required |
Fix / how to use it: in your own code the pattern is a server config with RequireAndVerifyClientCert, a client config that verifies the server chain, and an identity check on both sides (see Go). In a mesh you declare STRICT and the sidecar does the same.
Service identity: SAN, URI SAN and the SPIFFE ID Must-know
In plain words: A certificate names its owner in a field called Subject Alternative Name (SAN). For services the useful name is not a host name but a stable workload name such as spiffe://shop.example/ns/prod/sa/orders, stored as a URI SAN.
Common misunderstanding: "The Common Name (CN) is the identity." CN is legacy, free text and ignored by modern TLS clients for host names; RFC 5280 puts names in the SAN extension. Certificates for services should carry the identity in a SAN and leave the subject empty or generic.
Definition: a SAN entry can be a DNS name, an IP address, an e-mail address or a URI. A SPIFFE ID is a URI of the form spiffe://trust-domain/path. The SPIFFE X.509-SVID standard states: "An X.509 SVID MUST contain exactly one URI SAN, and by extension, exactly one SPIFFE ID." A verifier therefore does two checks beyond the chain: exactly one URI SAN with the spiffe scheme and a trust domain, and the whole ID is on its allow list.
| Identity kind | Example | Good for | Weakness |
|---|---|---|---|
| DNS SAN | orders.internal.example | Clients that verify a host name they dialed | Names the address, not the workload; shared by every replica and by whatever answers that name |
| IP SAN | 10.0.3.17 | Almost nothing in dynamic environments | Changes on every reschedule |
| URI SAN (SPIFFE ID) | spiffe://shop.example/ns/prod/sa/orders | Service-to-service identity in policy | Needs an issuer that assigns it correctly |
| Subject CN or O | CN=orders | Legacy systems (PostgreSQL cert auth maps the CN, RabbitMQ can use the CN) | Free text, no standard structure |
| Istio principal | cluster.local/ns/default/sa/sleep | AuthorizationPolicy principals | The Kubernetes ServiceAccount is the unit of identity |
A good naming scheme answers: which trust domain (organisation or environment), which namespace or team, which service. It should be derived from something the platform controls (a Kubernetes ServiceAccount, a cloud IAM role), not something the workload claims. A pod that can pick its own SPIFFE ID can be anyone.
Real scenarios: a staging service carrying the production trust domain by mistake; two teams both using sa/default; a policy written on *.internal.example that also matches an attacker-controlled name in an old DNS zone.
A private CA: root, intermediate and the trust bundle Must-know
In plain words: The certificates for internal services are issued by your own certificate authority, not by a public one. Services trust a short list of root certificates (the trust bundle), and everything signed under them is accepted.
Common misunderstanding: "We can reuse the public CA bundle of the operating system, or the Let's Encrypt chain, for internal mTLS." A public root trusts every certificate any customer of that CA can obtain. Internal clients should trust only your own roots, otherwise anyone who can get a public certificate for any name can pass the chain check.
Definition: A private PKI has a root CA whose key is kept offline, one or more intermediate CAs that are online and issue leaf certificates, and workloads that receive a leaf (and the intermediates, sent as part of the chain) and a trust bundle containing the root certificates they accept. The path-length constraint (pathLenConstraint, Go MaxPathLen) stops an intermediate from creating further CAs. The trust bundle holds roots, not leaves, and not intermediates (intermediates travel with the leaf).
| Choice | Option A | Option B | Prefer |
|---|---|---|---|
| Root key | Online, on the issuer | Offline, in an HSM or cold storage | Offline; the root signs the intermediate once a year |
| Number of CAs | One CA for everything | One intermediate per environment or cluster | Per environment, so a leak in staging does not trust production |
| Key type | RSA 2048 | ECDSA P-256 | ECDSA P-256 for leaves (smaller, faster handshakes), as in the lab code |
| Leaf key location | Issuer generates and ships the key | Workload generates a key and sends a CSR | The workload generates it; the key never leaves the pod |
| Name constraints | None | Intermediate limited to the trust domain | Constrain where the issuing software supports it |
For the design of PKI itself (CA hierarchies, HSMs, ceremonies) see Cryptography, TLS, PKI & Secrets; for what a chain looks like on the wire see TLS in Practice.
Short-lived certificates and rotation Must-know
In plain words: Instead of building a system that can un-trust a stolen certificate, issue certificates that die by themselves in minutes or hours and renew them automatically before they do.
Common misunderstanding: "Short lifetimes mean outages every few hours." A renewal that happens at half-life, run by an agent, is routine. What causes outages is a long lifetime that nobody renews until the day it expires (the thing short lifetimes are designed to prevent by making renewal a daily habit).
Definition: Revocation (CRL, RFC 5280 section 5; OCSP) relies on every verifier fetching and honouring revocation data. For internal traffic most platforms choose expiry instead of revocation: if a leaf lives for one hour, a stolen key is useful for at most one hour. The cost is an issuer that must be highly available and a workload agent that renews well before expiry.
| Product | Default leaf lifetime | Renewal | Source of the number |
|---|---|---|---|
| SPIRE | X.509-SVID 1 h (default_x509_svid_ttl), JWT-SVID 5 m, CA signing key 24 h (ca_ttl) | Agent renews through the Workload API | SPIRE server configuration reference |
| Linkerd | 24 h, bound to the pod's ServiceAccount | Automatic by the proxy | Linkerd automatic mTLS docs |
| cert-manager | duration 2160 h (90 days) in the documented example, renewBefore 360 h | Controller renews | cert-manager Certificate docs |
| Kubernetes CSR API | Request via spec.expirationSeconds, minimum 600 s | You re-submit before expiry | Kubernetes CSR docs |
| Istio | Workload certificates rotated by the Istio agent through SDS | Automatic | Istio security concepts |
t=0 issue leaf, TTL 60 min
t=30 agent renews (half-life): new key, new certificate, new connections use it
t=30..60 old certificate still valid, in-flight connections continue
t=60 old certificate expires; if no renewal succeeded there is a 100% outage for this workload
=> alert on "certificate expires in < 25% of TTL", not on "expired"Fix / how to use it: renew at half the lifetime; alert when remaining life is below a quarter; load the new certificate for new handshakes without restarting (see Hot reload); never put a leaf into an image or a long-lived Secret that no agent rewrites.
Dual trust: rotating the CA itself without downtime Must-know
In plain words: To change the CA, first teach everyone to trust the new CA while still trusting the old one, then start issuing from the new one, and only then remove the old one.
Common misunderstanding: "Rotating the CA is the same as rotating a leaf: replace the file and restart." Leaves are verified by every peer against its own trust bundle. If you start issuing from a CA that some peers do not trust yet, those peers reject the new leaves; if you remove the old root while leaves signed by it are still live, they are rejected too.
Definition: Dual trust (also called an overlapping trust bundle) is a trust bundle that contains both the old and the new root during a migration window.
phase 1 bundle = {old root} leaves from old everything works
phase 2 bundle = {old root, new root} leaves from old distribute; verify EVERY workload has the new bundle
phase 3 bundle = {old root, new root} leaves from new renewals switch issuers naturally within one TTL
phase 4 bundle = {new root} leaves from new remove the old root only after one TTL + margin| Mistake | Symptom | Prevention |
|---|---|---|
| Issue from the new CA before every bundle has the new root | x509: certificate signed by unknown authority from some peers only | Phase 2 must be verified (metrics: bundle hash per workload) |
| Remove the old root immediately | Workloads that have not renewed yet fail with unknown certificate authority | Wait one leaf TTL plus a margin |
| Bundle delivered by a different path than the leaves | Leaves renewed, bundle stale for hours | Ship bundle and leaf together (same agent, same volume) |
| Trust anchor with a long, forgotten lifetime | Outage on its expiry day | Track anchor expiry; Linkerd's default anchor lives 365 days and must be rotated manually |
In the Go code of this page Store.Set(cert, roots) takes the certificate and the bundle together, and a test (TestDualTrustRotationOfTheCA) runs the four phases.
SPIFFE and SPIRE Important
In plain words: SPIFFE is a standard for naming a workload and handing it a verifiable identity document. SPIRE is software that checks that a workload is what it claims to be and then issues that document.
Common misunderstanding: "SPIRE is a service mesh." SPIRE issues identities. Meshes (Istio can use SPIRE as its CA), proxies and your own code consume them.
Definition:
| Term | Meaning |
|---|---|
| SPIFFE ID | spiffe://trust-domain/path, the name of a workload |
| Trust domain | The root of trust and the namespace for IDs; usually one organisation or environment; the spiffe:// host part |
| SVID (SPIFFE Verifiable Identity Document) | The proof of an ID: an X.509-SVID (a certificate with the ID as the single URI SAN) or a JWT-SVID (a signed JWT with sub = the ID and an aud) |
| Workload API | A local API (gRPC over a Unix socket) from which a workload fetches its SVIDs, rotating bundles and keys without credentials of its own |
| Trust bundle | The set of root certificates (X.509 authorities) and JWT keys for a trust domain |
| Node attestation | The SPIRE agent proves what machine it runs on (cloud instance identity document, TPM, join token) and gets an agent SVID |
| Workload attestation | The agent identifies a calling process by selectors (Kubernetes namespace and ServiceAccount, Unix UID, container image) and matches them to a registration entry |
| Federation | Two trust domains exchange their trust bundles so that workloads in each can verify SVIDs from the other |
The SPIRE concepts page describes node attestation as the agent's way to prove the node's identity, so that it receives a SPIFFE ID that then serves as the “parent” of the workloads it is in charge of. Defaults in the server configuration reference: default_x509_svid_ttl is 1 h, default_jwt_svid_ttl is 5 m, ca_ttl is 24 h.
1 workload (pod) opens the Workload API socket (no secret needed)
2 SPIRE agent identifies the caller from the kernel: pid -> k8s pod -> namespace + serviceaccount
3 agent matches selectors to a registration entry: k8s:ns:prod + k8s:sa:orders -> spiffe://shop.example/ns/prod/sa/orders
4 agent returns an X.509-SVID (1 h) and the trust bundle; keeps the stream open
5 before expiry the agent pushes a new SVID on the same stream; the workload swaps it (hot reload)| X.509-SVID vs JWT-SVID | X.509-SVID | JWT-SVID |
|---|---|---|
| Carried by | TLS handshake | Authorization: Bearer header or gRPC metadata |
| Proof of possession | Yes, the handshake signs with the key | No, a bearer token: whoever holds it can replay it until it expires |
| Audience | Not applicable | Required aud claim; the verifier must check it |
| Works through an L7 proxy that terminates TLS | No, identity ends at the proxy | Yes |
| Default lifetime in SPIRE | 1 h | 5 m |
Federation lets spiffe://shop.example/... and spiffe://partner.example/... trust each other without sharing a root: each side publishes its bundle at a bundle endpoint (HTTPS with a SPIFFE-authenticated or web PKI endpoint) and refreshes it. The SPIFFE bundle specification notes that sharing a root key between trust domains degrades isolation, so use federation rather than a shared CA.
Service mesh mTLS Must-know
In plain words: A service mesh puts a proxy next to every service (or one per node) that does the mTLS for it. The application speaks plain HTTP to its local proxy; the proxies speak mTLS to each other and enforce policy.
Common misunderstanding: "With a mesh, traffic is encrypted everywhere." Only between meshed workloads, only when the policy says so, and not on the pod-local hop between the app and its proxy. Calls to a database outside the mesh, to a node-port, or to a pod without a sidecar stay as they were unless you configure them.
Definition: The mesh control plane acts as a CA (istiod, Linkerd's identity controller, Consul servers), issues a short-lived certificate per workload identity (the Kubernetes ServiceAccount in Istio and Linkerd), and pushes policy. The data plane proxies terminate mTLS and apply policy.
| Mesh | Identity unit | Cert lifetime | mTLS default | Policy objects | Data plane |
|---|---|---|---|---|---|
| Istio sidecar mode | ServiceAccount, principal cluster.local/ns/NS/sa/NAME | Rotated by the Istio agent via Envoy SDS | Auto mTLS between sidecars; PERMISSIVE accepts plaintext too | PeerAuthentication, AuthorizationPolicy, RequestAuthentication | Envoy sidecar per pod |
| Istio ambient mode | Same | Same | ztunnel provides L4 mTLS ("the ztunnel secure overlay handles routing and zero trust security for traffic") | AuthorizationPolicy at L4 on ztunnel, L7 on waypoint | ztunnel per node, optional waypoint proxy per namespace or service |
| Linkerd | ServiceAccount of the pod | 24 h, automatic | mTLS on by default for meshed TCP traffic | Server, AuthorizationPolicy, MeshTLSAuthentication | linkerd2-proxy sidecar |
| Consul Connect (Consul service mesh) | Service name, SPIFFE-compliant certificates | Rotated by Consul | mTLS "is the core"; intentions authorize | Service intentions (allow/deny per source and destination) | Envoy sidecar or gateway |
Istio PeerAuthentication modes:
| Mode | Behaviour | Use |
|---|---|---|
UNSET | Inherit from parent (namespace, then mesh) | Default |
DISABLE | No tunnel; plaintext | Ports that must stay plain (a probe, a legacy client) |
PERMISSIVE | Accept both mTLS and plaintext | Migration state while clients get sidecars |
STRICT | Only mTLS | Target state |
The Istio reference shows a namespace policy mtls: mode: STRICT, a per-workload override and a portLevelMtls entry that turns mTLS off for one port. A mesh-wide policy goes into the root namespace, and policies with workload selectors are ignored there.
apiVersion: security.istio.io/v1
kind: PeerAuthentication
metadata:
name: default
namespace: prod
spec:
mtls:
mode: STRICT
---
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata:
name: orders-from-billing
namespace: prod
spec:
selector:
matchLabels:
app: orders
action: ALLOW
rules:
- from:
- source:
principals: ["cluster.local/ns/prod/sa/billing"]
to:
- operation:
methods: ["GET"]
paths: ["/orders*"]| Sidecar | Ambient |
|---|---|
| Proxy per pod; adds CPU and memory per pod and a restart on proxy upgrade | ztunnel per node; the pod needs no change |
| L7 features everywhere | L4 by default; add a waypoint for L7 |
| Mature, widest feature set | Newer; the Istio documentation says sidecar and ambient pods can co-exist in one mesh |
| Per-pod certificate in the sidecar's memory | Node component holds identities for pods on that node, so a node compromise exposes more identities |
Linkerd's documentation says the control plane's identity component issues certificates to each proxy, "bound to the Kubernetes ServiceAccount identity of the containing pod", that they "expire after 24 hours and are automatically rotated", and that the trust anchor generated by the default install "expires after 365 days" and "must be manually rotated". That last sentence is the typical mesh outage waiting to happen. See Service Mesh & Sidecar Architecture and API Gateway, BFF & Service Mesh for the architecture trade-offs.
Alternatives and complements: tokens, signed requests, keys Important
In plain words: Not every hop can use mTLS (a message through a queue, a call through a CDN, a request that crosses an L7 proxy that terminates TLS). Then identity travels in the request: a signed token, a signature over the request, or a key.
Common misunderstanding: "A JWT is a replacement for mTLS." A bearer token proves possession of a string, not of a private key; stolen once, it works from anywhere until it expires. A token proves which service and for which audience, mTLS proves this connection. They compose: mTLS between hops, a token for the end-to-end claim.
| Mechanism | What it proves | Replay / theft | Typical use | Weakness |
|---|---|---|---|---|
| mTLS client certificate | Peer holds the private key for an identity certified by your CA | Needs the key; stolen cert without key is useless | Hop-to-hop | Terminates at the first proxy that terminates TLS |
| Service token (JWT) with audience | A trusted issuer vouched that subject S may call audience A until exp | Bearer: replayable until expiry | Across proxies, queues, async hops | Must verify signature, iss, aud, exp; short TTL |
| OAuth 2.0 client credentials grant (RFC 6749 section 4.4) | Client authenticated to the authorization server and got a scoped token | Same as JWT | Service to API behind an STS | Client secret management; use private_key_jwt or mTLS client authentication (RFC 8705) instead of a shared secret |
| Certificate-bound tokens (RFC 8705) | Token is only usable with the client certificate it was issued for | Stolen token is useless without the key | High-value APIs | More plumbing |
| Request signing, AWS SigV4 | The request (method, path, headers, payload hash) was signed with a key derived from a secret; signature includes a timestamp | Replay limited by timestamp window | AWS APIs, your own signed webhooks | Both sides need the secret (HMAC) |
| HMAC signature (shared secret) | The sender knows the shared secret and the body was not altered | Replay unless nonce/timestamp | Webhooks (for example X-Signature) | Shared secret on both sides; no per-caller identity unless one secret per caller |
| API key | The caller knows the key | Static: valid forever until rotated | Public APIs for rate limiting and billing | Not an identity; leaks in logs and repos; see below |
| IP allowlist | The packet's source address | Spoofable inside the network, shared NAT | Defense in depth for third parties | Weakest control; address is not identity |
API keys and their weaknesses: a key identifies a project for quota and billing; it is not authentication of a service. It has no expiry by default, appears in URLs and logs, is shared by every instance, and tells you nothing about who used it. If you must use one, send it in a header (never a query string), hash it at rest, support two active keys per caller for rotation, and add a second factor (mTLS or a signature).
IP allowlists are a useful extra layer against the wrong network (a partner's egress range) and a poor primary control. Addresses change with deploys and failovers, NAT merges many callers into one address, and inside a flat network the source address is as spoofable as the attacker's position.
For token structure and verification rules see JWT Deep Dive; for how tokens are minted see OAuth 2.0, OIDC & SSO. AWS describes SigV4 as the process for signing requests with credentials and notes it applies when you call the API without an SDK; the SDKs do the signing for you.
Authorization for services: from identity to policy Must-know
In plain words: Authentication tells you the caller is billing. Authorization is the rule "billing may GET /orders but not DELETE".
Common misunderstanding: "If the handshake succeeded, the caller is trusted." A valid certificate from your own CA only means some workload of yours is calling. reports has one too.
Definition: Service authorization maps the authenticated service identity (and optionally method, path, request claims and the end user) to allow or deny. It can run in the mesh (Istio AuthorizationPolicy, Consul intentions, Linkerd AuthorizationPolicy), in a policy engine (OPA/Rego, Cedar), or in application code. Default to deny and add allow rules.
| Where | Example | Strength | Limit |
|---|---|---|---|
| Mesh policy | Istio AuthorizationPolicy with action: ALLOW, from.source.principals, to.operation.methods/paths, when conditions on JWT claims | Uniform, no code, audited as config | Sees only what the proxy sees; business rules are out of reach |
| Policy engine (OPA) | Envoy ext_authz calling OPA, or a library decision allow if input.caller == "billing" and input.method == "GET" | Rich logic, one language, testable | Another hop and component to keep available; decision caching |
| Application middleware | The Go Authorize middleware and Laravel RequireServiceIdentity in this chapter | Knows the business object | Easy to forget on a new route |
| Database or broker ACL | PostgreSQL role mapped from the client certificate; Kafka ACLs on the principal | Last line of defence | Coarse |
Authorization of end users (the person on whose behalf billing calls orders) is a second identity layered on top: pass a user token, not the user's name in a header. See Authorization: RBAC, ABAC & Zero Trust.
mTLS at the edge: partners and B2B Important
In plain words: A bank or a logistics partner often must call you with a certificate you gave them (or one from a CA you both accepted). The load balancer checks the certificate at the edge and tells the backend who it was.
Common misunderstanding: "The load balancer verified the certificate, so the app can trust the X-Client-Cert header." Only if the proxy strips any incoming copy of that header and nothing else can reach the app. Otherwise the caller writes the header itself.
Definition: Edge mTLS is client-certificate authentication on a public or partner-facing listener, with a dedicated CA for partners (not the internal CA), a CRL or OCSP check, and an identity mapping from certificate fields to a partner account.
| Edge | How client certificates are enabled | How the backend learns the identity |
|---|---|---|
| NGINX | ssl_verify_client on; ssl_client_certificate partners-ca.pem; ssl_crl crl.pem; | proxy_set_header X-Client-DN $ssl_client_s_dn; and $ssl_client_verify |
| Envoy | Downstream TLS context with require_client_certificate: true and a validation context | The x-forwarded-client-cert (XFCC) header: Envoy documentation says a proxy "may choose to sanitize/append/forward" it, controlled by forward_client_cert_details |
| HAProxy | bind :443 ssl crt site.pem ca-file partners-ca.pem verify required crl-file crl.pem | ssl_c_s_dn, ssl_c_verify fetched into headers |
| AWS ALB | mTLS verify mode with a trust store (and optional CRL) | X-Amzn-Mtls-Clientcert-* headers |
| AWS API Gateway | Custom domain with a truststore in S3 | Request context identity fields |
| Cloudflare | API Shield mTLS with client certificates | Cloudflare adds certificate fields to the request |
Revocation matters more here than inside because partner certificates live for a year or more and the partner's key handling is outside your control. A CRL is a signed list of revoked serial numbers published by the CA (RFC 5280 section 5); OCSP asks the CA about one certificate. Both fail open or closed by configuration, so decide which on purpose: a partner API that fails open when the CRL endpoint is down defeats revocation.
1 partner connects to api.shop.example:443, offers client certificate (chain: partner leaf, partner issuing CA)
2 edge verifies: chain to partner-CA bundle, validity, clientAuth, CRL says not revoked
3 edge maps subject serial / SAN to partner id "acme-logistics"; strips any inbound X-Client-* headers
4 edge forwards: X-Partner-Id: acme-logistics (signed or over an mTLS hop to the backend)
5 backend applies per-partner policy and rate limits (see rate limiting chapter)Databases and queues over mTLS Important
In plain words: The same idea applies to the systems your services talk to: the database or broker can require a client certificate and take the identity from it, so a leaked password is not enough to connect.
Common misunderstanding: "sslmode=require means the connection is verified." In libpq, require encrypts but does not verify the server certificate; verify-ca checks the chain; verify-full also checks that the host name matches. The libpq documentation says verify-full "is recommended in most security-sensitive environments".
| System | Server verifies client | Identity taken from | Client verifies server | Server config key |
|---|---|---|---|---|
| PostgreSQL | hostssl line with clientcert=verify-full (or the cert method); the CA in ssl_ca_file | CN by default, or the whole DN with clientname=DN; mapped by pg_ident.conf | sslmode=verify-full and sslrootcert | pg_hba.conf, postgresql.conf |
| Redis | tls-auth-clients yes | Not mapped to a Redis user by default; ACLs are by user and password | tls-ca-cert-file, client verifies with its CA | redis.conf |
| Kafka | ssl.client.auth=required (or requested) with a truststore holding the CAs that signed client keys | The certificate's distinguished name becomes the principal, usable in ACLs | Client truststore holds the broker's CA | server.properties |
| RabbitMQ | ssl_options.verify = verify_peer, fail_if_no_peer_cert = true, and the EXTERNAL authentication mechanism | ssl_cert_login_from: the DN, the CN or a SAN | Client verifies the broker | rabbitmq.conf |
| MongoDB, MySQL | --tlsCAFile and --tlsMode requireTLS with x.509 auth (MongoDB) / REQUIRE X509 (MySQL) | Subject DN | Client CA file | server config |
The PostgreSQL manual explains the setup: put the CA that signed client certificates in ssl_ca_file and add clientcert=verify-ca or clientcert=verify-full to the hostssl lines; "verify-full additionally enforces that the cn (Common Name) in the certificate matches the username or an applicable mapping". RabbitMQ's EXTERNAL mechanism page says to allow it with auth_mechanisms.1 = EXTERNAL and that "the server must be configured with the SSL option 'verify' set to 'verify_peer'". The Kafka documentation says that when you set ssl.client.auth to requested or required on the brokers, "you must provide a truststore for the Kafka brokers as well and it should have all the CA certificates that clients’ keys were signed by".
# pg_hba.conf: only application servers with a certificate signed by our CA, and the CN must equal the role
hostssl orders orders_app 10.20.0.0/16 scram-sha-256 clientcert=verify-full-- Who is connected, with TLS, and which certificate did they present? (PostgreSQL pg_stat_ssl)
SELECT a.usename, a.client_addr, s.ssl, s.version, s.cipher, s.client_dn, s.client_serial
FROM pg_stat_ssl s
JOIN pg_stat_activity a USING (pid)
WHERE a.backend_type = 'client backend';
-- Anything connected without TLS is a finding:
SELECT a.usename, a.client_addr FROM pg_stat_ssl s JOIN pg_stat_activity a USING (pid)
WHERE NOT s.ssl AND a.backend_type = 'client backend';For broker-side certificates, ACLs and rotation in a messaging system see Messaging Security; for roles, row-level security and encryption of stored data see Database Security and Encryption at Rest, in Transit & in Use.
Kubernetes specifics Important
In plain words: Kubernetes can mint certificates (CertificateSigningRequest objects), cert-manager automates issuance and renewal, and the result lands in a Secret that pods mount. A mesh or SPIRE removes the Secret from the picture entirely.
Common misunderstanding: "A kubernetes.io/tls Secret is a safe place for a long-lived key." Secrets are base64 in etcd unless encryption at rest is enabled, readable by anyone who can get them in that namespace, and often copied into backups and CI logs. Prefer short-lived leaves delivered by an agent and mounted in memory (emptyDir with medium: Memory) or served by the Workload API.
| Piece | Role | Detail |
|---|---|---|
CertificateSigningRequest API (certificates.k8s.io/v1) | Ask a signer for a certificate | spec.signerName is required; spec.expirationSeconds (v1.22+) minimum 600; a request must be approved before it is signed; the built-in kubernetes.io/kube-apiserver-client signer's certificates are honoured by the API server and never auto-approved |
cert-manager Issuer / ClusterIssuer | Configuration of a CA (CA, Vault, ACME, Venafi, self-signed) | The ca issuer signs with a CA key held in a Secret |
cert-manager Certificate | Desired certificate: dnsNames, uris, duration, renewBefore, usages: [server auth, client auth], privateKey.rotationPolicy | The controller creates a Secret and renews |
| trust-manager | Distributes CA bundles as ConfigMaps | Keeps the trust bundle in step with the issuer |
| SPIFFE CSI driver / SPIRE agent | Delivers SVIDs without Secrets | Files in a CSI volume, rewritten on rotation |
| Mesh (Istio, Linkerd) | Delivers certificates inside the sidecar | Nothing for the app to mount |
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: orders
namespace: prod
spec:
secretName: orders-tls
duration: 24h
renewBefore: 8h
privateKey:
algorithm: ECDSA
size: 256
rotationPolicy: Always
usages: ["server auth", "client auth"]
dnsNames: ["orders.prod.svc.cluster.local"]
uris: ["spiffe://shop.example/ns/prod/sa/orders"]
issuerRef:
name: internal-ca
kind: ClusterIssuerKubernetes networking itself (Services, kube-proxy, CNI) is in Kubernetes Networking; deployment topics are in Containers & Kubernetes.
gRPC credentials Good to know
In plain words: gRPC has two kinds of credentials: channel credentials (the TLS identity of the connection) and call credentials (a token attached to each RPC).
Common misunderstanding: "gRPC is secure by default." The gRPC authentication guide says gRPC "promotes the use of SSL/TLS" but a channel is insecure unless you pass credentials when you create it.
| Credential | Go | Laravel / PHP |
|---|---|---|
| Server TLS | grpc.Creds(credentials.NewTLS(cfg)) where cfg is the same tls.Config as for HTTP | The PHP gRPC extension ChannelCredentials::createSsl($rootCerts, $privateKey, $certChain) |
| Client TLS (mutual) | grpc.WithTransportCredentials(credentials.NewTLS(cfg)) with GetClientCertificate | createSsl with the client key and chain |
| Per-RPC token | grpc.WithPerRPCCredentials(tokenSource) | Metadata authorization: Bearer ... |
| Peer identity in the handler | peer.FromContext(ctx) then AuthInfo.(credentials.TLSInfo).State.PeerCertificates[0] | Not available in client-only PHP |
Because gRPC rides on HTTP/2 over the same tls.Config, the Go code of this chapter works unchanged for gRPC: pass the config returned by Store.ServerConfig() to credentials.NewTLS. See gRPC & Protocol Buffers.
Performance: handshake cost, resumption, connection reuse, offload Important
In plain words: mTLS adds work at connection setup (an extra certificate to send and verify, one more signature each way), almost nothing per request afterwards.
Common misunderstanding: "mTLS makes every request slower." It makes new connections more expensive. A connection that serves a million requests pays the handshake once. The expensive pattern is a client that opens a new connection per request.
| Cost | Where | Magnitude | What reduces it |
|---|---|---|---|
| Handshake round trips | New connection | 1 RTT for TLS 1.3 on top of TCP's 1 RTT; mutual authentication does not add a round trip in TLS 1.3 | TLS 1.3; keep-alive; HTTP/2 multiplexing |
| Handshake CPU | Both ends | Measured on one laptop: 0.46 ms per one-way TLS handshake and 0.81 ms per mTLS handshake, both sides in one process, loopback | ECDSA P-256 instead of RSA; session resumption |
| Chain size | Bytes on the wire | A leaf plus one intermediate is typically 1-2 KB each way | Short chains; omit the root |
| Per-request cost | Steady state | AEAD symmetric encryption: usually negligible next to the application | Hardware AES |
| Resumption | Repeat connections | A resumed session skips the certificate exchange: 0.63 ms in the same measurement, and that figure includes re-verifying the chain and identity on every resumed connection, which our code does on purpose | ClientSessionCache in Go; session tickets; note that rotating the server config invalidates tickets |
| Offload | Terminate TLS in a proxy or load balancer | Moves CPU to a dedicated tier | But identity ends at the proxy; carry it forward in a trusted header or re-encrypt to the backend (TLS passthrough or re-origination) |
The numbers are from the benchmark in the lab (Apple M4 Pro, Go 1.27, loopback): they say how the three cases compare, not what your network will do. On a real network the two TCP/TLS round trips (about 2 x RTT) dominate the CPU cost.
new connection, no resumption : TCP SYN/ACK (1 RTT) + TLS 1.3 handshake (1 RTT) + request/response (1 RTT)
resumed connection (PSK) : TCP (1 RTT) + TLS resumption (1 RTT, no certificates) + request
reused connection (keep-alive): request/response (1 RTT) onlyConnection pooling in HTTP clients (Go http.Transport, Guzzle with a cURL handle, gRPC channels) is the biggest single lever; see Load Balancing for how an L4 or L7 balancer in the middle changes where TLS ends.
Operational failures: expiry outages and clock skew Must-know
In plain words: Most mTLS outages are not attacks. They are certificates that expired, a bundle that was not updated, or a clock that is wrong.
Common misunderstanding: "Short-lived certificates make clock skew a bigger risk, so use long ones." A verifier checks NotBefore <= now <= NotAfter. If the verifier's clock is behind the issuer's by more than the backdating margin, a brand-new certificate is "not yet valid"; if it is ahead, a still-valid one is "expired". The answer is to keep clocks right (NTP, chrony), backdate NotBefore by a minute (the Go pki package does), and monitor skew, not to lengthen lifetimes.
| Failure | What you see | Cause | Prevention |
|---|---|---|---|
| Leaf expired | x509: certificate has expired or is not yet valid (Go), certificate has expired (OpenSSL code 10), 503s through the mesh | Agent failed to renew; Secret not refreshed | Alert at 25% of TTL remaining; test renewal failure in a game day |
| Intermediate or root expired | Every chain fails at once | Forgotten CA lifetime | Inventory CA expiry dates; renew intermediates early |
| Linkerd trust anchor expired | Mesh-wide mTLS failure | Default anchor lives 365 days and must be rotated manually (Linkerd documentation) | Calendar and alert; supply your own anchor with a planned lifetime |
| Public cross-sign expired | Old clients fail to validate otherwise valid chains | On 30 September 2021 the DST Root CA X3 cross-sign used by Let's Encrypt expired; clients without ISRG Root X1 broke (Let's Encrypt documentation) | Know which roots your clients trust; do not use public chains for internal mTLS |
| Clock skew | certificate is not yet valid right after issuance | Node clock behind | NTP; NotBefore backdating; monitor node_timex_offset_seconds |
| Bundle not rotated | unknown certificate authority for some peers | Dual-trust phase skipped | Version the bundle; report the active bundle hash per workload |
| Hot reload missing | New cert on disk, old cert still served | Process loaded the file once | GetCertificate / GetClientCertificate read through a store; watch files |
Operational rules: keep an inventory of every certificate and CA with its expiry; export seconds until expiry as a metric from every agent and workload (the observability and alerting chapters cover the pipeline); rehearse the failure of the issuer, because with 1-hour leaves you have about 30 minutes after the issuer goes down before workloads start failing; and write the runbook for "the CA is compromised" before you need it (Secure SDLC & Incident Response).
Zero trust for services: BeyondProd Important
In plain words: Zero trust means no request is trusted merely because of where it comes from; every request carries an identity that is checked and every service is allowed only what it needs.
Common misunderstanding: "Zero trust is a product you buy." It is a design stance with several parts, and mTLS plus policy is the service-to-service part.
BeyondProd, Google's description of cloud-native security, lists the properties in its own words; three of them map straight onto this page:
| BeyondProd property | In this chapter |
|---|---|
| "No inherent mutual trust between services" | mTLS with a policy that defaults to deny |
| Trusted machines running code with known provenance; "Service identities are constrained to use only authorized code and configurations" | Workload attestation (SPIRE) and signed images; the issuer must not hand an ID to a pod that merely asks |
| Consistent, mutual authentication and transport encryption between services (ALTS at Google) | The mesh or the shared tls.Config library |
NIST SP 800-207 (Zero Trust Architecture) is the neutral reference for the policy decision point and enforcement point vocabulary; see Authorization: RBAC, ABAC & Zero Trust for the model and Security Foundations for the threat vocabulary (spoofing is the STRIDE category mTLS answers).
Debugging with openssl s_client Must-know
In plain words: openssl s_client is the shell's TLS client: it performs a handshake, prints the chain it received, and ends with a "Verify return code".
Common misunderstanding: "Connection refused and handshake failure are the same." Refused is TCP; a handshake failure means TCP worked and the two sides disagreed about certificates, versions or ciphers.
# 1. What does the server present, and does my CA verify it?
openssl s_client -connect orders.internal.example:8443 -servername orders.internal.example \
-CAfile ca.crt -verify_return_error </dev/null
# 2. Add my client certificate (mutual TLS)
openssl s_client -connect orders.internal.example:8443 -cert billing.crt -key billing.key -CAfile ca.crt </dev/null
# 3. Read a certificate: validity, SAN, key usage
openssl x509 -in billing.crt -noout -text | grep -E 'Not (Before|After)|Subject Alternative|Extended Key|CA:'
# 4. Does this leaf chain to this root, with this intermediate?
openssl verify -CAfile ca.crt -untrusted intermediate.crt billing.crt
# 5. Do key and certificate belong together? (the two hashes must match)
openssl x509 -in billing.crt -noout -pubkey | openssl sha256
openssl pkey -in billing.key -pubout | openssl sha256| Output | Meaning | Usual fix |
|---|---|---|
Verify return code: 0 (ok) | Chain verified | Look elsewhere (identity policy) |
Verify return code: 20 (unable to get local issuer certificate) | Missing intermediate or CA not in -CAfile | Send the chain with the leaf; fix the bundle |
Verify return code: 18 (self-signed certificate) or 19 (self-signed certificate in certificate chain) | Chain ends in a root you do not trust | Add that root to the bundle (if intended) |
Verify return code: 10 (certificate has expired) | Expired in the verifier's view | Renew; check the verifier's clock |
Verify return code: 9 (certificate is not yet valid) | NotBefore in the future for the verifier | Clock skew; backdate NotBefore |
Verify return code: 62 (Hostname mismatch ...) | Name given with -verify_hostname not in SAN | Use the right name or verify the SPIFFE ID instead |
no peer certificate available | Server did not send one | Wrong listener or plaintext port |
alert certificate required (TLS 1.3 alert 116) or alert handshake failure | Server wanted a client certificate and you sent none | Pass -cert and -key |
alert bad certificate (alert 42), unknown ca (alert 48) | Server rejected the client certificate | Check issuer, identity policy and server-side logs |
A request that fails only through the mesh can be probed from inside a pod with the sidecar's own certificate; istioctl proxy-config secret POD and istioctl x describe pod POD print what the sidecar holds and what policies apply. The error text on the server side usually tells you more than the client's: Go logs http: TLS handshake error from ...: tls: client didn't provide a certificate.
Mechanics
Verification, step by step
For one leaf and its presented chain, a verifier does:
1 parse certificates; reject if the leaf is a CA when a workload identity is expected
2 build a path: leaf -> presented intermediates -> a root in the trust bundle
3 check each certificate: signature, NotBefore <= now <= NotAfter, basicConstraints.CA and pathLenConstraint for CAs
4 check key usage: digitalSignature on the leaf; extendedKeyUsage contains serverAuth (verifying a server) or clientAuth (verifying a client)
5 check revocation if configured (CRL or OCSP); internal meshes usually rely on short lifetimes instead
6 extract the identity: URI SAN (exactly one, spiffe scheme) or DNS SAN against the dialed name
7 apply policy: is this identity allowed to talk to me?Knobs, in one place
| Knob | Where | Effect |
|---|---|---|
tls.Config.ClientAuth | Go server | NoClientCert, RequestClientCert, RequireAnyClientCert, VerifyClientCertIfGiven, RequireAndVerifyClientCert; use the last for mTLS |
tls.Config.ClientCAs | Go server | Roots used to verify client chains; static per config, so use GetConfigForClient to change it at run time |
tls.Config.RootCAs | Go client | Roots for server chains; nil means the system pool, which you do not want internally |
tls.Config.VerifyPeerCertificate | Go both sides | Runs after normal verification with the raw certificates and the verified chains; if normal verification fails the handshake aborts before this callback; the Go documentation says it "is not invoked on resumed connections" |
tls.Config.VerifyConnection | Go both sides | Runs on every connection including resumptions, regardless of InsecureSkipVerify or ClientAuth; use it for checks that must hold on every connection |
tls.Config.GetCertificate / GetClientCertificate | Go | Pick the certificate per handshake: the hot-rotation hook |
tls.Config.GetConfigForClient | Go server | Returns a config per connection: swap ClientCAs; keep the returned config cached so session tickets keep working |
tls.Config.MinVersion | Go | Set tls.VersionTLS13 for internal traffic |
tls.Config.Time | Go | Clock for validity; tests replace it |
InsecureSkipVerify | Go client | Disables the built-in chain and host name verification; only acceptable when VerifyConnection (or VerifyPeerCertificate plus resumption handling) replaces it completely, as in this chapter's client |
ssl_verify_client, ssl_client_certificate, ssl_crl, ssl_verify_depth | NGINX | Client verification, CA file, CRL, maximum chain depth |
trust_chain_verification / validation_context | Envoy | CA bundle and match_typed_subject_alt_names for SAN matching |
sslmode, sslcert, sslkey, sslrootcert | libpq / Laravel pgsql | Client side of PostgreSQL TLS |
ssl.client.auth, ssl.keystore.location, ssl.truststore.location | Kafka | Client-auth mode and stores |
auth_mechanisms, ssl_cert_login_from | RabbitMQ | Enable EXTERNAL and choose the identity field |
Error names you will see
| Message | Side | Meaning |
|---|---|---|
tls: client didn't provide a certificate | Go server log | Client sent none and ClientAuth requires one |
remote error: tls: certificate required | Go client | TLS 1.3 alert 116 from the server |
remote error: tls: bad certificate | Go client | Server rejected the client certificate (chain, usage or VerifyPeerCertificate) |
remote error: tls: unknown certificate authority | Go client | Server does not trust the issuer |
x509: certificate signed by unknown authority | Go | The verifier's bundle lacks the issuer |
x509: certificate has expired or is not yet valid: current time ... | Go | Validity window or clock |
x509: certificate specifies an incompatible key usage | Go | clientAuth or serverAuth missing from extended key usage |
mtls: peer identity not allowed: spiffe://... | This chapter's code | Valid certificate, identity outside the policy |
FATAL: connection requires a valid client certificate | PostgreSQL | Server wanted clientcert, none presented |
upstream connect error or disconnect/reset before headers with 503 | Envoy / Istio | Often a STRICT/plaintext mismatch or a failed handshake between sidecars |
CERTIFICATE_VERIFY_FAILED | Envoy, Python, others | BoringSSL/OpenSSL chain verification failed |
Exact wording varies with versions; the Go and OpenSSL lines were produced by the code and commands in this chapter, the PostgreSQL, Envoy and Istio lines are the common forms from their documentation and field experience.
Go
Example: a small private CA, a verifying server and client, hot rotation
The example has four parts. pki is a tiny CA (an ECDSA root, an intermediate with MaxPathLen 0, leaves with one SPIFFE URI SAN, both usages, NotBefore backdated by a minute). mtls.Store holds the current certificate and trust bundle and hands out tls.Config values that always read the latest snapshot. The server config uses RequireAndVerifyClientCert with GetConfigForClient (so the bundle can change), VerifyPeerCertificate for the identity check on a full handshake and VerifyConnection to repeat the checks on resumed sessions. The client config disables Go's built-in verification only to replace it, in VerifyConnection, with a complete one against the live bundle plus the identity policy. Reloader watches files and swaps a new snapshot in, keeping the old one when an update is broken.
// Package pki is a tiny private CA for tests and labs: an ECDSA root, optional
// intermediates, and short-lived leaf certificates that carry a SPIFFE ID as
// their only URI SAN. It is not a production CA: keys live in memory, there is
// no revocation, and nothing is audited.
package pki
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"errors"
"fmt"
"math/big"
"net/url"
"time"
)
// SkewAllowance is subtracted from NotBefore so that a verifier whose clock is
// a little behind the issuer does not reject a brand-new certificate.
const SkewAllowance = time.Minute
// CA is a certificate authority: a certificate, its key, and the intermediates
// that must be sent along with every leaf it issues (the root is never sent).
type CA struct {
Cert *x509.Certificate
Key *ecdsa.PrivateKey
// Chain holds this CA's own certificate and its intermediate ancestors,
// nearest first, root excluded. It is empty for a root.
Chain []*x509.Certificate
}
// NewRoot creates a self-signed root that may sign one level of intermediates.
func NewRoot(commonName string, ttl time.Duration, now time.Time) (*CA, error) {
return newCA(commonName, ttl, now, nil)
}
// NewIntermediate creates an intermediate CA signed by ca. It may only sign leaves.
func (ca *CA) NewIntermediate(commonName string, ttl time.Duration, now time.Time) (*CA, error) {
return newCA(commonName, ttl, now, ca)
}
func newCA(commonName string, ttl time.Duration, now time.Time, parent *CA) (*CA, error) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
}
serial, err := newSerial()
if err != nil {
return nil, err
}
tmpl := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{CommonName: commonName},
NotBefore: now.Add(-SkewAllowance),
NotAfter: now.Add(ttl),
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
BasicConstraintsValid: true,
IsCA: true,
MaxPathLen: 1, // a root may sign intermediates
}
signer, signerKey := tmpl, key
if parent != nil {
tmpl.MaxPathLen = 0 // an intermediate may only sign leaves
tmpl.MaxPathLenZero = true
signer, signerKey = parent.Cert, parent.Key
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, signer, &key.PublicKey, signerKey)
if err != nil {
return nil, err
}
cert, err := x509.ParseCertificate(der)
if err != nil {
return nil, err
}
ca := &CA{Cert: cert, Key: key}
if parent != nil {
ca.Chain = append([]*x509.Certificate{cert}, parent.Chain...)
}
return ca, nil
}
// LeafSpec describes the workload a certificate is issued to.
type LeafSpec struct {
SPIFFEID string // spiffe://trust-domain/path, becomes the only URI SAN
DNSNames []string // optional DNS SANs for clients that verify host names
TTL time.Duration // keep it short: minutes to hours, not years
}
// Leaf is an issued certificate chain (leaf first) with its private key.
type Leaf struct {
Cert *x509.Certificate
Chain [][]byte // DER, leaf first, then intermediates
Key *ecdsa.PrivateKey
}
// Issue signs a leaf for spec. The key never leaves the caller in a real system:
// the workload would send a CSR and keep its key. Here the CA generates both.
func (ca *CA) Issue(spec LeafSpec, now time.Time) (*Leaf, error) {
u, err := url.Parse(spec.SPIFFEID)
if err != nil || u.Scheme != "spiffe" || u.Host == "" {
return nil, fmt.Errorf("pki: %q is not a SPIFFE ID", spec.SPIFFEID)
}
if spec.TTL <= 0 {
return nil, errors.New("pki: TTL must be positive")
}
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
}
serial, err := newSerial()
if err != nil {
return nil, err
}
tmpl := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{}, // identity lives in the SAN, not in the subject
NotBefore: now.Add(-SkewAllowance),
NotAfter: now.Add(spec.TTL),
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
URIs: []*url.URL{u},
DNSNames: spec.DNSNames,
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.Cert, &key.PublicKey, ca.Key)
if err != nil {
return nil, err
}
cert, err := x509.ParseCertificate(der)
if err != nil {
return nil, err
}
chain := [][]byte{der}
for _, c := range ca.Chain {
chain = append(chain, c.Raw)
}
return &Leaf{Cert: cert, Chain: chain, Key: key}, nil
}
// TLS converts the leaf into a certificate usable in a tls.Config.
func (l *Leaf) TLS() tls.Certificate {
return tls.Certificate{Certificate: l.Chain, PrivateKey: l.Key, Leaf: l.Cert}
}
// PEM returns the certificate chain and the PKCS #8 private key as PEM.
func (l *Leaf) PEM() (certPEM, keyPEM []byte, err error) {
for _, der := range l.Chain {
certPEM = append(certPEM, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})...)
}
keyPEM, err = encodeKey(l.Key)
return certPEM, keyPEM, err
}
// Pool returns a trust bundle holding the given CA certificates.
func Pool(cas ...*CA) *x509.CertPool {
p := x509.NewCertPool()
for _, ca := range cas {
p.AddCert(ca.Cert)
}
return p
}
// CertPEM returns the CA certificate as PEM (a trust bundle entry).
func (ca *CA) CertPEM() []byte {
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca.Cert.Raw})
}
// KeyPEM returns the CA private key as PKCS #8 PEM. Guard it like a root secret.
func (ca *CA) KeyPEM() ([]byte, error) { return encodeKey(ca.Key) }
// LoadCA rebuilds a root CA from PEM files written by CertPEM and KeyPEM.
func LoadCA(certPEM, keyPEM []byte) (*CA, error) {
cb, _ := pem.Decode(certPEM)
kb, _ := pem.Decode(keyPEM)
if cb == nil || kb == nil {
return nil, errors.New("pki: no PEM block found")
}
cert, err := x509.ParseCertificate(cb.Bytes)
if err != nil {
return nil, err
}
k, err := x509.ParsePKCS8PrivateKey(kb.Bytes)
if err != nil {
return nil, err
}
key, ok := k.(*ecdsa.PrivateKey)
if !ok {
return nil, errors.New("pki: CA key is not ECDSA")
}
return &CA{Cert: cert, Key: key}, nil
}
func encodeKey(key *ecdsa.PrivateKey) ([]byte, error) {
der, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), nil
}
func newSerial() (*big.Int, error) {
return rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127))
}// Package mtls builds tls.Config values for service-to-service mutual TLS:
// both sides verify the peer chain, the peer identity is the SPIFFE ID in the
// URI SAN, a policy decides which identities may talk, and the certificate and
// trust bundle can be swapped at run time without restarting the process.
package mtls
import (
"crypto/x509"
"errors"
"fmt"
"net/url"
)
// ErrNotAllowed is returned when the peer's certificate is valid but its
// identity is not accepted by the policy.
var ErrNotAllowed = errors.New("mtls: peer identity not allowed")
// SPIFFEID extracts the workload identity from a certificate. Following the
// X.509-SVID rules it requires exactly one URI SAN, the spiffe scheme, a trust
// domain, and no user info, port, query or fragment; CA certificates are not
// workload identities.
func SPIFFEID(cert *x509.Certificate) (string, error) {
if cert.IsCA {
return "", errors.New("mtls: CA certificate used as a workload identity")
}
if len(cert.URIs) != 1 {
return "", fmt.Errorf("mtls: want exactly one URI SAN, got %d", len(cert.URIs))
}
u := cert.URIs[0]
if u.Scheme != "spiffe" || u.Host == "" || u.User != nil || u.Port() != "" ||
u.RawQuery != "" || u.Fragment != "" || u.Path == "" || u.Path == "/" {
return "", fmt.Errorf("mtls: %q is not a valid workload SPIFFE ID", u.String())
}
return u.String(), nil
}
// TrustDomain returns the trust domain (host part) of a SPIFFE ID.
func TrustDomain(id string) string {
u, err := url.Parse(id)
if err != nil {
return ""
}
return u.Host
}
// Policy decides whether a verified peer identity may connect.
type Policy func(peerID string) bool
// AllowIDs accepts exactly the listed SPIFFE IDs.
func AllowIDs(ids ...string) Policy {
set := make(map[string]struct{}, len(ids))
for _, id := range ids {
set[id] = struct{}{}
}
return func(peer string) bool { _, ok := set[peer]; return ok }
}
// AllowTrustDomain accepts any workload of one trust domain. Coarse; prefer AllowIDs.
func AllowTrustDomain(td string) Policy {
return func(peer string) bool { return TrustDomain(peer) == td }
}
func check(leaf *x509.Certificate, allow Policy) error {
id, err := SPIFFEID(leaf)
if err != nil {
return err
}
if allow != nil && !allow(id) {
return fmt.Errorf("%w: %s", ErrNotAllowed, id)
}
return nil
}package mtls
import (
"crypto/tls"
"crypto/x509"
"errors"
"sync/atomic"
"time"
)
// snapshot is one consistent pair of "who I am" and "whom I trust".
type snapshot struct {
cert *tls.Certificate
roots *x509.CertPool
server *tls.Config // built once per snapshot so session tickets keep working
}
// Store holds the current certificate and trust bundle and hands out tls.Config
// values that always read the latest snapshot. Replacing a snapshot affects new
// handshakes only; established connections keep running.
type Store struct {
cur atomic.Pointer[snapshot]
allow Policy
// Now is the clock used for certificate validity. Tests replace it.
Now func() time.Time
}
// NewStore creates a Store. allow is applied to every peer, on both sides.
func NewStore(cert tls.Certificate, roots *x509.CertPool, allow Policy) *Store {
s := &Store{allow: allow, Now: time.Now}
s.Set(cert, roots)
return s
}
// Set swaps in a new certificate and trust bundle atomically.
func (s *Store) Set(cert tls.Certificate, roots *x509.CertPool) {
snap := &snapshot{cert: &cert, roots: roots}
snap.server = &tls.Config{
MinVersion: tls.VersionTLS13,
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: roots,
GetCertificate: s.GetCertificate,
Time: func() time.Time { return s.Now() },
// Full handshakes only: Go has verified the chain against ClientCAs, so
// only the identity check is left. verifiedChains[0][0] is the client's leaf.
VerifyPeerCertificate: func(_ [][]byte, chains [][]*x509.Certificate) error {
if len(chains) == 0 || len(chains[0]) == 0 {
return errors.New("mtls: no verified chain")
}
return check(chains[0][0], s.allow)
},
// Every connection, including resumed sessions (VerifyPeerCertificate is
// skipped on resumption): chain and identity are checked again against the
// current bundle and policy.
VerifyConnection: func(cs tls.ConnectionState) error {
return s.verify(cs.PeerCertificates, x509.ExtKeyUsageClientAuth)
},
}
s.cur.Store(snap)
}
// GetCertificate serves the current certificate to a connecting client.
func (s *Store) GetCertificate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
return s.cur.Load().cert, nil
}
// GetClientCertificate serves the current certificate when a server asks for one.
func (s *Store) GetClientCertificate(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
return s.cur.Load().cert, nil
}
// ServerConfig returns a config that requires and verifies a client certificate.
// GetConfigForClient is what lets ClientCAs follow the trust bundle on rotation.
func (s *Store) ServerConfig() *tls.Config {
return &tls.Config{
MinVersion: tls.VersionTLS13,
GetCertificate: s.GetCertificate,
GetConfigForClient: func(*tls.ClientHelloInfo) (*tls.Config, error) { return s.cur.Load().server, nil },
}
}
// ClientConfig returns a config for dialing other services.
//
// InsecureSkipVerify disables only Go's built-in verification; it does NOT mean
// "trust anything". VerifyConnection below performs the full chain verification
// against the current trust bundle, requires the serverAuth key usage, and checks
// the SPIFFE ID against the policy, on every connection including resumed ones.
// The server is identified by its SPIFFE ID, not by the host name it was dialed with.
func (s *Store) ClientConfig() *tls.Config {
return &tls.Config{
MinVersion: tls.VersionTLS13,
GetClientCertificate: s.GetClientCertificate,
InsecureSkipVerify: true, //nolint:gosec // replaced by VerifyConnection
VerifyConnection: func(cs tls.ConnectionState) error {
return s.verify(cs.PeerCertificates, x509.ExtKeyUsageServerAuth)
},
}
}
// verify checks a presented chain (leaf first) against the current bundle,
// the clock and the key usage, then applies the identity policy.
func (s *Store) verify(certs []*x509.Certificate, usage x509.ExtKeyUsage) error {
if len(certs) == 0 {
return errors.New("mtls: peer sent no certificate")
}
inter := x509.NewCertPool()
for _, c := range certs[1:] {
inter.AddCert(c)
}
_, err := certs[0].Verify(x509.VerifyOptions{
Roots: s.cur.Load().roots,
Intermediates: inter,
KeyUsages: []x509.ExtKeyUsage{usage},
CurrentTime: s.Now(),
})
if err != nil {
return err
}
return check(certs[0], s.allow)
}package mtls
import (
"net/http"
"strings"
)
// Rule says which caller may use which method and path prefix.
type Rule struct {
Caller string // SPIFFE ID
Methods []string // empty means any
PathPrefix string // empty means any
}
// CallerID returns the SPIFFE ID of the verified client certificate of r.
func CallerID(r *http.Request) (string, bool) {
if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
return "", false
}
id, err := SPIFFEID(r.TLS.PeerCertificates[0])
return id, err == nil
}
// Authorize turns the transport identity into an application decision:
// 401 without a verified identity, 403 when no rule matches. Authentication
// (who is calling) is done by the handshake; this is authorization (may it).
func Authorize(rules []Rule, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
caller, ok := CallerID(r)
if !ok {
http.Error(w, "no verified service identity", http.StatusUnauthorized)
return
}
for _, rule := range rules {
if rule.Caller == caller && methodOK(rule.Methods, r.Method) &&
strings.HasPrefix(r.URL.Path, rule.PathPrefix) {
next.ServeHTTP(w, r)
return
}
}
http.Error(w, "caller not allowed for this operation", http.StatusForbidden)
})
}
func methodOK(methods []string, m string) bool {
if len(methods) == 0 {
return true
}
for _, x := range methods {
if x == m {
return true
}
}
return false
}package mtls
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"os"
"sync"
"time"
)
// Files names the PEM files a workload agent (cert-manager, SPIRE helper,
// Vault agent, a Kubernetes Secret volume) keeps fresh on disk.
type Files struct {
Cert, Key, CA string
}
// Load reads the files into a certificate and a trust bundle. The cert file
// may contain the leaf followed by intermediates.
func (f Files) Load() (tls.Certificate, *x509.CertPool, error) {
cert, err := tls.LoadX509KeyPair(f.Cert, f.Key)
if err != nil {
return tls.Certificate{}, nil, err
}
caPEM, err := os.ReadFile(f.CA)
if err != nil {
return tls.Certificate{}, nil, err
}
roots := x509.NewCertPool()
if !roots.AppendCertsFromPEM(caPEM) {
return tls.Certificate{}, nil, errors.New("mtls: no certificates in CA bundle")
}
return cert, roots, nil
}
// Reloader polls the files and calls Store.Set when any of them changed. A bad
// update (half-written file, mismatched key) is reported and the old material
// stays in use: rotation must never turn into an outage by itself.
type Reloader struct {
Store *Store
Files Files
OnError func(error)
mu sync.Mutex
seen map[string]os.FileInfo
}
// Poll reloads when a file changed since the last successful call.
func (r *Reloader) Poll() (reloaded bool, err error) {
r.mu.Lock()
defer r.mu.Unlock()
now := map[string]os.FileInfo{}
changed := r.seen == nil
for _, p := range []string{r.Files.Cert, r.Files.Key, r.Files.CA} {
fi, err := os.Stat(p) // Stat follows symlinks: Kubernetes Secret volumes swap them
if err != nil {
return false, err
}
now[p] = fi
if old, ok := r.seen[p]; !ok || !old.ModTime().Equal(fi.ModTime()) || old.Size() != fi.Size() {
changed = true
}
}
if !changed {
return false, nil
}
cert, roots, err := r.Files.Load()
if err != nil {
return false, err
}
r.Store.Set(cert, roots)
r.seen = now
return true, nil
}
// Run polls until ctx is cancelled.
func (r *Reloader) Run(ctx context.Context, every time.Duration) {
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if _, err := r.Poll(); err != nil && r.OnError != nil {
r.OnError(err)
}
}
}
}The tests generate every certificate in memory with crypto/x509. They cover the allowed caller, no client certificate, a certificate from another CA, a valid certificate with an identity outside the policy, an impostor server, an expired certificate with a controlled clock, clock skew inside and outside the backdating margin, hot rotation of the server certificate, the four-phase dual-trust rotation, 403 from Authorize, SPIFFE ID validation, and file reloading including a corrupted update.
package mtls_test
import (
"crypto/tls"
"crypto/x509"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"academy/mtls-service-security/mtls"
"academy/mtls-service-security/pki"
)
const (
ordersID = "spiffe://shop.example/ns/prod/sa/orders"
billingID = "spiffe://shop.example/ns/prod/sa/billing"
mailerID = "spiffe://shop.example/ns/prod/sa/mailer"
)
var t0 = time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC)
type env struct {
root, inter *pki.CA
}
func newEnv(t *testing.T) env {
t.Helper()
root, err := pki.NewRoot("Shop Root CA", 10*365*24*time.Hour, t0)
if err != nil {
t.Fatal(err)
}
inter, err := root.NewIntermediate("Shop Issuing CA", 365*24*time.Hour, t0)
if err != nil {
t.Fatal(err)
}
return env{root, inter}
}
func (e env) leaf(t *testing.T, id string, ttl time.Duration) *pki.Leaf {
t.Helper()
l, err := e.inter.Issue(pki.LeafSpec{SPIFFEID: id, TTL: ttl}, t0)
if err != nil {
t.Fatal(err)
}
return l
}
// startOrders runs the "orders" service. Only billing may call it.
func startOrders(t *testing.T, e env) (*httptest.Server, *mtls.Store) {
t.Helper()
store := mtls.NewStore(e.leaf(t, ordersID, time.Hour).TLS(), pki.Pool(e.root), mtls.AllowIDs(billingID))
store.Now = func() time.Time { return t0.Add(time.Minute) }
mux := http.NewServeMux()
mux.HandleFunc("/orders", func(w http.ResponseWriter, r *http.Request) {
id, _ := mtls.CallerID(r)
_, _ = io.WriteString(w, "hello "+id)
})
srv := httptest.NewUnstartedServer(mtls.Authorize([]mtls.Rule{{Caller: billingID, PathPrefix: "/orders"}}, mux))
srv.TLS = store.ServerConfig()
srv.StartTLS()
t.Cleanup(srv.Close)
return srv, store
}
func client(store *mtls.Store) *http.Client {
return &http.Client{Transport: &http.Transport{TLSClientConfig: store.ClientConfig(), DisableKeepAlives: true}}
}
func get(c *http.Client, url string) (string, error) {
resp, err := c.Get(url + "/orders")
if err != nil {
return "", err
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
if resp.StatusCode != 200 {
return string(b), errors.New(resp.Status)
}
return string(b), nil
}
func clientStore(t *testing.T, e env, id string, trust *x509.CertPool) *mtls.Store {
t.Helper()
s := mtls.NewStore(e.leaf(t, id, time.Hour).TLS(), trust, mtls.AllowIDs(ordersID))
s.Now = func() time.Time { return t0.Add(time.Minute) }
return s
}
func TestAllowedCallerSucceeds(t *testing.T) {
e := newEnv(t)
srv, _ := startOrders(t, e)
body, err := get(client(clientStore(t, e, billingID, pki.Pool(e.root))), srv.URL)
if err != nil || body != "hello "+billingID {
t.Fatalf("body=%q err=%v", body, err)
}
}
func TestClientWithoutCertificateIsRejected(t *testing.T) {
e := newEnv(t)
srv, _ := startOrders(t, e)
c := &http.Client{Transport: &http.Transport{TLSClientConfig: clientStore(t, e, billingID, pki.Pool(e.root)).ClientConfig()}}
c.Transport.(*http.Transport).TLSClientConfig.GetClientCertificate = nil // present nothing
if _, err := get(c, srv.URL); err == nil {
t.Fatal("handshake without a client certificate must fail")
}
}
func TestCertificateFromAnotherCAIsRejected(t *testing.T) {
e, rogue := newEnv(t), newEnv(t)
srv, _ := startOrders(t, e)
// A perfectly valid billing identity, but issued by a CA the server does not trust.
if _, err := get(client(clientStore(t, rogue, billingID, pki.Pool(e.root))), srv.URL); err == nil {
t.Fatal("certificate from an untrusted CA must be rejected")
}
}
func TestValidCertificateWrongIdentityIsRejected(t *testing.T) {
e := newEnv(t)
srv, _ := startOrders(t, e)
// The mailer has a certificate from our CA, but is not on orders' allow list.
_, err := get(client(clientStore(t, e, mailerID, pki.Pool(e.root))), srv.URL)
if err == nil {
t.Fatal("identity outside the allow list must be rejected during the handshake")
}
}
func TestClientRejectsImpostorServer(t *testing.T) {
e := newEnv(t)
// The server presents the mailer identity, the client expects orders.
store := mtls.NewStore(e.leaf(t, mailerID, time.Hour).TLS(), pki.Pool(e.root), mtls.AllowIDs(billingID))
store.Now = func() time.Time { return t0.Add(time.Minute) }
srv := httptest.NewUnstartedServer(http.NotFoundHandler())
srv.TLS = store.ServerConfig()
srv.StartTLS()
defer srv.Close()
if _, err := get(client(clientStore(t, e, billingID, pki.Pool(e.root))), srv.URL); err == nil ||
!strings.Contains(err.Error(), "not allowed") {
t.Fatalf("want identity error, got %v", err)
}
}
func TestExpiredCertificateIsRejected(t *testing.T) {
e := newEnv(t)
srv, store := startOrders(t, e)
store.Now = func() time.Time { return t0.Add(2 * time.Hour) } // server clock: leaf is 1h long
cs := clientStore(t, e, billingID, pki.Pool(e.root))
cs.Now = store.Now
if _, err := get(client(cs), srv.URL); err == nil {
t.Fatal("expired certificates must be rejected")
}
}
func TestClockSkewWithinAllowance(t *testing.T) {
e := newEnv(t)
srv, store := startOrders(t, e)
// Verifier clock is 30 s behind the issuer: NotBefore was backdated by a minute.
store.Now = func() time.Time { return t0.Add(-30 * time.Second) }
cs := clientStore(t, e, billingID, pki.Pool(e.root))
cs.Now = store.Now
if _, err := get(client(cs), srv.URL); err != nil {
t.Fatalf("30 s of skew must be tolerated: %v", err)
}
// Two minutes behind is beyond the allowance.
store.Now = func() time.Time { return t0.Add(-2 * time.Minute) }
cs.Now = store.Now
if _, err := get(client(cs), srv.URL); err == nil {
t.Fatal("2 minutes of skew must fail")
}
}
func TestHotRotationOfServerCertificate(t *testing.T) {
e := newEnv(t)
srv, store := startOrders(t, e)
cs := clientStore(t, e, billingID, pki.Pool(e.root))
serial := func() string {
c := client(cs)
resp, err := c.Get(srv.URL + "/orders")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
return resp.TLS.PeerCertificates[0].SerialNumber.String()
}
before := serial()
store.Set(e.leaf(t, ordersID, time.Hour).TLS(), pki.Pool(e.root)) // no restart, no listener change
if after := serial(); after == before {
t.Fatal("new connections must see the rotated certificate")
}
}
func TestDualTrustRotationOfTheCA(t *testing.T) {
oldEnv, newEnv2 := newEnv(t), newEnv(t)
// Server first trusts both roots, then clients move to the new CA, then the old root is dropped.
both := pki.Pool(oldEnv.root, newEnv2.root)
srv, store := startOrders(t, oldEnv)
store.Set(oldEnv.leaf(t, ordersID, time.Hour).TLS(), both)
oldClient := clientStore(t, oldEnv, billingID, pki.Pool(oldEnv.root, newEnv2.root))
newClient := clientStore(t, newEnv2, billingID, pki.Pool(oldEnv.root, newEnv2.root))
if _, err := get(client(oldClient), srv.URL); err != nil {
t.Fatalf("old client during overlap: %v", err)
}
if _, err := get(client(newClient), srv.URL); err != nil {
t.Fatalf("new client during overlap: %v", err)
}
// Overlap over: the server drops the old root and moves to a certificate of the new CA.
store.Set(newEnv2.leaf(t, ordersID, time.Hour).TLS(), pki.Pool(newEnv2.root))
newClient.Set(newClient2(t, newEnv2), pki.Pool(newEnv2.root))
if _, err := get(client(newClient), srv.URL); err != nil {
t.Fatalf("new client after overlap: %v", err)
}
if _, err := get(client(oldClient), srv.URL); err == nil {
t.Fatal("a certificate of the retired CA must be rejected after the overlap")
}
}
func newClient2(t *testing.T, e env) tls.Certificate {
return e.leaf(t, billingID, time.Hour).TLS()
}
func TestAuthorizeRulesGive403(t *testing.T) {
e := newEnv(t)
srv, _ := startOrders(t, e)
c := client(clientStore(t, e, billingID, pki.Pool(e.root)))
resp, err := c.Get(srv.URL + "/admin") // billing is only allowed on /orders
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("status %d, want 403", resp.StatusCode)
}
}
func TestSPIFFEIDValidation(t *testing.T) {
e := newEnv(t)
good := e.leaf(t, billingID, time.Hour)
if id, err := mtls.SPIFFEID(good.Cert); err != nil || id != billingID {
t.Fatalf("id=%q err=%v", id, err)
}
if _, err := mtls.SPIFFEID(e.inter.Cert); err == nil {
t.Fatal("a CA certificate is not a workload identity")
}
if _, err := e.inter.Issue(pki.LeafSpec{SPIFFEID: "https://shop.example/x", TTL: time.Hour}, t0); err == nil {
t.Fatal("non-SPIFFE URI must not be issued")
}
}
func TestReloaderPicksUpNewFilesAndKeepsOldOnBadUpdate(t *testing.T) {
e := newEnv(t)
dir := t.TempDir()
f := mtls.Files{Cert: filepath.Join(dir, "tls.crt"), Key: filepath.Join(dir, "tls.key"), CA: filepath.Join(dir, "ca.crt")}
write := func(l *pki.Leaf) {
c, k, err := l.PEM()
if err != nil {
t.Fatal(err)
}
must(t, os.WriteFile(f.Cert, c, 0o600))
must(t, os.WriteFile(f.Key, k, 0o600))
must(t, os.WriteFile(f.CA, e.root.CertPEM(), 0o600))
}
first := e.leaf(t, ordersID, time.Hour)
write(first)
cert, roots, err := f.Load()
must(t, err)
store := mtls.NewStore(cert, roots, nil)
r := &mtls.Reloader{Store: store, Files: f}
if ok, err := r.Poll(); err != nil || !ok {
t.Fatalf("first poll: reloaded=%v err=%v", ok, err)
}
if ok, _ := r.Poll(); ok {
t.Fatal("nothing changed, nothing should reload")
}
second := e.leaf(t, ordersID, time.Hour)
write(second)
future := time.Now().Add(time.Minute)
for _, p := range []string{f.Cert, f.Key, f.CA} {
must(t, os.Chtimes(p, future, future))
}
if ok, err := r.Poll(); err != nil || !ok {
t.Fatalf("rotation poll: reloaded=%v err=%v", ok, err)
}
got, _ := store.GetCertificate(nil)
if got.Leaf != nil && got.Leaf.SerialNumber.Cmp(first.Cert.SerialNumber) == 0 {
t.Fatal("store still serves the first certificate")
}
// A half-written update must not replace the working certificate.
must(t, os.WriteFile(f.Cert, []byte("garbage"), 0o600))
later := future.Add(time.Minute)
must(t, os.Chtimes(f.Cert, later, later))
if _, err := r.Poll(); err == nil {
t.Fatal("garbage must be reported")
}
still, _ := store.GetCertificate(nil)
if still != got {
t.Fatal("a failed reload must keep the previous certificate")
}
}
func must(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}package pki_test
import (
"crypto/x509"
"testing"
"time"
"academy/mtls-service-security/pki"
)
func TestLeafChainsToRootThroughIntermediate(t *testing.T) {
now := time.Date(2026, 11, 26, 9, 0, 0, 0, time.UTC)
root, err := pki.NewRoot("Root", 24*time.Hour, now)
if err != nil {
t.Fatal(err)
}
inter, err := root.NewIntermediate("Issuing", 12*time.Hour, now)
if err != nil {
t.Fatal(err)
}
leaf, err := inter.Issue(pki.LeafSpec{SPIFFEID: "spiffe://shop.example/ns/a/sa/b", TTL: 15 * time.Minute}, now)
if err != nil {
t.Fatal(err)
}
if got := len(leaf.Chain); got != 2 {
t.Fatalf("chain has %d certificates, want leaf + intermediate", got)
}
if ttl := leaf.Cert.NotAfter.Sub(now); ttl != 15*time.Minute {
t.Fatalf("ttl %v", ttl)
}
opts := x509.VerifyOptions{Roots: pki.Pool(root), CurrentTime: now, KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}}
opts.Intermediates = x509.NewCertPool()
opts.Intermediates.AddCert(inter.Cert)
if _, err := leaf.Cert.Verify(opts); err != nil {
t.Fatal(err)
}
// An intermediate must not be able to sign another intermediate (MaxPathLen 0).
sub, err := inter.NewIntermediate("Sub", time.Hour, now)
if err != nil {
t.Fatal(err)
}
subLeaf, _ := sub.Issue(pki.LeafSpec{SPIFFEID: "spiffe://shop.example/x", TTL: time.Minute}, now)
opts.Intermediates.AddCert(sub.Cert)
if _, err := subLeaf.Cert.Verify(opts); err == nil {
t.Fatal("path length constraint must reject a third CA level")
}
}
func TestPEMRoundTrip(t *testing.T) {
now := time.Now()
root, _ := pki.NewRoot("Root", time.Hour, now)
k, err := root.KeyPEM()
if err != nil {
t.Fatal(err)
}
back, err := pki.LoadCA(root.CertPEM(), k)
if err != nil || !back.Cert.Equal(root.Cert) {
t.Fatalf("round trip failed: %v", err)
}
}A handshake benchmark and a session-resumption check:
package mtls_test
import (
"crypto/tls"
"net"
"testing"
"time"
"academy/mtls-service-security/mtls"
"academy/mtls-service-security/pki"
)
// listen starts a TLS listener that completes handshakes and closes the connection.
func listen(t testing.TB, cfg *tls.Config) net.Listener {
t.Helper()
ln, err := tls.Listen("tcp", "127.0.0.1:0", cfg)
if err != nil {
t.Fatal(err)
}
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
go func() {
defer c.Close()
if tc, ok := c.(*tls.Conn); ok {
if tc.Handshake() == nil {
_, _ = c.Write([]byte{1}) // TLS 1.3 session tickets travel before this byte
}
_, _ = c.Read(make([]byte, 1)) // wait for the client to close
}
}()
}
}()
t.Cleanup(func() { _ = ln.Close() })
return ln
}
// handshake dials and reads one byte: the client only processes the server's
// NewSessionTicket messages while it reads.
func handshake(t testing.TB, addr string, cfg *tls.Config) *tls.Conn {
t.Helper()
conn, err := tls.Dial("tcp", addr, cfg)
if err != nil {
t.Fatal(err)
}
_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
_, _ = conn.Read(make([]byte, 1))
return conn
}
func benchEnv(t testing.TB) (srvStore, cliStore *mtls.Store) {
t0 := time.Now()
root, _ := pki.NewRoot("Root", time.Hour, t0)
inter, _ := root.NewIntermediate("Issuing", time.Hour, t0)
s, _ := inter.Issue(pki.LeafSpec{SPIFFEID: ordersID, TTL: time.Hour}, t0)
c, _ := inter.Issue(pki.LeafSpec{SPIFFEID: billingID, TTL: time.Hour}, t0)
return mtls.NewStore(s.TLS(), pki.Pool(root), mtls.AllowIDs(billingID)),
mtls.NewStore(c.TLS(), pki.Pool(root), mtls.AllowIDs(ordersID))
}
// BenchmarkHandshake compares what one new connection costs on loopback
// (no network latency, so this is pure CPU and memory, not round trips).
func BenchmarkHandshake(b *testing.B) {
srv, cli := benchEnv(b)
b.Run("mTLS_full_handshake", func(b *testing.B) {
ln := listen(b, srv.ServerConfig())
cfg := cli.ClientConfig()
b.ResetTimer()
for i := 0; i < b.N; i++ {
handshake(b, ln.Addr().String(), cfg).Close()
}
})
b.Run("mTLS_resumed_session", func(b *testing.B) {
ln := listen(b, srv.ServerConfig())
cfg := cli.ClientConfig()
cfg.ClientSessionCache = tls.NewLRUClientSessionCache(8)
c := handshake(b, ln.Addr().String(), cfg) // fills the ticket cache
_ = c.Close()
b.ResetTimer()
resumed := 0
for i := 0; i < b.N; i++ {
c := handshake(b, ln.Addr().String(), cfg)
if c.ConnectionState().DidResume {
resumed++
}
_ = c.Close()
}
b.ReportMetric(float64(resumed)/float64(b.N), "resumed/op")
})
b.Run("oneway_TLS_full_handshake", func(b *testing.B) {
scfg := srv.ServerConfig()
inner, _ := scfg.GetConfigForClient(nil)
one := inner.Clone()
one.ClientAuth = tls.NoClientCert
one.VerifyPeerCertificate = nil
ln := listen(b, one)
cfg := cli.ClientConfig()
cfg.GetClientCertificate = nil
b.ResetTimer()
for i := 0; i < b.N; i++ {
handshake(b, ln.Addr().String(), cfg).Close()
}
})
}
// TestResumedSessionAfterTrustChange logs what a resumed session does after the
// server drops the client's root from its bundle. The result is logged, not
// asserted, because it depends on the Go version.
func TestResumedSessionAfterTrustChange(t *testing.T) {
now := time.Now()
root, _ := pki.NewRoot("Root", time.Hour, now)
other, _ := pki.NewRoot("Other", time.Hour, now)
sLeaf, _ := root.Issue(pki.LeafSpec{SPIFFEID: ordersID, TTL: time.Hour}, now)
cLeaf, _ := root.Issue(pki.LeafSpec{SPIFFEID: billingID, TTL: time.Hour}, now)
srv := mtls.NewStore(sLeaf.TLS(), pki.Pool(root), mtls.AllowIDs(billingID))
cli := mtls.NewStore(cLeaf.TLS(), pki.Pool(root, other), mtls.AllowIDs(ordersID))
ln := listen(t, srv.ServerConfig())
cfg := cli.ClientConfig()
cfg.ClientSessionCache = tls.NewLRUClientSessionCache(8)
handshake(t, ln.Addr().String(), cfg).Close()
// The server now trusts only "other" and presents a certificate from it.
newLeaf, _ := other.Issue(pki.LeafSpec{SPIFFEID: ordersID, TTL: time.Hour}, now)
srv.Set(newLeaf.TLS(), pki.Pool(other))
conn, err := tls.Dial("tcp", ln.Addr().String(), cfg)
if err != nil {
t.Logf("after trust change: dial error=%v", err)
return
}
_ = conn.SetReadDeadline(time.Now().Add(time.Second))
_, err = conn.Read(make([]byte, 1))
t.Logf("after trust change: DidResume=%v, first read error=%v", conn.ConnectionState().DidResume, err)
_ = conn.Close()
}A runnable scenario, and a command-line CA for the lab:
// Command demo runs a small mTLS scenario in one process and prints what each
// handshake did: allowed caller, caller without a certificate, a valid
// certificate with the wrong identity, an expired certificate, and a hot rotation.
package main
import (
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"time"
"academy/mtls-service-security/mtls"
"academy/mtls-service-security/pki"
)
const (
orders = "spiffe://shop.example/ns/prod/sa/orders"
billing = "spiffe://shop.example/ns/prod/sa/billing"
mailer = "spiffe://shop.example/ns/prod/sa/mailer"
)
func main() {
now := time.Now()
root := must(pki.NewRoot("Shop Root CA", 24*time.Hour, now))
issuing := must(root.NewIntermediate("Shop Issuing CA", 12*time.Hour, now))
issue := func(id string, ttl time.Duration) *pki.Leaf {
return must(issuing.Issue(pki.LeafSpec{SPIFFEID: id, TTL: ttl}, now))
}
trust := pki.Pool(root)
server := mtls.NewStore(issue(orders, 15*time.Minute).TLS(), trust, mtls.AllowIDs(billing))
srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id, _ := mtls.CallerID(r)
fmt.Fprintf(w, "orders saw caller %s", id)
}))
srv.TLS = server.ServerConfig()
srv.Config.ErrorLog = log.New(os.Stdout, " server log: ", 0)
srv.StartTLS()
defer srv.Close()
call := func(label string, store *mtls.Store) {
c := &http.Client{Transport: &http.Transport{TLSClientConfig: store.ClientConfig(), DisableKeepAlives: true}}
resp, err := c.Get(srv.URL)
if err != nil {
fmt.Printf("%-34s REFUSED: %v\n", label, short(err))
return
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
fmt.Printf("%-34s %s | %s | server cert %s\n", label, resp.Status, b,
resp.TLS.PeerCertificates[0].SerialNumber.Text(16)[:8])
}
mk := func(id string, ttl time.Duration) *mtls.Store {
return mtls.NewStore(issue(id, ttl).TLS(), trust, mtls.AllowIDs(orders))
}
call("billing (allowed)", mk(billing, 15*time.Minute))
call("mailer (valid cert, not allowed)", mk(mailer, 15*time.Minute))
anon := mk(billing, 15*time.Minute)
cfg := anon.ClientConfig()
cfg.GetClientCertificate = nil
c := &http.Client{Transport: &http.Transport{TLSClientConfig: cfg}}
if _, err := c.Get(srv.URL); err != nil {
fmt.Printf("%-34s REFUSED: %v\n", "no client certificate", short(err))
}
late := mk(billing, 15*time.Minute)
late.Now = func() time.Time { return now.Add(time.Hour) } // client believes it is one hour later
call("billing, expired (client clock +1h)", late)
server.Set(issue(orders, 15*time.Minute).TLS(), trust) // hot rotation, listener untouched
call("billing after server rotation", mk(billing, 15*time.Minute))
}
func short(err error) string {
s := err.Error()
if len(s) > 110 {
s = s[:110] + "..."
}
return s
}
func must[T any](v T, err error) T {
if err != nil {
panic(err)
}
return v
}// Command minica is a tiny private CA for labs. The first run creates a root
// under -dir; every run issues one short-lived leaf for a SPIFFE ID.
//
// go run ./cmd/minica -dir /tmp/pki -id spiffe://shop.example/ns/prod/sa/orders -dns orders.internal.example -ttl 15m
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"academy/mtls-service-security/pki"
)
func main() {
dir := flag.String("dir", "pki", "output directory")
id := flag.String("id", "", "SPIFFE ID of the workload (required)")
dns := flag.String("dns", "", "comma separated DNS SANs")
ttl := flag.Duration("ttl", 15*time.Minute, "leaf lifetime")
flag.Parse()
if *id == "" {
fmt.Fprintln(os.Stderr, "minica: -id is required")
os.Exit(2)
}
if err := run(*dir, *id, *dns, *ttl); err != nil {
fmt.Fprintln(os.Stderr, "minica:", err)
os.Exit(1)
}
}
func run(dir, id, dns string, ttl time.Duration) error {
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
now := time.Now()
ca, err := loadOrCreate(dir, now)
if err != nil {
return err
}
var names []string
if dns != "" {
names = strings.Split(dns, ",")
}
leaf, err := ca.Issue(pki.LeafSpec{SPIFFEID: id, DNSNames: names, TTL: ttl}, now)
if err != nil {
return err
}
certPEM, keyPEM, err := leaf.PEM()
if err != nil {
return err
}
base := filepath.Join(dir, filepath.Base(id))
if err := os.WriteFile(base+".crt", certPEM, 0o644); err != nil {
return err
}
if err := os.WriteFile(base+".key", keyPEM, 0o600); err != nil {
return err
}
fmt.Printf("issued %s valid until %s -> %s.crt, %s.key\n", id, leaf.Cert.NotAfter.Format(time.RFC3339), base, base)
return nil
}
func loadOrCreate(dir string, now time.Time) (*pki.CA, error) {
certPath, keyPath := filepath.Join(dir, "ca.crt"), filepath.Join(dir, "ca.key")
if c, err := os.ReadFile(certPath); err == nil {
k, err := os.ReadFile(keyPath)
if err != nil {
return nil, err
}
return pki.LoadCA(c, k)
}
ca, err := pki.NewRoot("Lab Root CA", 30*24*time.Hour, now)
if err != nil {
return nil, err
}
k, err := ca.KeyPEM()
if err != nil {
return nil, err
}
if err := os.WriteFile(keyPath, k, 0o600); err != nil {
return nil, err
}
return ca, os.WriteFile(certPath, ca.CertPEM(), 0o644)
}The Go angle
Go's standard library is a complete mTLS toolkit. crypto/tls has the handshake and the hooks (GetCertificate, GetClientCertificate, GetConfigForClient, VerifyPeerCertificate, VerifyConnection), crypto/x509 has chain building, ExtKeyUsage, URIs and CertPool, and net/http accepts a *tls.Config on both http.Server and http.Transport. The same config feeds gRPC (credentials.NewTLS). Three details deserve attention. First, tls.Config is copied when a server starts and must not be mutated afterwards; that is why rotation goes through callbacks that read an atomic pointer. Second, the Go documentation says VerifyPeerCertificate "is not invoked on resumed connections", including connections resumed across configs returned by GetConfigForClient, and advises VerifyConnection instead; this chapter's code runs its checks in VerifyConnection on both sides, and a Store.Set builds a new server config and therefore new ticket keys, so sessions made before a rotation are not resumed. Third, InsecureSkipVerify: true is dangerous by name and correct here only because the replacement verification is complete; if you copy the pattern keep the chain check, the key-usage check and the identity check together. Production code often uses github.com/spiffe/go-spiffe/v2, whose tlsconfig package does the same with a Workload API source.
Laravel
Example: a client certificate, verified TLS to the database and cache, a service token
PHP does not terminate TLS itself: PHP-FPM sits behind NGINX or a mesh sidecar, so the server side of mTLS is the proxy's job, and the application reads the verified identity from a trusted header. The client side is real code: Laravel's HTTP client passes Guzzle options (cert, ssl_key, verify) through withOptions, the pgsql connection takes sslmode, sslcert, sslkey and sslrootcert (the connector copies exactly those four into the PDO DSN), and Laravel's Redis connection takes 'scheme' => 'tls'.
<?php
// config/mtls.php: where this service keeps its identity and whom it trusts.
// The files are written by the platform (cert-manager, SPIRE helper, Vault agent),
// never generated by the application.
return [
'cert' => env('MTLS_CERT', '/var/run/identity/tls.crt'), // leaf + intermediates
'key' => env('MTLS_KEY', '/var/run/identity/tls.key'),
'ca' => env('MTLS_CA', '/var/run/identity/ca.crt'), // trust bundle
'peers' => [
'orders' => [
'base_url' => env('ORDERS_URL', 'https://orders.internal.example:8443'),
'spiffe_id' => 'spiffe://shop.example/ns/prod/sa/orders',
],
],
// Callers this service accepts, by SPIFFE ID (set by the sidecar in X-Forwarded-Client-Cert).
'allowed_callers' => [
'spiffe://shop.example/ns/prod/sa/billing',
],
'service_tokens' => [
'issuer' => env('SERVICE_TOKEN_ISSUER', 'https://sts.internal.example'),
'audience' => env('SERVICE_TOKEN_AUDIENCE', 'orders'),
'jwks_public_key' => env('SERVICE_TOKEN_PUBLIC_KEY_PATH', '/var/run/identity/sts.pub'),
],
];<?php
namespace App\Services;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
/**
* Calls the orders service over mutual TLS.
*
* Guzzle (under Laravel's HTTP client) options used here:
* - 'cert' client certificate (PEM; may hold leaf + intermediates)
* - 'ssl_key' the matching private key
* - 'verify' CA bundle used to verify the server; NEVER false
*
* PHP-FPM re-reads the files for every new connection, so rotation by the
* platform needs no reload. Octane keeps workers alive, but cURL still opens
* a new TLS connection per request unless a handle is reused: restart workers
* (or call Octane's reload) if you cache the PendingRequest.
*/
final class OrdersClient
{
public function http(): PendingRequest
{
return Http::baseUrl(config('mtls.peers.orders.base_url'))
->withOptions([
'cert' => config('mtls.cert'),
'ssl_key' => config('mtls.key'),
'verify' => config('mtls.ca'),
])
->connectTimeout(1)
->timeout(3)
->acceptJson();
}
public function find(int $orderId): Response
{
return $this->http()->get("/orders/{$orderId}")->throw();
}
}<?php
// Excerpt of config/database.php. The pgsql connector passes sslmode, sslcert,
// sslkey and sslrootcert to the PDO DSN (Illuminate\Database\Connectors\PostgresConnector).
return [
'connections' => [
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', 'postgres.internal.example'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'orders'),
'username' => env('DB_USERNAME', 'orders'),
'password' => env('DB_PASSWORD', ''),
// verify-full: check the chain AND that the host name matches the server certificate.
'sslmode' => 'verify-full',
'sslrootcert' => env('DB_SSLROOTCERT', '/var/run/identity/ca.crt'),
// Client certificate: the server's pg_hba.conf line says "hostssl ... cert" or clientcert=verify-full.
'sslcert' => env('DB_SSLCERT', '/var/run/identity/tls.crt'),
'sslkey' => env('DB_SSLKEY', '/var/run/identity/tls.key'),
],
],
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'default' => [
// 'scheme' => 'tls' is documented for Laravel Redis connections.
'scheme' => 'tls',
'host' => env('REDIS_HOST', 'redis.internal.example'),
'port' => env('REDIS_PORT', '6380'),
'password' => env('REDIS_PASSWORD'),
'database' => 0,
// PHP stream SSL context options (phpredis 'context'): verify the server and present a client certificate.
'context' => [
'stream' => [
'verify_peer' => true,
'verify_peer_name' => true,
'cafile' => env('REDIS_CA', '/var/run/identity/ca.crt'),
'local_cert' => env('REDIS_CERT', '/var/run/identity/tls.crt'),
'local_pk' => env('REDIS_KEY', '/var/run/identity/tls.key'),
],
],
],
],
];The two middleware classes are the server side. RequireServiceIdentity reads the SPIFFE ID from X-Forwarded-Client-Cert (written by Envoy or the mesh sidecar) and applies an allow list; VerifyServiceToken verifies a JWT's signature, issuer and audience when mTLS is not available on a hop.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Authorization by service identity. The TLS handshake was terminated by a
* sidecar or proxy (Envoy, NGINX, an Istio waypoint) that put the verified
* client certificate in X-Forwarded-Client-Cert (XFCC), e.g.
* By=spiffe://shop.example/ns/prod/sa/orders;Hash=...;URI=spiffe://shop.example/ns/prod/sa/billing
*
* This header is only trustworthy if (a) the proxy sets it itself and strips any
* value sent by the caller, and (b) nothing can reach this app except through
* the proxy (a NetworkPolicy, or the app listening on localhost only).
*/
final class RequireServiceIdentity
{
public function handle(Request $request, Closure $next, string ...$extraCallers): Response
{
$caller = $this->callerFromXfcc((string) $request->header('X-Forwarded-Client-Cert'));
if ($caller === null) {
return response()->json(['error' => 'no verified service identity'], 401);
}
$allowed = [...config('mtls.allowed_callers', []), ...$extraCallers];
if (! in_array($caller, $allowed, true)) {
return response()->json(['error' => 'caller not allowed'], 403);
}
$request->attributes->set('service_identity', $caller);
return $next($request);
}
private function callerFromXfcc(string $header): ?string
{
// Only the first element is the immediate peer; later elements are upstream hops.
$first = explode(',', $header)[0] ?? '';
foreach (explode(';', $first) as $pair) {
if (str_starts_with($pair, 'URI=')) {
$uri = substr($pair, 4);
return str_starts_with($uri, 'spiffe://') ? $uri : null;
}
}
return null;
}
}<?php
namespace App\Http\Middleware;
use Closure;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
/**
* A service token (JWT issued by an internal STS, or a JWT-SVID) proves who is
* calling and for whom the token was minted. The audience check is the part
* people forget: without it, a token meant for service A is accepted by service B.
*
* Requires: composer require firebase/php-jwt
*/
final class VerifyServiceToken
{
public function handle(Request $request, Closure $next): Response
{
$token = $request->bearerToken();
if ($token === null) {
return response()->json(['error' => 'missing service token'], 401);
}
$cfg = config('mtls.service_tokens');
try {
// The algorithm is fixed by the verifier, never taken from the token header.
$claims = JWT::decode($token, new Key(file_get_contents($cfg['jwks_public_key']), 'RS256'));
} catch (Throwable) {
return response()->json(['error' => 'invalid token'], 401); // signature, exp, nbf
}
$audiences = (array) ($claims->aud ?? []);
if (($claims->iss ?? null) !== $cfg['issuer'] || ! in_array($cfg['audience'], $audiences, true)) {
return response()->json(['error' => 'wrong issuer or audience'], 403);
}
$request->attributes->set('service_subject', $claims->sub ?? null);
return $next($request);
}
}<?php
namespace Tests\Feature;
use App\Http\Middleware\RequireServiceIdentity;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;
class ServiceIdentityTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
config(['mtls.allowed_callers' => ['spiffe://shop.example/ns/prod/sa/billing']]);
Route::get('/internal/orders', fn () => 'ok')->middleware(RequireServiceIdentity::class);
}
public function test_known_caller_is_allowed(): void
{
$this->withHeader('X-Forwarded-Client-Cert', 'By=spiffe://shop.example/ns/prod/sa/orders;URI=spiffe://shop.example/ns/prod/sa/billing')
->get('/internal/orders')->assertOk();
}
public function test_missing_identity_is_401(): void
{
$this->get('/internal/orders')->assertStatus(401);
}
public function test_other_identity_is_403(): void
{
$this->withHeader('X-Forwarded-Client-Cert', 'URI=spiffe://shop.example/ns/prod/sa/mailer')
->get('/internal/orders')->assertStatus(403);
}
}The Laravel angle
Laravel's Http facade wraps Guzzle, and the documented route to Guzzle options is Http::withOptions([...]) (or globalOptions in a service provider for every outgoing request). Never set 'verify' => false; point verify at the CA bundle. Under PHP-FPM each request is a fresh process state, so reading certificate files on each request means rotation by the platform needs no reload, and connection reuse across requests is limited, which makes handshake cost per request real: put a sidecar or a local proxy that keeps connections warm (or use Octane and a shared handle) if that matters. For the server side use middleware that trusts the identity header only when the app is reachable exclusively through the proxy: X-Forwarded-Client-Cert can be forged by anyone who can connect directly. Laravel Sanctum and Passport solve user and API token authentication; service identity is a separate concern, and JWT verification for service tokens needs a library such as firebase/php-jwt, with the algorithm pinned by the verifier.
Solving the classic problems
"Anything inside the cluster can call anything"
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Mesh with STRICT and deny-by-default AuthorizationPolicy | Enable sidecars or ambient, then one allow policy per service | No code change, uniform | Migration through PERMISSIVE; mesh operations |
In-app mTLS with RequireAndVerifyClientCert plus identity policy | The Go code of this chapter | No mesh dependency | Each language needs the library; rotation by every team |
| NetworkPolicy only | Label-based allow lists | Cheap, no certificates | No identity, no encryption, coarse |
"Certificates expire and take us down"
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Short leaves with automatic renewal at half-life | cert-manager, SPIRE, mesh | Renewal is exercised hourly | Issuer must be highly available |
| Expiry metric and alert | Export not_after from every workload and CA; alert at 25% left | Warns before the outage | Needs the inventory to be complete |
| Hot reload | GetCertificate reads a store | No restart | Must be implemented in every client and server |
| CA expiry calendar | Track roots and intermediates separately | Catches the 365-day trust anchor | Manual discipline |
"We need to move to mTLS without breaking clients"
1 deploy sidecars / certificates everywhere; mode PERMISSIVE (accept plaintext and mTLS)
2 measure: which calls still arrive in plaintext? (Istio telemetry: connection_security_policy = none)
3 fix or exempt each plaintext caller; exempt by port with portLevelMtls: DISABLE if truly needed
4 switch namespace by namespace to STRICT, watching 503 rates
5 add AuthorizationPolicy: first ALLOW for known callers, then deny-by-default"We rotated the CA and half the fleet fell over"
Follow the four phases in Dual trust. Verify between phases that every workload reports the new bundle hash; do not time the phases with a calendar alone.
"A partner's certificate was leaked"
Revoke at the CA (publish a new CRL, or have the OCSP responder answer revoked), make sure the edge fetches CRLs frequently, disable the partner's account mapping as the fast path, and issue a new certificate. Prefer partner certificates with a lifetime of weeks if the partner can automate renewal (ACME or a private equivalent).
"The proxy terminated TLS and the app lost the identity"
Re-originate mTLS from the proxy to the app and keep the identity in the connection, or forward it in a header the proxy sets and sanitises (x-forwarded-client-cert), and bind the app to the proxy only. A JWT or a signed internal header survives hops the certificate cannot.
Choosing
| Situation | Recommended control | Extra technique | Reason |
|---|---|---|---|
| Kubernetes, many services, multiple languages | Mesh mTLS (Istio ambient or Linkerd), STRICT, AuthorizationPolicy | SPIRE if you need identity beyond the cluster | Uniform, no per-language code |
| A few Go or JVM services, no cluster | In-app mTLS with a shared library and a private CA | Vault PKI or cert-manager equivalent for issuance | Smallest moving parts |
| Calls through a queue or an L7 proxy that terminates TLS | Service token with aud, short exp | mTLS on each hop; sender-constrained tokens (RFC 8705) | Identity must survive the hop |
| Public API for developers | API key for quota plus OAuth for identity | Rate limits, signed webhooks (HMAC) | Keys are not identity |
| B2B partner API | Edge mTLS with a partner CA | CRL or OCSP, per-partner policy, IP allowlist as an extra layer | Strong identity under partner key handling you do not control |
| Calling AWS services | IAM role with SigV4 (done by the SDK) | VPC endpoints | Native identity |
| Database and broker access | Client certificate plus role mapping, verify-full | Short-lived certs from Vault or cert-manager | A leaked password alone is not enough |
| Multi-cluster or multi-cloud | SPIFFE federation or a shared issuer per environment | Separate trust domains per environment | No shared root between production and staging |
| Legacy workload that cannot hold a key | Sidecar or ingress proxy in front | NetworkPolicy to bind it to the proxy | Gives identity at the edge of the legacy app |
In architecture: from a single process to a distributed system
Monolith: one process, one database
There is no service-to-service traffic to secure. The connections that exist are app to database and app to cache: use sslmode=verify-full (Laravel pgsql options above) and a database role with minimum rights; add a client certificate if the database supports it. The first real mTLS decision is the admin plane and the background worker, which are already a second process.
Modular monolith: boundaries without the network
Modules call each other in-process, so authorization is a code-level policy (module A may call module B's public interface). The only network hops are to the database, cache and queue: use TLS to each, and give workers and web processes different database roles so the worker identity is distinct. The identity design is worth doing now because splitting a module out later makes it a service with that identity.
Microservices: every arrow is a decision
An order flow has checkout -> orders -> payments, orders -> inventory, an async orders -> queue -> mailer, and a partner call from payments to an acquirer.
checkout --mTLS--> orders --mTLS--> payments --mTLS(partner CA, client cert)--> acquirer
|--mTLS--> inventory
'--TLS + SASL/EXTERNAL--> broker --TLS--> mailer
policy: orders accepts checkout (POST /orders) and billing (GET /orders*); payments accepts orders only
the message carries a service token (aud=mailer) because the broker hop ends the mTLS identityEvery synchronous arrow is mTLS with an allow list; the queue hop needs a token or a signed message because the original certificate stops at the broker; the partner hop uses a certificate from the partner's CA kept in a separate store with its own rotation and revocation checks. One failure budget is shared by every hop: a broken trust bundle is a cascading failure (Cascading Failures), so roll out trust changes gradually and keep timeouts tight (Timeouts, Retries & Jitter).
Distributed data: replicas, caches, regions
Replication links (PostgreSQL streaming replication, Kafka inter-broker, Redis replicas) need TLS and client certificates of their own, with identities that only replicas and brokers hold. Caches in front of a service make authorization a cache-key problem: never serve a cached response to a caller whose identity differs from the one that filled the cache unless the response is public. Across regions the CA is the single point whose outage shows up everywhere: run the issuer in each region (intermediates per region, one offline root) so a region can keep issuing when the others are unreachable; and use separate trust domains, federated, between clouds or between production and a partner.
Scaling path: 1x, 10x, 100x
| Scale | What you run | Identity and rotation | What breaks first |
|---|---|---|---|
| 1x: a few services | TLS with a private CA and shared library, certificates from cert-manager or Vault | Leaves of days; manual bundle | A forgotten expiry date |
| 10x: dozens of services, several teams | Mesh (sidecar or ambient) with STRICT; AuthorizationPolicy per service | Leaves of 24 h; automatic | PERMISSIVE left on forever; policies nobody owns |
| 100x: hundreds of services, several clusters or clouds | SPIFFE and SPIRE with federation, per-region issuers, policy as code with tests | Leaves of 1 h; bundle rollout monitored | Issuer capacity and availability; bundle propagation delay; policy sprawl |
Lab: issue, connect, break, rotate, measure
Everything below was run on one machine except where marked "expected, not run".
Experiment 1: run the scenario and the tests (run)
cd docs/snippets/system-design/mtls-service-security/go
go run ./cmd/demo
go test -race ./...Output of go run ./cmd/demo (ports vary per run):
billing (allowed) 200 OK | orders saw caller spiffe://shop.example/ns/prod/sa/billing | server cert 595407e9
server log: http: TLS handshake error from 127.0.0.1:65422: mtls: peer identity not allowed: spiffe://shop.example/ns/prod/sa/mailer
mailer (valid cert, not allowed) REFUSED: Get "https://127.0.0.1:65420": remote error: tls: bad certificate
server log: http: TLS handshake error from 127.0.0.1:65423: tls: client didn't provide a certificate
no client certificate REFUSED: Get "https://127.0.0.1:65420": remote error: tls: certificate required
billing, expired (client clock +1h) REFUSED: Get "https://127.0.0.1:65420": x509: certificate has expired or is not yet valid: current time 2026-11-26T05:1...
server log: http: TLS handshake error from 127.0.0.1:65424: remote error: tls: bad certificate
billing after server rotation 200 OK | orders saw caller spiffe://shop.example/ns/prod/sa/billing | server cert 40c70910How to read it. The allowed caller gets 200 and the server sees its SPIFFE ID. The mailer has a perfectly valid certificate from the same CA and is refused during the handshake by the identity policy, so the server never reads an HTTP request. A client with no certificate gets certificate required. A client whose clock is an hour ahead sees the server's 15-minute certificate as expired. After server.Set(...) the next connection shows a different server certificate serial (595407e9 became 40c70910) with no restart. go test -race ./... passes (13 tests in the mtls package plus the pki tests).
Experiment 2: issue short-lived certificates and read them (run)
go run ./cmd/minica -dir /tmp/pki -id spiffe://shop.example/ns/prod/sa/orders -dns orders.internal.example -ttl 15m
openssl x509 -in /tmp/pki/orders.crt -noout -text | grep -A1 -E 'Subject Alt|Extended Key|Not (Before|After)'issued spiffe://shop.example/ns/prod/sa/orders valid until 2026-11-26T00:49:00Z -> /tmp/pki/orders.crt, /tmp/pki/orders.key
Not Before: Nov 26 00:33:00 2026 GMT
Not After : Nov 26 00:49:00 2026 GMT
TLS Web Server Authentication, TLS Web Client Authentication
X509v3 Subject Alternative Name: critical
DNS:orders.internal.example, URI:spiffe://shop.example/ns/prod/sa/ordersThe certificate lives 16 minutes in total: 15 minutes of TTL plus the one-minute NotBefore backdating. The SAN extension is marked critical because the subject is empty (RFC 5280 requires this when the subject is empty).
Experiment 3: measure the handshake (run)
go test ./mtls -run xxx -bench Handshake -benchtime 2s -count 3cpu: Apple M4 Pro
BenchmarkHandshake/mTLS_full_handshake-12 2664 871465 ns/op
BenchmarkHandshake/mTLS_full_handshake-12 3098 807288 ns/op
BenchmarkHandshake/mTLS_full_handshake-12 3015 804234 ns/op
BenchmarkHandshake/mTLS_resumed_session-12 3806 620506 ns/op 1.000 resumed/op
BenchmarkHandshake/mTLS_resumed_session-12 3922 636261 ns/op 1.000 resumed/op
BenchmarkHandshake/mTLS_resumed_session-12 3853 637690 ns/op 1.000 resumed/op
BenchmarkHandshake/oneway_TLS_full_handshake-12 5143 453159 ns/op
BenchmarkHandshake/oneway_TLS_full_handshake-12 5364 454283 ns/op
BenchmarkHandshake/oneway_TLS_full_handshake-12 5451 464645 ns/opHow to read it. Each operation is a full connect, handshake and close on loopback with both ends in one process, so the figures are CPU for client plus server and carry no network latency. A one-way handshake is about 0.46 ms, a full mutual handshake about 0.81 ms (an extra certificate chain to send, parse and verify, one more signature and verification, and our own second verification in VerifyConnection), a resumed mutual session about 0.63 ms (the certificate exchange is skipped, but VerifyConnection still re-verifies the chain against the current bundle and policy, which is the price of noticing a trust change on resumed sessions). The point is the order of magnitude: mTLS costs well under a millisecond of CPU per new connection, which is why connection reuse matters more than the choice between TLS and mTLS.
Experiment 4: the failure modes with openssl (expected, not run)
# server: require a client certificate (OpenSSL)
openssl s_server -accept 8443 -cert orders.crt -key orders.key -CAfile ca.crt -Verify 1 -verify_return_error -www
# no certificate
openssl s_client -connect localhost:8443 -CAfile ca.crt </dev/null
# expected: handshake fails with "alert certificate required" (TLS 1.3)
# with the billing certificate
openssl s_client -connect localhost:8443 -cert billing.crt -key billing.key -CAfile ca.crt </dev/null
# expected: "Verify return code: 0 (ok)"
# a certificate from another CA
openssl s_client -connect localhost:8443 -cert rogue.crt -key rogue.key -CAfile ca.crt </dev/null
# expected: alert "unknown ca" or "bad certificate", server prints "certificate verify failed"The Apple-provided openssl on this machine is LibreSSL 3.3.6, whose flags and messages differ from OpenSSL 3, so this experiment is labelled expected, not run.
Experiment 5: Istio STRICT and an AuthorizationPolicy (expected, not run)
kubectl apply -f peer-auth-strict.yaml # PeerAuthentication mode STRICT, namespace prod
kubectl -n prod exec deploy/sleep -- curl -s -o /dev/null -w '%{http_code}\n' http://orders:8080/orders
# expected from a pod WITHOUT a sidecar (namespace legacy): connection reset (000)
# expected from a meshed pod with an unauthorised ServiceAccount: 403 "RBAC: access denied"
# expected from sa/billing: 200
istioctl x describe pod -n prod orders-xxxxx # lists the effective PeerAuthentication and AuthorizationPolicyExperiment 6: Laravel client against a fake (expected, not run)
php artisan test --filter ServiceIdentityTest
# expected: 3 tests pass (known caller 200, no identity 401, other identity 403)Common misconceptions
| Belief | Reality |
|---|---|
| "TLS inside the cluster is enough" | One-way TLS authenticates the server only; the server still does not know who the client is |
| "A valid client certificate means the caller is allowed" | It means the caller holds a certificate from a CA you trust; you still need an identity-based policy |
| "We need revocation (CRL/OCSP) for internal mTLS" | Usually not: short lifetimes make revocation unnecessary inside; keep CRL/OCSP for long-lived partner certificates |
"sslmode=require verifies the database" | It encrypts only; verify-full checks chain and host name |
"InsecureSkipVerify: true is always a bug" | It is only safe when a custom verifier replaces the whole check; otherwise it is a bug |
| "JWT replaces mTLS" | A bearer token can be replayed by anyone who steals it; mTLS proves possession of a key |
| "A service mesh encrypts everything" | Only meshed, STRICT traffic; the app-to-sidecar hop and out-of-mesh destinations are not covered |
| "PERMISSIVE is a safe default" | It is the migration state; it accepts plaintext and leaves the mesh unenforced |
| "Common Name is the service identity" | Use a SAN (a SPIFFE URI SAN); CN is legacy and free text |
| "An internal CA can share the public CA bundle" | Trust only your own roots, or any holder of a public certificate passes the chain check |
| "Rotating a CA is like rotating a leaf" | Peers verify against bundles; use dual trust and four phases |
| "Short-lived certificates need a restart on renewal" | Not if the process reads certificates through GetCertificate/GetClientCertificate or an agent-managed file |
| "An API key identifies the calling service" | It identifies a key holder; keys are shared, long-lived and leak |
Cheat sheet
| Topic | What to remember |
|---|---|
| Purpose of mTLS | Authenticate both ends of every service call; identity comes from the certificate, not the address |
| Server config (Go) | ClientAuth: RequireAndVerifyClientCert, ClientCAs, MinVersion: TLS13, identity check in VerifyPeerCertificate |
| Client config (Go) | Verify chain against the private bundle, require serverAuth, check the SPIFFE ID; never verify => false |
| Identity | One URI SAN: spiffe://trust-domain/path; derive it from the platform (ServiceAccount), not from the workload |
| CA design | Offline root, online intermediate (MaxPathLen 0), per-environment CAs, ECDSA P-256 leaves |
| Lifetime | Minutes to hours; renew at half-life; alert at 25% remaining |
| CA rotation | Add the new root, issue from the new CA, wait one TTL, remove the old root |
| Mesh | Istio PeerAuthentication STRICT (PERMISSIVE only while migrating); Linkerd 24 h certs, anchor 365 days by default; Consul intentions |
| Sidecar vs ambient | Per-pod proxy and full L7 versus per-node ztunnel for L4 and optional waypoint for L7 |
| Tokens | Verify signature, iss, aud, exp; pin the algorithm; keep lifetimes short |
| Weak controls | IP allowlists and API keys are layers, not identity |
| Authorization | Deny by default, allow by caller identity, method and path; AuthorizationPolicy, OPA or middleware |
| Edge mTLS | Partner CA, CRL or OCSP, strip and re-set identity headers, bind the app to the proxy |
| Data stores | PostgreSQL clientcert=verify-full and sslmode=verify-full; Kafka ssl.client.auth=required; RabbitMQ EXTERNAL with verify_peer |
| Performance | New mTLS connection ~0.8 ms CPU (both ends) in our benchmark; reuse and resumption matter more than the choice of mTLS |
| Debugging | openssl s_client -connect host:port -cert -key -CAfile; openssl verify -untrusted; read the server log first |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why is a source IP not an identity inside a cluster? Must-know
Answer
Answer: Addresses are reused after every deploy, shared behind NAT, and reachable by any compromised workload in the same flat network. An attacker who controls one pod controls its address and can reach every service that trusts the network position.
2 — What does the server check in RequireAndVerifyClientCert and what does it not check? Important
Answer
Answer: It checks that the client chain leads to a root in ClientCAs, that validity and key usage fit, and that the client proved possession of the key. It does not check whether this particular identity may call this service; that needs VerifyPeerCertificate, middleware or a mesh policy.
3 — Why must a SPIFFE X.509-SVID contain exactly one URI SAN? Good to know
Answer
Answer: The standard says several SPIFFE IDs make auditing and authorization logic ambiguous and complicate validation. A verifier extracts one ID and checks it against policy; with two it would have to guess which one the caller meant.
4 — A fleet fails with unknown certificate authority right after you started issuing from a new CA. What went wrong? Important
Answer
Answer: Phase 2 of dual trust was skipped or incomplete: some peers did not have the new root in their trust bundle when the first leaves from the new CA appeared. Roll back issuance, distribute and verify the bundle, then proceed.
5 — Why do short-lived certificates usually remove the need for CRLs inside the mesh? Important
Answer
Answer: A stolen key is only useful until the certificate expires, which is minutes to hours. Maintaining, distributing and enforcing revocation data for thousands of workloads is harder than renewing reliably. Long-lived partner certificates still need CRL or OCSP.
6 — What is the difference between PERMISSIVE and STRICT in Istio? Must-know
Answer
Answer: PERMISSIVE accepts both mTLS and plaintext, so it allows migration; STRICT accepts only mTLS. A mesh left in PERMISSIVE does not protect against a caller that simply uses plaintext.
7 — When is a service token with an audience better than mTLS? Important
Answer
Answer: When the identity must survive a hop that terminates TLS (an L7 proxy, a CDN, a message broker) or be carried inside a message. The token's aud stops it being accepted by another service.
8 — Why is sslmode=require not enough for PostgreSQL? Must-know
Answer
Answer: require encrypts but does not verify the server certificate, so a man in the middle with any certificate passes. verify-full verifies the chain and that the host name matches the certificate.
9 — Where can VerifyPeerCertificate not help in Go, and what do you use instead? Good to know
Answer
Answer: It is not invoked on resumed connections. Checks that must hold on every connection go into VerifyConnection, which runs for all connections including resumptions; alternatively disable session tickets or rebuild the config when policy changes.
10 — A certificate-based outage happens at 03:00 every 90 days. What is the likely cause and the fix? Important
Answer
Answer: A leaf with a 90-day lifetime that nothing renews (or a renewal job that fails silently). Fix with automatic renewal at half-life, hot reload, an expiry metric and an alert at 25% remaining life.
11 — Why must the app trust X-Forwarded-Client-Cert only when it is reachable solely through the proxy? Important
Answer
Answer: The header is plain text. If a caller can connect directly, it can send any value. The proxy must also strip inbound copies and set the header from the verified certificate.
12 — What should you monitor for a healthy mTLS estate? Must-know
Answer
Answer: Seconds until expiry for every leaf and CA, issuer availability and latency, handshake failure rate by reason, the fraction of plaintext connections in the mesh, the active trust bundle hash per workload, and clock offset.
Glossary
| Term | Meaning |
|---|---|
| mTLS (mutual TLS) | TLS in which both client and server authenticate with certificates |
| Server certificate | Certificate presented by the server; verified by the client |
| Client certificate | Certificate presented by the client when asked; verified by the server |
| Certificate verification | Chain building, validity, key usage and identity checks |
| SAN (Subject Alternative Name) | X.509 extension listing the names a certificate is valid for (DNS, IP, e-mail, URI) |
| URI SAN | A SAN entry of type URI; carries the SPIFFE ID |
| Service identity | The name that proves which workload is calling |
| SPIFFE | Standard for workload identity names and documents |
| SPIFFE ID | spiffe://trust-domain/path |
| SVID | SPIFFE Verifiable Identity Document: X.509-SVID or JWT-SVID |
| SPIRE | Reference implementation that attests workloads and issues SVIDs |
| Workload attestation | Identifying a workload by selectors such as namespace and ServiceAccount |
| Trust domain | The root of trust and namespace of a SPIFFE deployment |
| Federation | Exchanging trust bundles between trust domains |
| Private CA | A certificate authority operated inside the organisation |
| Intermediate CA | An online CA signed by the root; issues leaves |
| Trust bundle | The root certificates a workload accepts |
| Short-lived certificate | Leaf valid for minutes to hours, replacing revocation |
| Certificate rotation | Replacing a certificate (or CA) with a new one before expiry |
| Hot reload | Using a new certificate for new connections without restarting |
| Dual trust | Trusting old and new roots at once during a CA change |
| Service mesh | Infrastructure that provides mTLS, policy and telemetry between services |
| Sidecar | A proxy running next to each application container |
| Ambient mesh | Istio mode with a per-node ztunnel and optional waypoint proxies instead of sidecars |
| PeerAuthentication | Istio resource setting the mTLS mode (STRICT, PERMISSIVE, DISABLE, UNSET) |
| STRICT / PERMISSIVE | Only mTLS / mTLS and plaintext |
| AuthorizationPolicy | Istio (and Linkerd) resource that allows or denies by identity, method, path |
| Linkerd identity | Linkerd component that issues per-proxy certificates bound to a ServiceAccount |
| Consul Connect | Consul's mTLS service mesh feature, authorized by intentions |
| Service token | A signed token (often a JWT) proving which service calls and for which audience |
Audience (aud) | Claim naming the service a token is meant for |
| Client credentials grant | OAuth 2.0 flow in which a service authenticates as itself to get a token |
| Request signing / SigV4 / HMAC signature | Signing the request (method, path, headers, payload hash, timestamp) with a secret or key |
| API key | A static secret identifying a project or caller; not strong authentication |
| IP allowlist | Restricting callers by source address; weak control |
| Lateral movement | Attacker moving from one compromised system to others |
| Zero trust | Treating no request as trusted by location; verify and authorize each one |
| BeyondProd | Google's cloud-native security model built on service identity and no inherent mutual trust |
| Handshake cost | CPU and latency of establishing a TLS connection |
| Session resumption | Skipping the full handshake with a ticket or PSK |
| TLS offload | Terminating TLS at a proxy or load balancer |
| Certificate expiry outage | Failure because a certificate or CA passed NotAfter |
| Clock skew | Difference between two machines' clocks |
openssl s_client | OpenSSL command-line TLS client for debugging |
clientcert=verify-full | PostgreSQL pg_hba.conf option requiring and matching a client certificate |
sslmode=verify-full | libpq client mode verifying chain and host name |
| Kafka SSL client auth | ssl.client.auth=required with a truststore of client CAs |
| EXTERNAL mechanism | RabbitMQ authentication mechanism taking the identity from the TLS client certificate |
| cert-manager | Kubernetes controller issuing and renewing certificates |
| CSR API | Kubernetes CertificateSigningRequest API (certificates.k8s.io/v1) |
RequireAndVerifyClientCert | Go tls.ClientAuthType that demands and verifies a client certificate |
VerifyPeerCertificate | Go hook for extra checks after normal verification |
GetCertificate / GetClientCertificate | Go hooks choosing the certificate per handshake; used for hot rotation |
| gRPC credentials | Channel credentials (TLS identity) and call credentials (per-RPC tokens) |
| CRL / OCSP | Certificate revocation list / online certificate status protocol |
References
- RFC 8446, The Transport Layer Security (TLS) Protocol Version 1.3: https://www.rfc-editor.org/rfc/rfc8446.html
- RFC 5280, Internet X.509 PKI Certificate and CRL Profile: https://www.rfc-editor.org/rfc/rfc5280.html
- RFC 6749, OAuth 2.0 (client credentials): https://www.rfc-editor.org/rfc/rfc6749.html
- RFC 7523, JWT profile for OAuth 2.0 client authentication: https://www.rfc-editor.org/rfc/rfc7523.html
- RFC 8705, OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens: https://www.rfc-editor.org/rfc/rfc8705.html
- SPIFFE ID and SVID standard: https://github.com/spiffe/spiffe/blob/main/standards/SPIFFE-ID.md
- X509-SVID: https://github.com/spiffe/spiffe/blob/main/standards/X509-SVID.md
- JWT-SVID: https://github.com/spiffe/spiffe/blob/main/standards/JWT-SVID.md
- SPIFFE Workload API: https://github.com/spiffe/spiffe/blob/main/standards/SPIFFE_Workload_API.md
- SPIFFE Federation: https://github.com/spiffe/spiffe/blob/main/standards/SPIFFE_Federation.md
- SPIFFE Trust Domain and Bundle: https://github.com/spiffe/spiffe/blob/main/standards/SPIFFE_Trust_Domain_and_Bundle.md
- SPIFFE concepts: https://spiffe.io/docs/latest/spiffe-about/spiffe-concepts/
- SPIRE concepts: https://spiffe.io/docs/latest/spire-about/spire-concepts/
- SPIRE server configuration reference: https://spiffe.io/docs/latest/deploying/spire_server/
- Istio security concepts: https://istio.io/latest/docs/concepts/security/
- Istio PeerAuthentication reference: https://istio.io/latest/docs/reference/config/security/peer_authentication/
- Istio AuthorizationPolicy reference: https://istio.io/latest/docs/reference/config/security/authorization-policy/
- Istio ambient mode overview: https://istio.io/latest/docs/ambient/overview/
- Linkerd automatic mTLS: https://linkerd.io/2/features/automatic-mtls/
- Consul service mesh (Connect) docs: https://developer.hashicorp.com/consul/docs/connect
- Consul connect internals: https://developer.hashicorp.com/consul/docs/connect/connect-internals
- Envoy TLS (SSL) architecture overview: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/security/ssl
- Envoy HTTP headers (x-forwarded-client-cert): https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_conn_man/headers
- NGINX ngx_http_ssl_module: https://nginx.org/en/docs/http/ngx_http_ssl_module.html
- Google Cloud, BeyondProd: https://cloud.google.com/docs/security/beyondprod
- AWS Signature Version 4: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html
- PostgreSQL, SSL support (server): https://www.postgresql.org/docs/current/ssl-tcp.html
- PostgreSQL, pg_hba.conf: https://www.postgresql.org/docs/current/auth-pg-hba-conf.html
- PostgreSQL, libpq SSL support: https://www.postgresql.org/docs/current/libpq-ssl.html
- PostgreSQL, monitoring statistics (pg_stat_ssl): https://www.postgresql.org/docs/current/monitoring-stats.html
- Apache Kafka, SSL encryption and authentication: https://kafka.apache.org/41/security/encryption-and-authentication-using-ssl/
- RabbitMQ TLS support: https://www.rabbitmq.com/docs/ssl
- RabbitMQ EXTERNAL authentication mechanism (rabbitmq_auth_mechanism_ssl): https://github.com/rabbitmq/rabbitmq-server/tree/main/deps/rabbitmq_auth_mechanism_ssl
- cert-manager documentation: https://cert-manager.io/docs/
- cert-manager Certificate resource: https://cert-manager.io/docs/usage/certificate/
- Kubernetes, Certificates and CertificateSigningRequests: https://kubernetes.io/docs/reference/access-authn-authz/certificate-signing-requests/
- Kubernetes, Manage TLS certificates in a cluster: https://kubernetes.io/docs/tasks/tls/managing-tls-in-a-cluster/
- Go
crypto/tls: https://pkg.go.dev/crypto/tls - Go
crypto/x509: https://pkg.go.dev/crypto/x509 - gRPC authentication guide: https://grpc.io/docs/guides/auth/
- OpenSSL
s_client: https://docs.openssl.org/master/man1/openssl-s_client/ - Let's Encrypt, DST Root CA X3 expiration (September 2021): https://letsencrypt.org/docs/dst-root-ca-x3-expiration-september-2021/
- Laravel 13 HTTP client: https://laravel.com/docs/13.x/http-client
- Laravel 13 database: https://laravel.com/docs/13.x/database
- Laravel 13 Redis: https://laravel.com/docs/13.x/redis
- Laravel framework PostgresConnector (13.x): https://github.com/laravel/framework/blob/13.x/src/Illuminate/Database/Connectors/PostgresConnector.php