Skip to content

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 forGo to
The whole page in four tablesEverything in one minute
Why a private network is not a security boundaryWhy it exists
Where mTLS, SPIFFE and BeyondProd come fromWhere it comes from
What an attacker does with one compromised podLateral movement
Both sides prove who they areMutual TLS
What goes in the certificate: SAN, URI SAN, SPIFFE IDService identity
Root, intermediate, trust bundleA private CA
Why lifetimes of minutes beat revocationShort-lived certificates
Changing the CA without an outageDual trust
SVIDs, attestation, trust domains, federationSPIFFE and SPIRE
Istio, Linkerd, Consul, sidecar, ambientService mesh mTLS
JWTs, client credentials, SigV4, HMAC, API keys, IP allowlistsAlternatives and complements
Identity to policy: AuthorizationPolicy, OPAAuthorization for services
Partners and B2B client certificatesmTLS at the edge
PostgreSQL, Redis, Kafka, RabbitMQDatabases and queues
cert-manager, CSR API, SecretsKubernetes
gRPC channel and call credentialsgRPC credentials
Handshake cost, resumption, offloadPerformance
Expiry outages, clock skewOperational failures
BeyondProd and zero trustZero trust for services
openssl s_client and the error messagesDebugging
Exact knobs and messagesMechanics
CodeGo, Laravel
Classic failures and their fixesSolving the classic problems
Which control for which situationChoosing
Monolith to distributed systemIn architecture
Commands and measured numbersLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The four questions every service-to-service call must answer.

QuestionControl that answers itWeak answerStrong answer
Is anyone listening on the wire?Encryption in transitPlain HTTP inside the VPCTLS 1.3 between every pair of services
Is this really the server I meant to call?Server certificate verificationSkip 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 tokenSource IP, a shared API keyA 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.

StepWhat happensWho does it
1Each workload gets a key pair and a short-lived certificate naming itIssuer (cert-manager, SPIRE, mesh CA, Vault)
2Server sends its chain and asks for a client certificateTLS 1.3 CertificateRequest
3Client sends its chain and proves it holds the keyCertificate and CertificateVerify
4Both verify the chain against the trust bundle and read the identitytls.Config, Envoy, sidecar
5A policy maps identity to allowed operationsAuthorizationPolicy, middleware, OPA

Where mTLS can live, from least to most automatic.

LayerExampleYou writeYou operateTypical lifetime of a leaf
In the applicationGo tls.Config, Laravel Guzzle optionsTLS and verification codeCert files, reloadHours to days
Next to the applicationEnvoy or NGINX sidecar you configureProxy configProxy plus cert agentHours
Service mesh sidecarIstio, Linkerd, Consul ConnectPolicy onlyThe mesh control plane24 hours by default in Linkerd
Ambient or node levelIstio ambient ztunnelPolicy onlyThe mesh, per nodeHours to a day
Platform identitySPIFFE and SPIRE under any of the aboveRegistration entriesSPIRE servers and agents1 hour X.509-SVID by default in SPIRE

Controls that look like security and are not enough.

ControlWhat it really provesWhy it is weak
IP allowlistThe packet arrived from an addressAddresses are shared, reused, spoofable inside a flat network, and change on every deploy
Shared API keyThe caller knows a stringNo 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 subnetOne compromised pod is inside the subnet too
Hostname check onlyThe server's name matchesSays 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 networkTrust a verified identity
Cheap: no certificates, no policyNeeds an issuer, rotation and policy
One compromised pod reaches everythingA compromised pod reaches only what its identity allows
Identity is an IP address that changes on every deployIdentity 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 silentlyFails 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 ​

  1. "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: RequireAnyClientCert and no policy accepts any certificate from any CA.
  2. "Encrypted means authenticated." One-way TLS authenticates the server to the client only. The server still has no idea who the client is.
  3. "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 with Certificate and CertificateVerify, and because the handshake after ServerHello is 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 (the post_handshake_auth extension, 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 403

Real 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.

ControlStops lateral movement?Notes
Firewalls and Kubernetes NetworkPolicyPartlyAllow lists by label or CIDR; coarse, no identity; see Firewalls
mTLS with identity policyYes, per callNeeds issuer, rotation and policy
Service tokens with audienceYes, per callReplayable if stolen; short expiry and sender-constraint help
API key per callerWeaklyStatic, 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) <============================>
billing (client)key + cert + trust bundleorders (server)key + cert + trust bundleClientHello (TLS 1.3, key share)ServerHello, Certificate (chain), CertificateRequest, Finishedclient: verify chain to trust bundle, serverAuth usage, SPIFFE ID of ordersCertificate (chain), CertificateVerify (proves key), Finishedapplication data, encrypted both waysserver: verify chain, clientAuth usage, SPIFFE ID of billingAuthenticatedboth sides hold a verified identityURI SAN spiffe://shop.example/ns/prod/sa/...Authorized?policy: may billing call GET /orders?no rule matches: 403, or handshake refused

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.

ProductHow it requires the client certificateSetting
Go crypto/tls serverFails the handshake without a verifiable client certificateClientAuth: tls.RequireAndVerifyClientCert plus ClientCAs
NGINX (ngx_http_ssl_module)Verifies against a CA file and exposes the result in variablesssl_verify_client on; ssl_client_certificate ca.pem;
EnvoyRequires a client certificate in the downstream TLS contextrequire_client_certificate: true with a validation context
IstioSidecar enforces it per workload, namespace or meshPeerAuthentication mode: STRICT
PostgreSQLRequests a client certificate on hostssl linesclientcert=verify-ca or clientcert=verify-full in pg_hba.conf
RabbitMQRejects connections without a certificatessl_options.verify = verify_peer, ssl_options.fail_if_no_peer_cert = true
Kafka brokerRequests a client certificatessl.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 kindExampleGood forWeakness
DNS SANorders.internal.exampleClients that verify a host name they dialedNames the address, not the workload; shared by every replica and by whatever answers that name
IP SAN10.0.3.17Almost nothing in dynamic environmentsChanges on every reschedule
URI SAN (SPIFFE ID)spiffe://shop.example/ns/prod/sa/ordersService-to-service identity in policyNeeds an issuer that assigns it correctly
Subject CN or OCN=ordersLegacy systems (PostgreSQL cert auth maps the CN, RabbitMQ can use the CN)Free text, no standard structure
Istio principalcluster.local/ns/default/sa/sleepAuthorizationPolicy principalsThe 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).

Root CAoffline, HSM, yearssigns only intermediatesIntermediate CAonline, rotated yearlysigns leaves, MaxPathLen 0Issuer APIcert-manager, SPIRE server,Vault PKI, mesh control planeWorkload agentattests the workload,gets leaf, renews at 1/2 lifewrites files or serves APIService (leaf)URI SAN = identityTTL minutes to hourskey never leaves the podTrust bundleroot certificates onlyold + new during rotationverifies every peer chainsignsissuesCSR / attestationcert + keytrustsdistributed to all
ChoiceOption AOption BPrefer
Root keyOnline, on the issuerOffline, in an HSM or cold storageOffline; the root signs the intermediate once a year
Number of CAsOne CA for everythingOne intermediate per environment or clusterPer environment, so a leak in staging does not trust production
Key typeRSA 2048ECDSA P-256ECDSA P-256 for leaves (smaller, faster handshakes), as in the lab code
Leaf key locationIssuer generates and ships the keyWorkload generates a key and sends a CSRThe workload generates it; the key never leaves the pod
Name constraintsNoneIntermediate limited to the trust domainConstrain 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.

ProductDefault leaf lifetimeRenewalSource of the number
SPIREX.509-SVID 1 h (default_x509_svid_ttl), JWT-SVID 5 m, CA signing key 24 h (ca_ttl)Agent renews through the Workload APISPIRE server configuration reference
Linkerd24 h, bound to the pod's ServiceAccountAutomatic by the proxyLinkerd automatic mTLS docs
cert-managerduration 2160 h (90 days) in the documented example, renewBefore 360 hController renewscert-manager Certificate docs
Kubernetes CSR APIRequest via spec.expirationSeconds, minimum 600 sYou re-submit before expiryKubernetes CSR docs
IstioWorkload certificates rotated by the Istio agent through SDSAutomaticIstio 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.

1. Steady statebundle: old root2. Trust new rootbundle: old + new3. Issue from newleaves renew naturally4. Drop old rootbundle: new onlytime, left to right; leaf TTL = 1 h, so phase 3 lasts at least one TTL plus the renewal marginleaves signed by OLD CAtrust bundle contains NEW rootleaves signed by NEW CAIf phase 2 is skipped: new leaves are rejected by peers that do not trust the new root yet (outage).If phase 4 comes too early: services still holding old leaves are rejected (outage).
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
MistakeSymptomPrevention
Issue from the new CA before every bundle has the new rootx509: certificate signed by unknown authority from some peers onlyPhase 2 must be verified (metrics: bundle hash per workload)
Remove the old root immediatelyWorkloads that have not renewed yet fail with unknown certificate authorityWait one leaf TTL plus a margin
Bundle delivered by a different path than the leavesLeaves renewed, bundle stale for hoursShip bundle and leaf together (same agent, same volume)
Trust anchor with a long, forgotten lifetimeOutage on its expiry dayTrack 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:

TermMeaning
SPIFFE IDspiffe://trust-domain/path, the name of a workload
Trust domainThe 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 APIA local API (gRPC over a Unix socket) from which a workload fetches its SVIDs, rotating bundles and keys without credentials of its own
Trust bundleThe set of root certificates (X.509 authorities) and JWT keys for a trust domain
Node attestationThe SPIRE agent proves what machine it runs on (cloud instance identity document, TPM, join token) and gets an agent SVID
Workload attestationThe agent identifies a calling process by selectors (Kubernetes namespace and ServiceAccount, Unix UID, container image) and matches them to a registration entry
FederationTwo 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-SVIDX.509-SVIDJWT-SVID
Carried byTLS handshakeAuthorization: Bearer header or gRPC metadata
Proof of possessionYes, the handshake signs with the keyNo, a bearer token: whoever holds it can replay it until it expires
AudienceNot applicableRequired aud claim; the verifier must check it
Works through an L7 proxy that terminates TLSNo, identity ends at the proxyYes
Default lifetime in SPIRE1 h5 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.

Control plane: CA + identity (istiod, Linkerd identity, Consul servers, SPIRE server)issues short-lived workload certificates, distributes the trust bundle, pushes policySidecar modelapp Aplain HTTPproxymTLSproxymTLSapp Bplain HTTPAmbient modelapp Ano sidecarztunnelL4 mTLS per nodewaypointoptional, L7 policyWhat the mesh gives and what it does notGives: encryption in transit, workload identity per ServiceAccount, certificate rotation without app changes, deny-by-default policyDoes not give: protection on the pod-local hop (app to its own proxy), end-user authentication, business authorization,protection if the app itself is compromised, mTLS to destinations outside the mesh unless you configure itMode STRICT rejects plaintext; PERMISSIVE accepts both and is the migration state, not the destination
MeshIdentity unitCert lifetimemTLS defaultPolicy objectsData plane
Istio sidecar modeServiceAccount, principal cluster.local/ns/NS/sa/NAMERotated by the Istio agent via Envoy SDSAuto mTLS between sidecars; PERMISSIVE accepts plaintext tooPeerAuthentication, AuthorizationPolicy, RequestAuthenticationEnvoy sidecar per pod
Istio ambient modeSameSameztunnel provides L4 mTLS ("the ztunnel secure overlay handles routing and zero trust security for traffic")AuthorizationPolicy at L4 on ztunnel, L7 on waypointztunnel per node, optional waypoint proxy per namespace or service
LinkerdServiceAccount of the pod24 h, automaticmTLS on by default for meshed TCP trafficServer, AuthorizationPolicy, MeshTLSAuthenticationlinkerd2-proxy sidecar
Consul Connect (Consul service mesh)Service name, SPIFFE-compliant certificatesRotated by ConsulmTLS "is the core"; intentions authorizeService intentions (allow/deny per source and destination)Envoy sidecar or gateway

Istio PeerAuthentication modes:

ModeBehaviourUse
UNSETInherit from parent (namespace, then mesh)Default
DISABLENo tunnel; plaintextPorts that must stay plain (a probe, a legacy client)
PERMISSIVEAccept both mTLS and plaintextMigration state while clients get sidecars
STRICTOnly mTLSTarget 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.

yaml
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*"]
SidecarAmbient
Proxy per pod; adds CPU and memory per pod and a restart on proxy upgradeztunnel per node; the pod needs no change
L7 features everywhereL4 by default; add a waypoint for L7
Mature, widest feature setNewer; the Istio documentation says sidecar and ambient pods can co-exist in one mesh
Per-pod certificate in the sidecar's memoryNode 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.

MechanismWhat it provesReplay / theftTypical useWeakness
mTLS client certificatePeer holds the private key for an identity certified by your CANeeds the key; stolen cert without key is uselessHop-to-hopTerminates at the first proxy that terminates TLS
Service token (JWT) with audienceA trusted issuer vouched that subject S may call audience A until expBearer: replayable until expiryAcross proxies, queues, async hopsMust 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 tokenSame as JWTService to API behind an STSClient 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 forStolen token is useless without the keyHigh-value APIsMore plumbing
Request signing, AWS SigV4The request (method, path, headers, payload hash) was signed with a key derived from a secret; signature includes a timestampReplay limited by timestamp windowAWS APIs, your own signed webhooksBoth sides need the secret (HMAC)
HMAC signature (shared secret)The sender knows the shared secret and the body was not alteredReplay unless nonce/timestampWebhooks (for example X-Signature)Shared secret on both sides; no per-caller identity unless one secret per caller
API keyThe caller knows the keyStatic: valid forever until rotatedPublic APIs for rate limiting and billingNot an identity; leaks in logs and repos; see below
IP allowlistThe packet's source addressSpoofable inside the network, shared NATDefense in depth for third partiesWeakest 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.

WhereExampleStrengthLimit
Mesh policyIstio AuthorizationPolicy with action: ALLOW, from.source.principals, to.operation.methods/paths, when conditions on JWT claimsUniform, no code, audited as configSees 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, testableAnother hop and component to keep available; decision caching
Application middlewareThe Go Authorize middleware and Laravel RequireServiceIdentity in this chapterKnows the business objectEasy to forget on a new route
Database or broker ACLPostgreSQL role mapped from the client certificate; Kafka ACLs on the principalLast line of defenceCoarse

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.

EdgeHow client certificates are enabledHow the backend learns the identity
NGINXssl_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
EnvoyDownstream TLS context with require_client_certificate: true and a validation contextThe x-forwarded-client-cert (XFCC) header: Envoy documentation says a proxy "may choose to sanitize/append/forward" it, controlled by forward_client_cert_details
HAProxybind :443 ssl crt site.pem ca-file partners-ca.pem verify required crl-file crl.pemssl_c_s_dn, ssl_c_verify fetched into headers
AWS ALBmTLS verify mode with a trust store (and optional CRL)X-Amzn-Mtls-Clientcert-* headers
AWS API GatewayCustom domain with a truststore in S3Request context identity fields
CloudflareAPI Shield mTLS with client certificatesCloudflare 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".

SystemServer verifies clientIdentity taken fromClient verifies serverServer config key
PostgreSQLhostssl line with clientcert=verify-full (or the cert method); the CA in ssl_ca_fileCN by default, or the whole DN with clientname=DN; mapped by pg_ident.confsslmode=verify-full and sslrootcertpg_hba.conf, postgresql.conf
Redistls-auth-clients yesNot mapped to a Redis user by default; ACLs are by user and passwordtls-ca-cert-file, client verifies with its CAredis.conf
Kafkassl.client.auth=required (or requested) with a truststore holding the CAs that signed client keysThe certificate's distinguished name becomes the principal, usable in ACLsClient truststore holds the broker's CAserver.properties
RabbitMQssl_options.verify = verify_peer, fail_if_no_peer_cert = true, and the EXTERNAL authentication mechanismssl_cert_login_from: the DN, the CN or a SANClient verifies the brokerrabbitmq.conf
MongoDB, MySQL--tlsCAFile and --tlsMode requireTLS with x.509 auth (MongoDB) / REQUIRE X509 (MySQL)Subject DNClient CA fileserver 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
sql
-- 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.

PieceRoleDetail
CertificateSigningRequest API (certificates.k8s.io/v1)Ask a signer for a certificatespec.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 / ClusterIssuerConfiguration of a CA (CA, Vault, ACME, Venafi, self-signed)The ca issuer signs with a CA key held in a Secret
cert-manager CertificateDesired certificate: dnsNames, uris, duration, renewBefore, usages: [server auth, client auth], privateKey.rotationPolicyThe controller creates a Secret and renews
trust-managerDistributes CA bundles as ConfigMapsKeeps the trust bundle in step with the issuer
SPIFFE CSI driver / SPIRE agentDelivers SVIDs without SecretsFiles in a CSI volume, rewritten on rotation
Mesh (Istio, Linkerd)Delivers certificates inside the sidecarNothing for the app to mount
yaml
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: ClusterIssuer

Kubernetes 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.

CredentialGoLaravel / PHP
Server TLSgrpc.Creds(credentials.NewTLS(cfg)) where cfg is the same tls.Config as for HTTPThe PHP gRPC extension ChannelCredentials::createSsl($rootCerts, $privateKey, $certChain)
Client TLS (mutual)grpc.WithTransportCredentials(credentials.NewTLS(cfg)) with GetClientCertificatecreateSsl with the client key and chain
Per-RPC tokengrpc.WithPerRPCCredentials(tokenSource)Metadata authorization: Bearer ...
Peer identity in the handlerpeer.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.

CostWhereMagnitudeWhat reduces it
Handshake round tripsNew connection1 RTT for TLS 1.3 on top of TCP's 1 RTT; mutual authentication does not add a round trip in TLS 1.3TLS 1.3; keep-alive; HTTP/2 multiplexing
Handshake CPUBoth endsMeasured on one laptop: 0.46 ms per one-way TLS handshake and 0.81 ms per mTLS handshake, both sides in one process, loopbackECDSA P-256 instead of RSA; session resumption
Chain sizeBytes on the wireA leaf plus one intermediate is typically 1-2 KB each wayShort chains; omit the root
Per-request costSteady stateAEAD symmetric encryption: usually negligible next to the applicationHardware AES
ResumptionRepeat connectionsA 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 purposeClientSessionCache in Go; session tickets; note that rotating the server config invalidates tickets
OffloadTerminate TLS in a proxy or load balancerMoves CPU to a dedicated tierBut 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) only

Connection 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.

FailureWhat you seeCausePrevention
Leaf expiredx509: certificate has expired or is not yet valid (Go), certificate has expired (OpenSSL code 10), 503s through the meshAgent failed to renew; Secret not refreshedAlert at 25% of TTL remaining; test renewal failure in a game day
Intermediate or root expiredEvery chain fails at onceForgotten CA lifetimeInventory CA expiry dates; renew intermediates early
Linkerd trust anchor expiredMesh-wide mTLS failureDefault 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 expiredOld clients fail to validate otherwise valid chainsOn 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 skewcertificate is not yet valid right after issuanceNode clock behindNTP; NotBefore backdating; monitor node_timex_offset_seconds
Bundle not rotatedunknown certificate authority for some peersDual-trust phase skippedVersion the bundle; report the active bundle hash per workload
Hot reload missingNew cert on disk, old cert still servedProcess loaded the file onceGetCertificate / 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 propertyIn 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.

sh
# 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
OutputMeaningUsual fix
Verify return code: 0 (ok)Chain verifiedLook elsewhere (identity policy)
Verify return code: 20 (unable to get local issuer certificate)Missing intermediate or CA not in -CAfileSend 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 trustAdd that root to the bundle (if intended)
Verify return code: 10 (certificate has expired)Expired in the verifier's viewRenew; check the verifier's clock
Verify return code: 9 (certificate is not yet valid)NotBefore in the future for the verifierClock skew; backdate NotBefore
Verify return code: 62 (Hostname mismatch ...)Name given with -verify_hostname not in SANUse the right name or verify the SPIFFE ID instead
no peer certificate availableServer did not send oneWrong listener or plaintext port
alert certificate required (TLS 1.3 alert 116) or alert handshake failureServer wanted a client certificate and you sent nonePass -cert and -key
alert bad certificate (alert 42), unknown ca (alert 48)Server rejected the client certificateCheck 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 ​

KnobWhereEffect
tls.Config.ClientAuthGo serverNoClientCert, RequestClientCert, RequireAnyClientCert, VerifyClientCertIfGiven, RequireAndVerifyClientCert; use the last for mTLS
tls.Config.ClientCAsGo serverRoots used to verify client chains; static per config, so use GetConfigForClient to change it at run time
tls.Config.RootCAsGo clientRoots for server chains; nil means the system pool, which you do not want internally
tls.Config.VerifyPeerCertificateGo both sidesRuns 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.VerifyConnectionGo both sidesRuns on every connection including resumptions, regardless of InsecureSkipVerify or ClientAuth; use it for checks that must hold on every connection
tls.Config.GetCertificate / GetClientCertificateGoPick the certificate per handshake: the hot-rotation hook
tls.Config.GetConfigForClientGo serverReturns a config per connection: swap ClientCAs; keep the returned config cached so session tickets keep working
tls.Config.MinVersionGoSet tls.VersionTLS13 for internal traffic
tls.Config.TimeGoClock for validity; tests replace it
InsecureSkipVerifyGo clientDisables 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_depthNGINXClient verification, CA file, CRL, maximum chain depth
trust_chain_verification / validation_contextEnvoyCA bundle and match_typed_subject_alt_names for SAN matching
sslmode, sslcert, sslkey, sslrootcertlibpq / Laravel pgsqlClient side of PostgreSQL TLS
ssl.client.auth, ssl.keystore.location, ssl.truststore.locationKafkaClient-auth mode and stores
auth_mechanisms, ssl_cert_login_fromRabbitMQEnable EXTERNAL and choose the identity field

Error names you will see ​

MessageSideMeaning
tls: client didn't provide a certificateGo server logClient sent none and ClientAuth requires one
remote error: tls: certificate requiredGo clientTLS 1.3 alert 116 from the server
remote error: tls: bad certificateGo clientServer rejected the client certificate (chain, usage or VerifyPeerCertificate)
remote error: tls: unknown certificate authorityGo clientServer does not trust the issuer
x509: certificate signed by unknown authorityGoThe verifier's bundle lacks the issuer
x509: certificate has expired or is not yet valid: current time ...GoValidity window or clock
x509: certificate specifies an incompatible key usageGoclientAuth or serverAuth missing from extended key usage
mtls: peer identity not allowed: spiffe://...This chapter's codeValid certificate, identity outside the policy
FATAL: connection requires a valid client certificatePostgreSQLServer wanted clientcert, none presented
upstream connect error or disconnect/reset before headers with 503Envoy / IstioOften a STRICT/plaintext mismatch or a failed handshake between sidecars
CERTIFICATE_VERIFY_FAILEDEnvoy, Python, othersBoringSSL/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.

go
// 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))
}
go
// 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
}
go
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)
}
go
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
}
go
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.

go
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)
	}
}
go
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:

go
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:

go
// 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
}
go
// 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
<?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
<?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
<?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
<?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
<?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
<?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" ​

SolutionHowAdvantageCost or limit
Mesh with STRICT and deny-by-default AuthorizationPolicyEnable sidecars or ambient, then one allow policy per serviceNo code change, uniformMigration through PERMISSIVE; mesh operations
In-app mTLS with RequireAndVerifyClientCert plus identity policyThe Go code of this chapterNo mesh dependencyEach language needs the library; rotation by every team
NetworkPolicy onlyLabel-based allow listsCheap, no certificatesNo identity, no encryption, coarse

"Certificates expire and take us down" ​

SolutionHowAdvantageCost or limit
Short leaves with automatic renewal at half-lifecert-manager, SPIRE, meshRenewal is exercised hourlyIssuer must be highly available
Expiry metric and alertExport not_after from every workload and CA; alert at 25% leftWarns before the outageNeeds the inventory to be complete
Hot reloadGetCertificate reads a storeNo restartMust be implemented in every client and server
CA expiry calendarTrack roots and intermediates separatelyCatches the 365-day trust anchorManual 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 ​

SituationRecommended controlExtra techniqueReason
Kubernetes, many services, multiple languagesMesh mTLS (Istio ambient or Linkerd), STRICT, AuthorizationPolicySPIRE if you need identity beyond the clusterUniform, no per-language code
A few Go or JVM services, no clusterIn-app mTLS with a shared library and a private CAVault PKI or cert-manager equivalent for issuanceSmallest moving parts
Calls through a queue or an L7 proxy that terminates TLSService token with aud, short expmTLS on each hop; sender-constrained tokens (RFC 8705)Identity must survive the hop
Public API for developersAPI key for quota plus OAuth for identityRate limits, signed webhooks (HMAC)Keys are not identity
B2B partner APIEdge mTLS with a partner CACRL or OCSP, per-partner policy, IP allowlist as an extra layerStrong identity under partner key handling you do not control
Calling AWS servicesIAM role with SigV4 (done by the SDK)VPC endpointsNative identity
Database and broker accessClient certificate plus role mapping, verify-fullShort-lived certs from Vault or cert-managerA leaked password alone is not enough
Multi-cluster or multi-cloudSPIFFE federation or a shared issuer per environmentSeparate trust domains per environmentNo shared root between production and staging
Legacy workload that cannot hold a keySidecar or ingress proxy in frontNetworkPolicy to bind it to the proxyGives 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 identity

Every 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 ​

ScaleWhat you runIdentity and rotationWhat breaks first
1x: a few servicesTLS with a private CA and shared library, certificates from cert-manager or VaultLeaves of days; manual bundleA forgotten expiry date
10x: dozens of services, several teamsMesh (sidecar or ambient) with STRICT; AuthorizationPolicy per serviceLeaves of 24 h; automaticPERMISSIVE left on forever; policies nobody owns
100x: hundreds of services, several clusters or cloudsSPIFFE and SPIRE with federation, per-region issuers, policy as code with testsLeaves of 1 h; bundle rollout monitoredIssuer 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) ​

sh
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):

text
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 40c70910

How 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) ​

sh
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)'
text
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/orders

The 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) ​

sh
go test ./mtls -run xxx -bench Handshake -benchtime 2s -count 3
text
cpu: 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/op

How 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) ​

sh
# 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) ​

sh
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 AuthorizationPolicy

Experiment 6: Laravel client against a fake (expected, not run) ​

sh
php artisan test --filter ServiceIdentityTest
# expected: 3 tests pass (known caller 200, no identity 401, other identity 403)

Common misconceptions ​

BeliefReality
"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 ​

TopicWhat to remember
Purpose of mTLSAuthenticate 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
IdentityOne URI SAN: spiffe://trust-domain/path; derive it from the platform (ServiceAccount), not from the workload
CA designOffline root, online intermediate (MaxPathLen 0), per-environment CAs, ECDSA P-256 leaves
LifetimeMinutes to hours; renew at half-life; alert at 25% remaining
CA rotationAdd the new root, issue from the new CA, wait one TTL, remove the old root
MeshIstio PeerAuthentication STRICT (PERMISSIVE only while migrating); Linkerd 24 h certs, anchor 365 days by default; Consul intentions
Sidecar vs ambientPer-pod proxy and full L7 versus per-node ztunnel for L4 and optional waypoint for L7
TokensVerify signature, iss, aud, exp; pin the algorithm; keep lifetimes short
Weak controlsIP allowlists and API keys are layers, not identity
AuthorizationDeny by default, allow by caller identity, method and path; AuthorizationPolicy, OPA or middleware
Edge mTLSPartner CA, CRL or OCSP, strip and re-set identity headers, bind the app to the proxy
Data storesPostgreSQL clientcert=verify-full and sslmode=verify-full; Kafka ssl.client.auth=required; RabbitMQ EXTERNAL with verify_peer
PerformanceNew mTLS connection ~0.8 ms CPU (both ends) in our benchmark; reuse and resumption matter more than the choice of mTLS
Debuggingopenssl s_client -connect host:port -cert -key -CAfile; openssl verify -untrusted; read the server log first

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
mTLS (mutual TLS)TLS in which both client and server authenticate with certificates
Server certificateCertificate presented by the server; verified by the client
Client certificateCertificate presented by the client when asked; verified by the server
Certificate verificationChain 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 SANA SAN entry of type URI; carries the SPIFFE ID
Service identityThe name that proves which workload is calling
SPIFFEStandard for workload identity names and documents
SPIFFE IDspiffe://trust-domain/path
SVIDSPIFFE Verifiable Identity Document: X.509-SVID or JWT-SVID
SPIREReference implementation that attests workloads and issues SVIDs
Workload attestationIdentifying a workload by selectors such as namespace and ServiceAccount
Trust domainThe root of trust and namespace of a SPIFFE deployment
FederationExchanging trust bundles between trust domains
Private CAA certificate authority operated inside the organisation
Intermediate CAAn online CA signed by the root; issues leaves
Trust bundleThe root certificates a workload accepts
Short-lived certificateLeaf valid for minutes to hours, replacing revocation
Certificate rotationReplacing a certificate (or CA) with a new one before expiry
Hot reloadUsing a new certificate for new connections without restarting
Dual trustTrusting old and new roots at once during a CA change
Service meshInfrastructure that provides mTLS, policy and telemetry between services
SidecarA proxy running next to each application container
Ambient meshIstio mode with a per-node ztunnel and optional waypoint proxies instead of sidecars
PeerAuthenticationIstio resource setting the mTLS mode (STRICT, PERMISSIVE, DISABLE, UNSET)
STRICT / PERMISSIVEOnly mTLS / mTLS and plaintext
AuthorizationPolicyIstio (and Linkerd) resource that allows or denies by identity, method, path
Linkerd identityLinkerd component that issues per-proxy certificates bound to a ServiceAccount
Consul ConnectConsul's mTLS service mesh feature, authorized by intentions
Service tokenA 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 grantOAuth 2.0 flow in which a service authenticates as itself to get a token
Request signing / SigV4 / HMAC signatureSigning the request (method, path, headers, payload hash, timestamp) with a secret or key
API keyA static secret identifying a project or caller; not strong authentication
IP allowlistRestricting callers by source address; weak control
Lateral movementAttacker moving from one compromised system to others
Zero trustTreating no request as trusted by location; verify and authorize each one
BeyondProdGoogle's cloud-native security model built on service identity and no inherent mutual trust
Handshake costCPU and latency of establishing a TLS connection
Session resumptionSkipping the full handshake with a ticket or PSK
TLS offloadTerminating TLS at a proxy or load balancer
Certificate expiry outageFailure because a certificate or CA passed NotAfter
Clock skewDifference between two machines' clocks
openssl s_clientOpenSSL command-line TLS client for debugging
clientcert=verify-fullPostgreSQL pg_hba.conf option requiring and matching a client certificate
sslmode=verify-fulllibpq client mode verifying chain and host name
Kafka SSL client authssl.client.auth=required with a truststore of client CAs
EXTERNAL mechanismRabbitMQ authentication mechanism taking the identity from the TLS client certificate
cert-managerKubernetes controller issuing and renewing certificates
CSR APIKubernetes CertificateSigningRequest API (certificates.k8s.io/v1)
RequireAndVerifyClientCertGo tls.ClientAuthType that demands and verifies a client certificate
VerifyPeerCertificateGo hook for extra checks after normal verification
GetCertificate / GetClientCertificateGo hooks choosing the certificate per handshake; used for hot rotation
gRPC credentialsChannel credentials (TLS identity) and call credentials (per-RPC tokens)
CRL / OCSPCertificate revocation list / online certificate status protocol

References ​

Built by Morteza Negahi