Platform Engineering · Lesson 179

Workload Identity with SPIFFE and SPIRE: Short-Lived Certificates for Every Service

Services need to prove who they are to each other, and long-lived API keys and shared passwords are the usual way that goes wrong: copied, leaked, never rotated. SPIFFE is a standard for workload identity: every workload gets an ID such as spiffe://prod.example.com/ns/shop/sa/checkout, carried in a short-lived X.509 certificate or JWT called an SVID. SPIRE is the system that issues them: it attests what a workload really is, from the node and the kubelet rather than from anything the workload claims, and rotates its certificate automatically. This lesson follows one service-to-service call from attestation to authorization, and shows what happens when a workload is not registered and when the SPIRE server is unreachable for longer than a certificate lives.

Difficulty: Advanced · Know this first: Lesson 59, Lesson 104, Lesson 177

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar splits the first call of a newly started workload, in milliseconds. It is a worked example, not a measurement. Attestation and issuance happen once; after that each connection only pays for the handshake.

Try it: how long can SPIRE be down?

Set the SVID lifetime and how long the SPIRE server has been unreachable. The agent renews at half the lifetime, so the last good certificate lasts at most one lifetime from its last renewal.

The last renewal happened at most half a lifetime before the outage, so certificates stay valid for between half and one full lifetime into it · safe outage ≥ lifetime ÷ 2

30minutes of outage always survived
expiredcertificates now
60minutes a leaked SVID stays useful

The outage outlasted the certificates: services can no longer connect

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Workload identity grows in four levels: first what a SPIFFE ID and an SVID are, then running SPIRE on Kubernetes, then authorization, federation, and availability, and finally replacing static secrets across an organization.

Basic — An ID and a short-lived document

At the basic level you know the terms. A SPIFFE ID is a URI naming a workload: spiffe://trust-domain/path. An SVID is the document that proves it: an X.509 certificate with the ID in its URI SAN, or a signed JWT. A trust domain is a group that shares one root of trust. SPIRE is the reference implementation: a server that signs, and agents on every node that attest and deliver.

Where it breaks: static API keys shared between services; they cannot say which workload used them, and they rarely rotate.

Try it: Basic

Where is the SPIFFE ID inside an X.509-SVID?

Now do it: Run spiffe_ids.py in Go deeper and read which workloads get an ID.

Intermediate — Run SPIRE on Kubernetes

At the intermediate level you deploy SPIRE (often with its Helm charts): servers as a StatefulSet with a datastore, agents as a DaemonSet with node attestation (k8s_psat), the SPIFFE CSI driver to mount the Workload API socket into pods, and the SPIRE controller manager to create entries from ClusterSPIFFEID resources.

  • One trust domain per environment: prod, staging, dev.
  • IDs that encode namespace and service account, so Kubernetes RBAC and SPIFFE agree on who a workload is.
  • A mesh or SPIFFE library in each service to use the SVIDs.

Troubleshooting: spire-server entry show, agent logs for attestation failures, and the pod's mounted socket.

Try it: Intermediate

A pod gets no SVID. The agent log says no identity issued. What do you check first?

Now do it: Write a ClusterSPIFFEID like the one in Go deeper for one namespace and check which pods it selects.

Advanced — Authorization, federation, and availability

At the advanced level you build on identities.

  • Authorization: allow lists by SPIFFE ID in mesh policy or OPA, default deny between services.
  • Beyond the cluster: agents on VMs (node attestation by cloud instance identity), and JWT-SVIDs exchanged for cloud credentials (for example AWS roles trusting an OIDC issuer), replacing static cloud keys.
  • Federation: exchanging trust bundles between trust domains for cross-environment or partner calls, deliberately and narrowly.
  • Availability: several SPIRE servers behind a shared datastore, agents caching SVIDs, alerts on renewal failures well before the half-life, and an upstream CA with its own rotation.

Try it: Advanced

Your SVID lifetime is one hour. What is the longest SPIRE server outage every workload is guaranteed to survive?

Now do it: Use the simulator: find the lifetime that survives a 4-hour SPIRE outage, and decide whether a leaked certificate lasting that long is acceptable.

Master — Retire static secrets

At the master level workload identity replaces static secrets across the organization.

  • Inventory: every API key, database password, and cloud access key used service-to-service, and which can move to SVID-based mTLS or token exchange.
  • Databases and clouds: PostgreSQL and others accept client certificates; cloud providers accept OIDC federation; Vault can authenticate workloads by SVID.
  • Audit: every call carries a cryptographic caller identity, which turns "who accessed this?" into a query.
  • Risk: SPIRE becomes tier-zero; its signing keys, upstream CA, and datastore need the protection of a root CA.

Trade-off: short-lived identities remove whole classes of leaks and make the identity system a dependency of every connection. Longer lifetimes soften outages and weaken the protection; choose with the simulator's two numbers in mind.

Try it: Master

A team wants a 24-hour SVID lifetime "to be safe from SPIRE outages". What is the trade?

Now do it: List the static secrets your services use to call each other, and which could become SPIFFE-based.

Go deeper

Attestation, rotation, and authorization each fit in a few lines. This script matches workloads to registration entries, shows certificate rotation with and without the SPIRE server, and authorizes peers by SPIFFE ID and trust domain. Standard library only; python3 spiffe_ids.py.

Attest, rotate, authorize

# spiffe_ids.py - attest a workload, issue an identity, rotate it, and authorize a peer by its SPIFFE ID
TRUST_DOMAIN = "prod.example.com"
ENTRIES = [  # registration entries: selectors a workload must match -> the SPIFFE ID it gets
    ({"k8s:ns:payments", "k8s:sa:ledger"}, f"spiffe://{TRUST_DOMAIN}/ns/payments/sa/ledger"),
    ({"k8s:ns:shop", "k8s:sa:checkout"}, f"spiffe://{TRUST_DOMAIN}/ns/shop/sa/checkout"),
]
TTL_MIN = 60                                  # X.509-SVID lifetime; the agent renews at half of it

def attest(selectors):
    """The agent observes the workload (kernel, container runtime, kubelet) and matches entries."""
    for need, spiffe_id in ENTRIES:
        if need <= selectors:
            return spiffe_id
    return None

def authorize(peer_id, allowed):
    if not peer_id.startswith(f"spiffe://{TRUST_DOMAIN}/"):
        return "reject: other trust domain"
    return "allow" if peer_id in allowed else "reject: not on the allow list"

for selectors in [{"k8s:ns:shop", "k8s:sa:checkout", "k8s:pod-label:app:checkout"},
                  {"k8s:ns:shop", "k8s:sa:default"}]:
    sid = attest(selectors)
    print(f"workload {sorted(selectors)} -> {sid or 'no matching entry: no identity issued'}")

# Rotation: the agent renews at half the TTL, if it can reach the SPIRE server.
for server_reachable_until in (10_000, 20):
    issued, line = 0, []
    for minute in range(0, 91, 15):
        if minute - issued >= TTL_MIN // 2 and minute <= server_reachable_until:
            issued = minute                               # renewed with a fresh SVID
        line.append(f"{minute}m:{'ok' if minute - issued < TTL_MIN else 'EXPIRED'}")
    label = "server reachable" if server_reachable_until > 1000 else "server unreachable after 20m"
    print(f"{label:<28} " + " ".join(line))

ledger_allows = {f"spiffe://{TRUST_DOMAIN}/ns/shop/sa/checkout"}
for peer in [f"spiffe://{TRUST_DOMAIN}/ns/shop/sa/checkout", f"spiffe://{TRUST_DOMAIN}/ns/shop/sa/reports",
             "spiffe://dev.example.com/ns/shop/sa/checkout"]:
    print(f"ledger receives a call from {peer}: {authorize(peer, ledger_allows)}")
$ python3 spiffe_ids.py
workload ['k8s:ns:shop', 'k8s:pod-label:app:checkout', 'k8s:sa:checkout'] -> spiffe://prod.example.com/ns/shop/sa/checkout
workload ['k8s:ns:shop', 'k8s:sa:default'] -> no matching entry: no identity issued
server reachable             0m:ok 15m:ok 30m:ok 45m:ok 60m:ok 75m:ok 90m:ok
server unreachable after 20m 0m:ok 15m:ok 30m:ok 45m:ok 60m:EXPIRED 75m:EXPIRED 90m:EXPIRED
ledger receives a call from spiffe://prod.example.com/ns/shop/sa/checkout: allow
ledger receives a call from spiffe://prod.example.com/ns/shop/sa/reports: reject: not on the allow list
ledger receives a call from spiffe://dev.example.com/ns/shop/sa/checkout: reject: other trust domain

Read it like this: the pod with the right service account gets its ID and the default one gets nothing; with the server reachable every check is valid, and with the server gone after 20 minutes the last certificate, issued at minute 0, expires at 60; and ledger accepts checkout from its own trust domain only.

IDs for every pod, by namespace and service account

apiVersion: spire.spiffe.io/v1alpha1
kind: ClusterSPIFFEID
metadata:
  name: default-workloads
spec:
  spiffeIDTemplate: "spiffe://{{ .TrustDomain }}/ns/{{ .PodMeta.Namespace }}/sa/{{ .PodSpec.ServiceAccountName }}"
  podSelector:
    matchExpressions:
      - key: spiffe.io/enabled
        operator: In
        values: ["true"]
  namespaceSelector:
    matchExpressions:
      - key: kubernetes.io/metadata.name
        operator: NotIn
        values: ["kube-system", "spire"]

The resource is the SPIRE controller manager's ClusterSPIFFEID; it parses as YAML and follows the controller manager's documented fields. Install SPIRE with its Helm charts on a kind cluster first, label a test pod spiffe.io/enabled: "true", and inspect the entry with spire-server entry show.

Look at an identity

kubectl exec -n spire spire-server-0 -c spire-server -- /opt/spire/bin/spire-server entry show
kubectl exec -n spire spire-server-0 -c spire-server -- /opt/spire/bin/spire-server bundle show
# inside a pod with the SPIFFE helper or go-spiffe tools: fetch the SVID and read it
openssl x509 -in svid.0.pem -noout -subject -enddate -ext subjectAltName

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A company moved service-to-service authentication to SPIFFE with one-hour SVIDs and ran a single SPIRE server.

Timeline

  • 13:00The SPIRE server's datastore runs out of disk. The server stops signing. Nothing visible happens: every workload still has a valid certificate.
  • 13:30Renewals start failing. The agents log errors; nobody alerts on them.
  • 14:00Certificates begin to expire. Services fail mutual TLS one after another, in the order they were last renewed. The incident looks like a network outage for twenty minutes.

What changed after

SPIRE moved to three servers with a managed datastore, agents alert on any failed renewal, and the dashboard shows the earliest SVID expiry in the fleet. The one-hour lifetime stayed; the system that issues them was made as reliable as the services that depend on it.

If you remember nothing else

Design exercise

Design workload identity for 300 services across two Kubernetes clusters and a fleet of VMs, replacing shared API keys and static cloud access keys.

Clarifying questions to ask

Which calls cross clusters or leave Kubernetes? Which services already run in a mesh? What must keep working if the identity system is down for an hour? Which cloud services must the workloads reach, and do they accept OIDC federation? Who owns the trust domains?

Rough sizing

Say 3,000 pods, 400 VMs, 60-minute SVIDs, 3 SPIRE servers per cluster, and 2 trust domains (prod and non-prod).

Shape of the answer

SPIRE per cluster with three servers and a managed datastore, agents on every node and VM, the CSI driver and controller manager with ClusterSPIFFEIDs by namespace and service account; nested or federated trust between the two prod clusters; mesh mTLS with authorization policies by SPIFFE ID; JWT-SVIDs exchanged for cloud roles; alerts on failed renewals and the earliest expiry; a migration plan from static keys, service by service.

Trade-offs to name

Short SVIDs make leaks short-lived and need a highly available SPIRE. One trust domain per environment keeps blast radius small and needs federation for the few calls that cross. A mesh adds identity without code changes and is itself a large system to run; libraries are lighter and need code in every service.

Saved on this device, in this browser.
Next in this series · Lesson 180
Service Design from Scratch: Requirements, NFRs, and the Design Brief

Every service I have designed started as one sentence from someone who did not know it was a design problem. "Customers keep calling to ask where their parcel is. Can we show them?" That sentence is not a design. It is an ask.

Go to Lesson 180 →

Or browse the full course from the Lessons index.