HashiCorp Vault Deep Dive
From the publisher’s feed, collected in the ZeroLabs newsroom.
Dynamic secrets, the seal/unseal lifecycle, Kubernetes auth, AppRole, PKI, Transit, and production patterns.Part 2 of 5 — Machine identity, credential sprawl, and why most teams discover the problem too late.Series: Part 1Part 1 established the core problem: credential sprawl, static shared identities, no audit trail, and the Secret Zero recursion. The solution is an identity-driven model where workloads prove who they are and receive short-lived credentials in return.Application ↓ proves platform identity (no stored secret)Authenticates to Vault ↓ policy evaluatedRequests a credential ↓ TTL-bound, scoped, auditedReceives temporary access ↓ credential auto-revoked at expiryHashiCorp Vault is the most widely deployed open-source platform for this model. This article goes deep on how it actually works — not just what it does.What Vault IsVault is a secret management platform built around four core capabilities:Secret storage — secure, versioned, audited key-value storage.Dynamic credential generation — creates short-lived, scoped credentials on demand and revokes them automatically.Encryption as a service — performs cryptographic operations so applications never handle raw keys.Certificate authority — issues and renews short-lived TLS certificates.The core operating model is a broker, not a proxy:Vault issues credentials — it does not proxy connections. When Vault generates a database username and password, the application uses that credential to connect to the database directly. The database has no knowledge of Vault.Vault Architecture and Building BlocksVault’s architecture has four distinct layers that are worth understanding before you configure anything.The encryption barrier is what makes Vault’s storage backend agnostic. Whether you use Raft, Consul, or S3 as a backend, nothing stored there is readable without Vault’s root key. An attacker with direct access to your Raft data files has only encrypted bytes.The three operational layers you configure:Every request flows through all three layers in order. No exceptions.Vault Init, Seal, and UnsealThis is the most misunderstood part of Vault operations. Three distinct concepts are often conflated.Vault Init — runs oncevault operator init bootstraps a brand new Vault cluster. It:Generates the root key (the master encryption key for the barrier).Splits the root key into unseal key shares using Shamir Secret Sharing.Generates an initial root token with unrestricted access.Outputs both unseal key shares and the root token — these are shown exactly once and never again.$ vault operator init -key-shares=5 -key-threshold=3Unseal Key 1: A1B2C3D4...Unseal Key 2: E5F6G7H8...Unseal Key 3: I9J0K1L2...Unseal Key 4: M3N4O5P6...Unseal Key 5: Q7R8S9T0...Initial Root Token: hvs.XXXXXXXXXXXXXXXXXXXXXXXX# WARNING: Store these securely. They will never be shown again.# Revoke the root token after initial configuration is complete.⚠️ Root token warning. The initial root token has unrestricted access to everything in Vault. Use it only for initial configuration, then revoke it. Generate a new root token only when absolutely necessary, using a quorum of unseal key holders.Sealed vs Unsealed — the operational stateAfter init, and after every restart, Vault starts sealed. In the sealed state:Vault cannot decrypt any data from the storage backend.Every API call returns HTTP 503 — Vault is sealed.No secrets can be read, no credentials issued, no authentication possible.Vault is a locked box. The root key is not in memory. The encryption barrier cannot function.Shamir Unseal — the manual modelTo unseal, enough key shares must be provided to reconstruct the root key. The root key is then held in memory (never written to disk) and used to operate the barrier.This improves resilience but creates real operational overhead: every time a Vault node restarts (patch, crash, node replacement), three key holders must be available to manually unseal it. In an automated Kubernetes environment where nodes restart frequently, this is unacceptable.Auto-Unseal — the production modelIn auto-unseal, Vault stores an encrypted copy of the root key in the storage backend, and uses a cloud KMS or HSM to decrypt it on startup — without human intervention.Auto-unseal shifts the trust boundary: instead of trusting key holders to be available, you trust the KMS. Access to the KMS itself should be tightly controlled via IAM policies.Production rule: Configure auto-unseal before your first production deployment. Treating manual Shamir unseal as a day-2 model is an operational incident waiting to happen.Authentication MethodsVault’s auth methods solve the Secret Zero problem by accepting proof of identity from the execution environment — rather than a stored password.AppRole — for workloads without platform identityAppRole is the right choice when a workload has no cloud or platform identity to leverage (legacy VMs, on-prem batch jobs, CI runners without OIDC support).It uses two values:role_id — a non-secret identifier for the role. It is analogous to a username. It can be safely embedded in configuration or a container image because it is useless without the secret_id.secret_id — the actual authenticating credential. This is the secret and must be delivered securely.# Login to Vault using AppRolevault write auth/approle/login \ role_id="" \ secret_id=""The classic AppRole bootstrap problem: how do you securely deliver secret_id to the workload if the workload doesn't have an identity yet? The answer is Response Wrapping.Response Wrapping for AppRole secret_idInstead of delivering the secret_id directly, Vault wraps it in a single-use token with a short TTL. The CI/CD system or deployment pipeline delivers the wrapping token to the workload, and the workload unwraps it to get the real secret_id.The wrapping token is single-use. Even if it is intercepted, using it invalidates it and Vault alerts on the tampered unwrap attempt.When a platform identity (Kubernetes, AWS, Azure, GCP) is available, use it instead of AppRole. AppRole is the right tool when nothing better exists.PoliciesAfter authentication, Vault evaluates policies attached to the resulting token to determine what that token can do.Vault denies by default. If no policy explicitly allows an operation, it is denied. There is no implicit allow.# Policy: reporting-app# Attached to tokens issued to the reporting service# Allow reading dynamic DB credentials for the reporting rolepath "database/creds/reporting-role" { capabilities = ["read"]}# Allow reading application config secrets (versioned KV v2)# The /data/ infix is required for KV v2 data pathspath "secret/data/reporting/*" { capabilities = ["read"]}# Allow reading metadata (but not data) for rotation detectionpath "secret/metadata/reporting/*" { capabilities = ["read", "list"]}# Allow the token to renew itselfpath "auth/token/renew-self" { capabilities = ["update"]}Path wildcardsExample:# Matches: secret/data/reporting/db, secret/data/reporting/api/key, etc.path "secret/data/reporting/*" { ... }# Matches: secret/data/reporting/db - but NOT secret/data/reporting/api/keypath "secret/data/reporting/+" { ... }Root policyThe root policy is built-in and grants unrestricted access to everything. Only the initial root token has it. Revoke the root token after initial setup. Never attach the root policy to service tokens.KV v1 vs KV v2The KV (Key/Value) secrets engine stores static secrets — API keys, third-party credentials, configuration values that cannot be dynamically generated.Use KV v2 for new deployments. KV v1 exists for backwards compatibility.The /data/ path infix — a common policy bugThe CLI (vault kv get) handles the path translation transparently. The HTTP API does not.bash# CLI — path translation handled automaticallyvault kv get secret/reporting/db-config# HTTP API - must include /data/ infix explicitlycurl -H "X-Vault-Token: $VAULT_TOKEN" \ https://vault:8200/v1/secret/data/reporting/db-configWhen writing Vault policies for KV v2, you must use the /data/ path — otherwise the policy will not match HTTP API requests:# WRONG for KV v2 — matches CLI but not direct HTTP API callspath "secret/reporting/db-config" { capabilities = ["read"] }# CORRECT for KV v2 - matches both CLI and HTTP APIpath "secret/data/reporting/db-config" { capabilities = ["read"] }# Metadata operations use /metadata/ pathpath "secret/metadata/reporting/db-config" { capabilities = ["read"] }Check-and-set (CAS) writesKV v2 supports optimistic locking. If you enable CAS on a secret, a write must include the current version number. Writes with a stale version are rejected, preventing concurrent overwrites during rotation.Dynamic Database CredentialsStatic database passwords are the most common secret management failure in production systems. Vault’s database secrets engine eliminates them.Step 1 — Configure the database connectionBefore creating roles, Vault needs a privileged connection to the database to create and revoke users.vault write database/config/postgres-prod \ plugin_name=postgresql-database-plugin \ allowed_roles="reporting-role,payments-role" \ connection_url="postgresql://{{username}}:{{password}}@postgres.internal:5432/production" \ username="vault-admin" \ password="$VAULT_DB_ADMIN_PASSWORD"This connection is used only by Vault internally to manage dynamic users. The vault-admin user needs CREATEROLEprivilege and the ability to grant the required permissions.Step 2 — Define a database roleresource "vault_database_secret_backend_role" "reporting" { name = "reporting-role" backend = "database" db_name = "postgres-prod"creation_statements = [ "CREATE ROLE \"{{name}}\" WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';", "GRANT SELECT ON ALL TABLES IN SCHEMA reporting TO \"{{name}}\";", "GRANT USAGE ON SCHEMA reporting TO \"{{name}}\";" ] revocation_statements = [ "REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA reporting FROM \"{{name}}\";", "DROP ROLE IF EXISTS \"{{name}}\";" ] default_ttl = "1h" max_ttl = "24h"}revocation_statements define what Vault executes when the lease expires or is revoked. Without them, Vault may fail to clean up the user.Step 3 — Request a credential# Request via CLIvault read database/creds/reporting-role# Request via HTTP API (requires X-Vault-Token header)curl -H "X-Vault-Token: $VAULT_TOKEN" \ https://vault:8200/v1/database/creds/reporting-roleResponse:{ "lease_id": "database/creds/reporting-role/x7k2mQpLnR9aVbTc", "lease_duration": 3600, "renewable": true, "data": { "username": "v-k8s-reportin-x7k2mQpLnR", "password": "A1b2-C3d4-E5f6-G7h8" }}How Vault actually creates the user — corrected sequenceVault generates the credentials. PostgreSQL does not — it only acknowledges the CREATE ROLE statement. The database never "returns" a username or password to Vault.Leases and TokensEvery dynamic secret and every Vault token has a lease — a time-bounded right to access.Lease fieldsCorrected lease lifecycleIn Vault, expiry and revocation are the same event. When a lease expires, the Vault expiry worker revokes it — executing revocation_statements against the database and removing the dynamic user. There is no separate "expired but not yet revoked" state.The TTL hierarchyAuth method max_ttl └── Token TTL (cannot exceed auth method max_ttl) └── Secret lease TTL (cannot exceed the token's remaining TTL)A secret lease cannot outlive the token that created it. If your Vault token has 30 minutes remaining and you request a database credential with max_ttl=24h, the credential will be revoked when the token expires in 30 minutes — regardless of the role's max_ttl setting.This is the most common source of mysterious application disconnects in production Vault deployments. If your application is losing database connections after a fixed period, check token TTL first.Token renewal vs lease renewalThese are two separate operations:# Renew the Vault token itselfvault token renew# Renew a specific secret leasevault lease renew database/creds/reporting-role/x7k2mQpLnR9aVbTcRenewing the token does not renew leases issued under it. Renewing a lease does not renew the token. Both have their own max_ttl ceilings.Orphan tokensBy default, tokens have a parent-child relationship. When a parent token is revoked, all child tokens and their leases are revoked in a cascade. An orphan token has no parent — it is not affected by parent revocation. Vault Agent typically creates orphan tokens for exactly this reason.Kubernetes AuthenticationKubernetes auth is the cleanest solution to Secret Zero for Kubernetes workloads. The pod’s Service Account JWT — issued and signed by the Kubernetes API server — becomes its identity.Configuring the auth method# Enable the kubernetes auth method at a specific pathvault auth enable kubernetes# Configure it to talk to your clustervault write auth/kubernetes/config \ kubernetes_host="https://kubernetes.default.svc:443" \ kubernetes_ca_cert=@/var/run/secrets/kubernetes.io/serviceaccount/ca.crt \ issuer="https://kubernetes.default.svc.cluster.local"Configuring a role — with security constraintsvault write auth/kubernetes/role/reporting-app \ bound_service_account_names="reporting-sa" \ bound_service_account_namespaces="production" \ policies="reporting-app" \ ttl="1h"⚠️ bound_service_account_names and bound_service_account_namespaces are not optional. Without them, any service account in any namespace can authenticate to this role and receive the attached policies. Always restrict both fields.Complete authentication flowProjected service account tokensSince Kubernetes 1.21, pods use projected service account tokens — short-lived, audience-scoped JWTs automatically rotated by the kubelet. This is more secure than legacy long-lived SA secrets.Vault’s Kubernetes auth method supports projected tokens natively. No additional configuration is needed — Vault reads the token from the standard path (/var/run/secrets/kubernetes.io/serviceaccount/token) and validates it via the TokenReview API.Vault Agent Injector and Vault Secrets OperatorTwo Kubernetes-native patterns for delivering secrets to pods without modifying application code.Vault Agent InjectorThe Vault Agent Injector uses a mutating admission webhook (vault-k8s) to intercept pod creation and inject two containers:An init container that authenticates to Vault and writes secrets to a shared emptyDir volume before the application container starts.A sidecar container that monitors for lease renewals and refreshes secrets in the shared volume during the pod’s lifetime.The application container reads secrets from files at /vault/secrets/. It never calls Vault directly. The shared volume is an emptyDir — memory-backed, never persisted to the node's disk.Annotation configurationspec: template: metadata: annotations: vault.hashicorp.com/agent-inject: "true" vault.hashicorp.com/role: "reporting-app" vault.hashicorp.com/agent-inject-secret-db-config.txt: "database/creds/reporting-role" vault.hashicorp.com/agent-inject-template-db-config.txt: | {{- with secret "database/creds/reporting-role" -}} DB_USER={{ .Data.data.username }} DB_PASS={{ .Data.data.password }} {{- end -}} # Wait for init container to finish before starting app vault.hashicorp.com/agent-inject-status: "update"Note .Data.data.username — for KV v2, the data is nested under a second .data key in the template.Vault Secrets Operator (VSO) — the modern Kubernetes-native approachReleased in 2023, the Vault Secrets Operator is the current recommended approach for Kubernetes deployments. Instead of sidecars, it runs as a cluster-level operator and syncs Vault secrets into native Kubernetes Secret objects.VSO advantages over Agent Injector:No sidecar containers — lower resource overhead.Works with any workload type (Jobs, CronJobs, StatefulSets) without annotation requirements.Native Kubernetes Secret objects — compatible with all existing tooling.Secret rotation triggers pod restarts automatically (configurable).PKI Secrets EngineThe production PKI architectureA critical distinction: in production, Vault should be an intermediate CA, not the root CA. The root CA should be offline and air-gapped — its private key should never be on a network.If Vault is compromised, you revoke the intermediate CA certificate. The root CA is unaffected and can sign a new intermediate. This is why offline root CAs are non-negotiable in production PKI.Certificate issuance flowPKI role configurationvault write pki_int/roles/internal-services \ allowed_domains="production.svc,internal" \ allow_subdomains=true \ max_ttl="72h" \ key_type="ec" \ key_bits=256 \ require_cn=trueallowed_domains is the security boundary. A role misconfigured with allow_any_name=true can issue certificates for any domain, including ones you do not own.cert-manager integrationapiVersion: cert-manager.io/v1kind: Issuermetadata: name: vault-issuer namespace: productionspec: vault: server: https://vault.security.svc:8200 path: pki_int/sign/internal-services auth: kubernetes: role: cert-manager mountPath: /auth/kubernetes # no /v1/ prefix in cert-manager spec secretRef: name: cert-manager-vault-token key: tokenCertificate revocationVault maintains a Certificate Revocation List (CRL) at a well-known path (/v1/pki_int/crl). For OCSP validation, Vault exposes an OCSP responder. Both URLs are embedded in issued certificates via the Authority Information Access extension.Short-lived certificates (24h TTL) reduce the operational importance of CRL/OCSP — most certificates expire before revocation is needed. This is one of the primary reasons to prefer short-lived certs.Transit Secrets EngineTransit provides encryption as a service. Vault stores the encryption keys inside the barrier. Your application stores only ciphertext.What Transit does:Encrypt and decrypt data using keys Vault manages.Sign and verify data using asymmetric keys.Generate HMACs.Rotate encryption keys while maintaining the ability to decrypt old ciphertext.What Transit does not do:Store your encrypted data. That stays in your database.Supported key typesEncryption and decryption flowData sent to Vault for encryption must be base64-encoded. Vault returns ciphertext in the format vault:v1:. The v1 prefix is the key version — critical for key rotation.Key rotation# Rotate the key — Vault generates a new key version (v2)vault write -f transit/keys/payments-key/rotate# Now: new encryptions use v2, old ciphertext (v1) can still be decrypted# "vault:v2:..." for new data, "vault:v1:..." for existing data# Rewrap old ciphertext to the new key versionvault write transit/rewrap/payments-key \ ciphertext="vault:v1:AbCdEf..."# Returns: vault:v2:XyZaBc...# Optionally: set minimum decryption version to prevent use of old keysvault write transit/keys/payments-key/config \ min_decryption_version=2After rotation, old ciphertext tagged with v1 can still be decrypted until you advance min_decryption_version. This gives you a controlled migration window.Production ArchitectureIntegrated Storage (Raft) — the correct modelRaft is not a separate storage service. Each Vault node maintains its own local copy of the data and participates in the Raft consensus protocol. There is no external storage cluster.Why odd node counts: Raft requires a quorum (majority) for writes to succeed.3-node is the minimum for high availability. 5-node is common for production clusters that must survive AZ failure.Load balancer health checksThe /v1/sys/health endpoint returns different HTTP status codes by node state:Configure your load balancer to route only to 200 nodes, or to both 200 and 429 for read distribution.Snapshots and backup# Take a manual Raft snapshotvault operator raft snapshot save vault-backup-$(date +%Y%m%d).snap# Automate via Vault's snapshot agent (Enterprise)# or schedule the above command via cron / Kubernetes CronJobSnapshots are encrypted. Store them in object storage (S3, GCS, Azure Blob) with versioning and lifecycle policies. Test restore procedures regularly — an untested backup is not a backup.Enterprise-only featuresSeveral features mentioned in Vault documentation are Vault Enterprise only and not available in the open-source (OSS) release:Namespaces provide multi-team isolation within a single Vault cluster — each namespace has its own auth methods, policies, and secret engines. This is Enterprise-only. OSS teams achieve isolation through path conventions and RBAC policies instead.Replication for multi-region active/active or active/passive deployments is also Enterprise-only.Common Misconceptions“Vault is just encrypted storage”Vault is an identity-aware access broker. Encrypted KV storage is one small feature. The platform also provides dynamic credential generation, PKI, encryption-as-a-service, audit logging, lease management, and a policy engine. A team using Vault only as a key-value store is using roughly 10% of its capabilities.“Vault eliminates secrets”It doesn’t — and this is an important distinction. Every system still uses secrets. What Vault changes is the nature of the secret: from a long-lived, static, shared credential with no audit trail, to a short-lived, scoped, unique credential that is automatically revoked. The credential still exists — it just expires in an hour.“Vault only works in Kubernetes”Vault has auth methods for Kubernetes, AWS, Azure, GCP, bare metal (AppRole, TLS certs), LDAP, and OIDC. It runs on VMs, containers, bare metal servers, and in hybrid environments. Kubernetes is the most common deployment target but not the only one.“Vault can replace an HSM”Vault can integrate with HSMs (via auto-unseal and PKCS#11 seal) and provides many HSM-like capabilities for application workloads. But Vault is software — its security properties depend on the host, the OS, and the KMS backing it. Hardware security modules provide tamper-evident, FIPS 140–2/3 certified key storage that software cannot replicate. They solve different threat models.“Vault namespace isolation is available in the open-source version”It is not. Namespaces are Vault Enterprise. In OSS, isolation is achieved through separate Vault clusters or careful path-based policy design.What’s NextPart 3 moves beyond self-hosted Vault to compare the managed cloud alternatives: AWS Secrets Manager, GCP Secret Manager, and Azure Key Vault. It covers:How managed identities, IAM roles, and EKS IRSA eliminate Secret Zero without running additional infrastructure.Feature comparison: what Vault does that cloud-native secret managers do not (and vice versa).When to use Vault vs when a managed cloud secret service is the right tradeoff.External Secrets Operator (ESO) — syncing secrets from any backend into Kubernetes.The goal is not to use every Vault feature. The goal is to remove permanent credentials from every system that currently holds one.Stay ConnectedIf this helped you think more clearly about secrets management, the best thing you can do is share it with someone building on the same problems.Follow TheProdSDE for more content on platform engineering, cloud architecture, and production systems:🔗 LinkedIn: linkedin.com/in/TheProdSDE🐦 X (Twitter): x.com/TheProdSDE▶️ YouTube: youtube.com/@TheProdSDE✍️ Medium: medium.com/@TheProdSDEEvery article, video, and thread in this space is aimed at one thing: helping engineers build production systems that don’t break quietly.@TheProdSDEHashiCorp Vault Deep Dive was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.