Building a Safe Transport: mTLS with SPIFFE Identities and Policies
As Sherlock, I'll guide you through building a secure transport layer using mutual TLS (mTLS) authenticated by SPIFFE identities (via SPIRE) and enforced by policies. This setup ensures workloads authenticate each other cryptographically using short-lived X.509 SVIDs (SPIFFE Verifiable Identity Documents), with fine-grained authorization policies.
We'll target a Kubernetes environment (common for SPIFFE), but it's adaptable. The result: a client-server pair where:
- Identities are
spiffe://example.org/workload/server and spiffe://example.org/workload/client.
- mTLS is enforced bidirectionally.
- Policies deny unauthorized SPIFFE IDs (e.g., via SPIFFE selectors or an OPA-like policy engine).
Architecture Overview
Kubernetes Cluster
├── SPIRE Server (issues SVID bundles)
├── SPIRE Agents (per-node, attest workloads, fetch SVIDs)
├── Server Pod (fetches SVID, serves HTTPS with mTLS)
├── Client Pod (fetches SVID, calls server with mTLS)
└── Policy Engine (e.g., in-app checks or Envoy/OPA sidecar)
- SPIFFE Trust Domain:
example.org.
- mTLS: Server verifies client SVID; client verifies server bundle.
- Policies: Selector-based (e.g., only allow
path: /secure from specific SPIFFE IDs).
Security Guarantees:
- No static certs/TLSAuth.
- Workload-bound identities (via node attestation).
- Rotate SVIDs every ~1h.
- Audit via SPIRE logs.
Prerequisites
- Kubernetes 1.25+ cluster (e.g., kind/minikube for testing).
kubectl, helm.
- Go 1.21+ for app examples.
- SPIRE v1.9+ (latest stable).
Step 1: Deploy SPIRE (Server + Agents)
Use Helm for simplicity.
# Add SPIRE Helm repo
helm repo add spire https://spiffe.io/helm-charts
helm repo update
# Create namespace
kubectl create ns spire-system
# Install SPIRE Server (customize trust-domain)
helm install spire-server spire/spire-server \
--namespace spire-system \
--set "server.trustDomain=example.org" \
--set "server.serverURL=https://spire-server.spire-system.svc:8081"
# Install SPIRE Agent (DaemonSet)
helm install spire-agent spire/spire-agent \
--namespace spire-system \
--set "agent.serverURL=https://spire-server.spire-system.svc:8081" \
--set "agent.trustDomain=example.org"
Verify:
kubectl wait --for=condition=Ready pods -l app.kubernetes.io/name=spire-server -n spire-system --timeout=60s
kubectl wait --for=condition=Ready pods -l app.kubernetes.io/name=spire-agent -n spire-system --timeout=60s
Step 2: Register Workloads (SPIFFE Identities)
Register server and client as SPIRE workloads using selectors (Kubernetes pod labels).
# Port-forward SPIRE Server
kubectl port-forward -n spire-system svc/spire-server 8081:8081 &
# Register Server Workload
spire-server entry create \
-parentID spiffe://example.org/spire/agent/ns/spire-system/sa/spire-agent \
-spiffeID spiffe://example.org/workload/server \
-selector k8s:ns:default \
-selector k8s:sa:server-sa \
-selector k8s:pod-label:app=server \
-ttl 8760h0m0s # 1 year
# Register Client Workload
spire-server entry create \
-parentID spiffe://example.org/spire/agent/ns/spire-system/sa/spire-agent \
-spiffeID spiffe://example.org/workload/client \
-selector k8s:ns:default \
-selector k8s:sa:client-sa \
-selector k8s:pod-label:app=client \
-ttl 8760h0m0s
Policy Note: Selectors act as first-line policy – only matching pods get SVIDs.
Step 3: Build mTLS Server (Go Example)
Server fetches SVID via Workload API, serves HTTPS on :8443 with mTLS, verifies client SPIFFE ID.
// server.go
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/spiffe/go-spiffe/v2/workloadapi"
)
func main() {
// Fetch SVID from SPIRE Agent (UNIX socket)
client, err := workloadapi.NewX509Context(context.Background(), workloadapi.WithAddr("[::1]:8081"))
if err != nil {
log.Fatal(err)
}
defer client.Close()
svid, err := client.FetchX509SVID()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Server SVID: %v\n", svid.ID)
// Policy: Only allow clients with spiffe://example.org/workload/client
allowedSPIFFE := spiffeid.Must("spiffe://example.org/workload/client")
mux := http.NewServeMux()
mux.HandleFunc("/secure", func(w http.ResponseWriter, r *http.Request) {
clientPeer := r.TLS.PeerCertificates[0]
clientID, err := spiffeid.FromX509SVID(clientPeer)
if err != nil || !clientID.Matches(allowedSPIFFE) {
http.Error(w, "Unauthorized SPIFFE ID", http.StatusUnauthorized)
return
}
w.Write([]byte("Secure response!"))
})
tlsConfig := &tls.Config{
GetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
return svid.TLSConfig().GetCertificate(hello)
},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: x509.NewCertPool(), // Use SVID bundle for verification
GetClientCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
return svid.TLSConfig().GetClientCertificate(hello)
},
}
// Load bundle for CA verification
bundle, _ := client.FetchX509Bundle()
roots := x509.NewCertPool()
for _, cert := range bundle.Certificates() {
roots.AddCertificate(cert)
}
tlsConfig.ClientCAs = roots
srv := &http.Server{
Addr: ":8443",
Handler: mux,
TLSConfig: tlsConfig,
}
go func() { log.Fatal(srv.ListenAndServeTLS("", "")) }()
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
srv.Shutdown(ctx)
}
Dockerfile for Server:
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY server.go go.mod go.sum ./
RUN go mod tidy && go build -o server .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/server .
CMD ["./server"]
Step 4: Build mTLS Client (Go Example)
Client fetches SVID, calls server, verifies server SPIFFE ID.
// client.go (similar structure)
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"log"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/spiffe/go-spiffe/v2/workloadapi"
)
func main() {
client, err := workloadapi.NewX509Context(context.Background(), workloadapi.WithAddr("[::1]:8081"))
if err != nil {
log.Fatal(err)
}
defer client.Close()
svid, err := client.FetchX509SVID()
if err != nil {
log.Fatal(err)
}
// Policy: Verify server is spiffe://example.org/workload/server
bundle, _ := client.FetchX509Bundle()
tlsConfig := svid.TLSConfig()
tlsConfig.RootCAs = x509.NewCertPool()
for _, cert := range bundle.Certificates() {
tlsConfig.RootCAs.AddCertificate(cert)
}
tlsConfig.InsecureSkipVerify = false
resp, err := tlsConfig.Client(&tls.ClientConfig{
ServerName: "server.default.svc.cluster.local", // SNI
}).Client(func() (*http.Client, error) {
return &http.Client{Transport: &http.Transport{TLSClientConfig: tlsConfig}}, nil
}).Get("https://server.default.svc.cluster.local:8443/secure")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
Dockerfile: Same as server, replace server.go with client.go.
Step 5: Deploy Workloads with ServiceAccounts
# server-deployment.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: server-sa
namespace: default
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: server
namespace: default
spec:
replicas: 1
selector:
matchLabels:
app: server
template:
metadata:
labels:
app: server
spec:
serviceAccountName: server-sa
containers:
- name: server
image: your-registry/server:latest
ports:
- containerPort: 8443
---
apiVersion: v1
kind: Service
metadata:
name: server
spec:
selector:
app: server
ports:
- port: 8443
targetPort: 8443
Similar for client-deployment.yaml (no service needed, label app: client, SA client-sa).
kubectl apply -f server-deployment.yaml
kubectl apply -f client-deployment.yaml # Run client as Job for testing
Test:
# Exec into client pod
kubectl exec -it deployment/client -- /client # Should print "Secure response!"
# Tamper test: Delete client entry from SPIRE, restart pod → fails mTLS
Step 6: Advanced Policies
-
SPIRE Selectors: Already in Step 2 (label-based).
-
In-App (as above): Check spiffeid.Matches().
-
Envoy Proxy Sidecar: For L7 policies.
# Add to pod spec
- name: envoy
image: envoyproxy/envoy:v1.28-latest
volumeMounts:
- name: spire-agent-socket
mountPath: /spire
Use Envoy's spiffe filter: https://www.envoyproxy.io/docs/envoy/latest/configuration/listeners/listener_filters/spi...
-
OPA Integration: Sidecar with Rego policies querying SPIFFE bundle.
allow if input.client_id == "spiffe://example.org/workload/client" && input.path == "/secure"
Monitoring & Rotation
- SVIDs auto-rotate (~1h).
- Logs:
kubectl logs -n spire-system -l app.kubernetes.io/name=spire-server.
- Metrics: SPIRE exposes Prometheus endpoints.
Cleanup
helm uninstall spire-server spire-agent -n spire-system
kubectl delete ns spire-system
This is production-ready for sidecar-less mTLS. Scale to service mesh (Istio + SPIRE) for zero-code changes. Questions? Provide your env details! 🕵️