TExcelTAD
Home › Secrets & Policy as Code: Vault, SOPS, OPA & Conftest › Kubernetes Auth, Agent Injector & VSO

Kubernetes Auth, Agent Injector & VSO

Pods already have an identity: their service account, with a signed token the kubelet mounts and rotates (Service Accounts). Vault's kubernetes auth method accepts that token, asks the Kubernetes API whether it is valid (a TokenReview), checks the service account and namespace against a role, and returns a Vault token. No secret zero to distribute.

Note: this needs a running cluster and a reachable Kubernetes API, so the commands and manifests in this lesson are non-run samples. The Vault side (roles, policies, tokens) behaves exactly as in the earlier sessions.

Configuring the auth method

bash
vault auth enable kubernetes

# Vault running inside the cluster: it uses its own service account to call the TokenReview API
vault write auth/kubernetes/config kubernetes_host="https://kubernetes.default.svc:443"

# only the linkly service account in the linkly namespace, only tokens meant for Vault
vault write auth/kubernetes/role/linkly \
  bound_service_account_names=linkly \
  bound_service_account_namespaces=linkly \
  audience=vault \
  token_policies=linkly-read \
  token_ttl=20m
text
Success! Data written to: auth/kubernetes/config
Success! Data written to: auth/kubernetes/role/linkly

A pod logs in with its projected token: vault write auth/kubernetes/login role=linkly jwt=@/var/run/secrets/tokens/vault. Setting an audience and mounting a projected token with that audience means a token stolen from another system can't be replayed against Vault.

For Vault outside the cluster, set kubernetes_ca_cert and a token_reviewer_jwt from a service account bound to the system:auth-delegator ClusterRole, or use the cloud's JWT/OIDC issuer with the jwt method instead.

What the role check does

python · try it yourself
ROLE = {"bound_service_account_names": ["linkly"],
        "bound_service_account_namespaces": ["linkly"],
        "audience": "vault"}

def login(review):
    """review = what the TokenReview API says about the presented token."""
    if not review["authenticated"]:
        return "denied: token not valid (expired, deleted pod, wrong cluster)"
    ns, sa = review["namespace"], review["service_account"]
    if ns not in ROLE["bound_service_account_namespaces"]:
        return f"denied: namespace {ns!r} not bound"
    if sa not in ROLE["bound_service_account_names"]:
        return f"denied: service account {sa!r} not bound"
    if ROLE["audience"] not in review["audiences"]:
        return "denied: token audience is not 'vault'"
    return "ok: token with policy linkly-read, ttl 20m"

cases = {
    "linkly pod":             {"authenticated": True, "namespace": "linkly", "service_account": "linkly", "audiences": ["vault"]},
    "default SA in linkly":   {"authenticated": True, "namespace": "linkly", "service_account": "default", "audiences": ["vault"]},
    "linkly SA, other ns":    {"authenticated": True, "namespace": "dev", "service_account": "linkly", "audiences": ["vault"]},
    "API-audience token":     {"authenticated": True, "namespace": "linkly", "service_account": "linkly", "audiences": ["https://kubernetes.default.svc"]},
    "token of a deleted pod": {"authenticated": False},
}
for name, review in cases.items():
    print(f"{name:24} {login(review)}")
linkly pod               ok: token with policy linkly-read, ttl 20m
default SA in linkly     denied: service account 'default' not bound
linkly SA, other ns      denied: namespace 'dev' not bound
API-audience token       denied: token audience is not 'vault'
token of a deleted pod   denied: token not valid (expired, deleted pod, wrong cluster)

Never bind * for names or namespaces in production: anyone who can create a pod in any namespace would get the role's secrets.

Three ways to deliver the secret to the pod

Vault Agent Injector Vault CSI provider Vault Secrets Operator (VSO)
How mutating webhook adds a Vault Agent sidecar Secrets Store CSI driver mounts secrets as a volume operator syncs Vault secrets into Kubernetes Secret objects
Secret lands in a shared in-memory volume, rendered by a template a tmpfs volume a Kubernetes Secret (etcd)
Rotation agent re-renders the file on remount / rotation polling operator re-syncs and can restart Deployments
App changes read a file read a file none: env vars or volumes from a normal Secret

Agent Injector annotations

yaml
apiVersion: apps/v1
kind: Deployment
metadata: {name: linkly, namespace: linkly}
spec:
  template:
    metadata:
      annotations:
        vault.hashicorp.com/agent-inject: "true"
        vault.hashicorp.com/role: "linkly"
        vault.hashicorp.com/agent-inject-secret-db: "secret/data/linkly/db"
        vault.hashicorp.com/agent-inject-template-db: |
          {{- with secret "secret/data/linkly/db" -}}
          postgres://{{ .Data.data.username }}:{{ .Data.data.password }}@postgres:5432/linkly
          {{- end -}}
    spec:
      serviceAccountName: linkly
      containers:
        - name: app
          image: ghcr.io/acme/linkly:1.4.2
          env:
            - name: DATABASE_URL_FILE
              value: /vault/secrets/db

The template language is the same one Vault Agent uses outside Kubernetes, which you can run in Vault Agent.

Vault Secrets Operator

yaml
apiVersion: secrets.hashicorp.com/v1beta1
kind: VaultAuth
metadata: {name: linkly, namespace: linkly}
spec:
  method: kubernetes
  mount: kubernetes
  kubernetes:
    role: linkly
    serviceAccount: linkly
    audiences: [vault]
---
apiVersion: secrets.hashicorp.com/v1beta1
kind: VaultStaticSecret
metadata: {name: linkly-db, namespace: linkly}
spec:
  vaultAuthRef: linkly
  mount: secret
  type: kv-v2
  path: linkly/db
  refreshAfter: 60s
  destination:
    name: linkly-db          # the Kubernetes Secret the operator creates and updates
    create: true
  rolloutRestartTargets:
    - kind: Deployment
      name: linkly

VSO also has VaultDynamicSecret (database credentials with lease renewal) and VaultPKISecret. Because its output is a normal Kubernetes Secret, it sits next to the External Secrets Operator, which does the same for many stores; protect etcd with encryption at rest and RBAC either way.

Test yourself

How does Vault verify a pod's service-account token in the kubernetes auth method?

  1. It decodes it without checks
  2. It calls the Kubernetes TokenReview API, then checks namespace, service account and audience against the role
  3. It asks the pod for a password
  4. It compares it with a stored copy

Which delivery method leaves the secret in a Kubernetes Secret object in etcd?

  1. Vault Agent Injector
  2. Vault Secrets Operator
  3. Vault CSI provider
  4. None of them