Wednesday, November 19, 2025

HashiCorp Vault Leases

HashiCorp Vault Leases - Complete Lifecycle Management Guide

HashiCorp Vault Leases - Complete Lifecycle Management Guide

🎯 Prerequisites: Vault FundamentalsAuthentication MethodsPolicies & Access ControlToken ManagementSecrets Engines
📚 What You'll Master:
Complete lease lifecycle management: renewal strategies, revocation patterns, TTL inheritance, prefix operations, production use cases

Vault Leases Overview

What Are Vault Leases?

One of the key features of dynamic secrets is their limited lifetime. But how is that lifetime enforced by Vault? Through vault leases - the mechanism that controls the lifecycle of dynamically generated credentials.

🔑 Core Purpose:
Leases control the lifecycle of dynamic secrets by either:
  • Renewing - Extending the lifetime of a dynamic secret
  • Revoking - Terminating the dynamic secret before expiration

Leases Apply to Both Secrets and Tokens

Leases are a construct that exists for both dynamic secrets and service tokens:

Aspect Dynamic Secrets Service Tokens
Terminology Leases TTL (Time to Live)
Lifecycle Managed via lease commands Managed via token commands
Common Feature Both have limited lifetime and managed lifecycle
📊 Key Difference:
Same concept, different language. Dynamic secrets use "lease" terminology while service tokens use "TTL" terminology, but both represent a limited lifetime that you can manage through renewal or revocation.

Lease Properties & Metadata

Three Core Lease Properties

Every lease includes metadata that defines its characteristics and behavior:

✅ Lease Metadata Components:
  1. lease_id - Unique identifier constructed from path + unique ID
  2. lease_duration - Countdown timer showing remaining validity period
  3. renewable - Boolean indicating whether lease can be extended

Lease ID Structure

The lease_id is a construct that combines:

Format: <path_to_secret>/<unique_id>

Example: consul/creds/web/a1b2c3d4-e5f6-7890-abcd-ef1234567890

Components:
• Path: consul/creds/web
• Unique ID: a1b2c3d4-e5f6-7890-abcd-ef1234567890

Lease Duration

Lease duration functions as a countdown timer:

  • Initial Value - Set from default TTL at creation time
  • Countdown - Continuously decreases until expiration
  • Example - Starts at 30 minutes, counts down to zero
  • Expiration Behavior - When duration reaches zero, lease and secret are revoked

Renewable Property

The renewable Boolean determines lease extension capability:

  • true - Lease can be renewed/extended before expiration
  • false - Fixed lifetime from creation, cannot be extended
  • Configuration - Set at object level (role, group, user) within secrets engine
⚠️ No Direct Lookup Command:
Unlike tokens which have vault token lookup, there is no vault lease lookup command. You must use the special path /sys/leases/lookup to retrieve lease information.

Lease Duration & TTL Inheritance

Understanding Lease Duration

Lease duration is essentially the Time to Live (TTL) for a dynamic secret. Just like tokens have TTLs, dynamic secrets have lease durations that determine their validity period.

TTL Value Sources

When a dynamic secret or token is created, it inherits TTL values from multiple potential sources. The lease derives two critical values:

  • Default TTL - Initial lease duration when secret is created
  • Max TTL - Maximum allowable lifetime for the lease

TTL Inheritance Hierarchy

TTL values are inherited in a specific precedence order, from most general to most specific:

🎯 TTL Precedence (Lowest to Highest):
  1. System-Wide Defaults - Vault server configuration settings
  2. Mount Point Configuration - Secrets engine mount settings
  3. Object-Level Settings - Role, group, or user configuration

1. System-Wide Default TTL

Definition: Global default and max TTL defined in Vault server configuration

Scope: Applies to all leases and tokens unless overridden

Priority: Lowest - Used only when no other TTL is specified

Configuration: Set in Vault server config file

2. Mount Point TTL

Definition: Default and max TTL configured on secrets engine mount

Scope: Applies to all secrets from that specific engine

Priority: Medium - Overrides system-wide settings

Configuration: Set during engine enablement or via tune command

Example: vault secrets tune -default-lease-ttl=30m aws

3. Object-Level TTL

Definition: TTL configured on specific objects within secrets engine

Scope: Applies only to secrets generated from that object

Priority: Highest - Overrides both system and mount settings

Object Types: Roles, groups, users (depends on engine type)

Example: vault write consul/roles/web ttl=1h max_ttl=2h

TTL Inheritance Example

Level Default TTL Max TTL Applied?
System 32 days 32 days ❌ Overridden
Mount Point 30 minutes 2 hours ❌ Overridden
Role (Object) 1 hour 4 hours Applied
🎯 Key Concept:
The most specific configuration wins. Object-level settings override mount settings, which override system settings. This allows granular control over lease lifetimes for different use cases.

Renewable Property Configuration

The renewable property is set at the object level within the secrets engine:

Configuration Example:
vault write consul/roles/web \
    policies="web" \
    ttl=1h \
    max_ttl=2h \
    renewable=false

Result: Secrets from this role cannot be renewed

Lease Actions: Renewal & Revocation

Two Primary Lease Operations

When working with leases, you can perform two fundamental operations:

  1. Renew - Extend the lease lifetime
  2. Revoke - Terminate the lease before expiration

Lease Renewal

Renewal Characteristics:

✅ How Renewal Works:
  • Time Basis - Renewal is based on current time, not creation time
  • Increment Specification - Request renewal for specific duration (e.g., 30 minutes)
  • Countdown Reset - Lease duration resets to specified increment from now
  • Max TTL Constraint - Total duration from creation cannot exceed max TTL

Renewal Example:

Initial State:
• Created: 12:00 PM
• Default TTL: 1 hour
• Max TTL: 2 hours
• Current Time: 12:30 PM (30 minutes elapsed)
• Remaining: 30 minutes

Renewal Request at 12:30 PM:
vault lease renew -increment=30m <lease_id>

Result:
• New expiration: 1:00 PM (30 minutes from now)
• Total lifetime: 1 hour (within max TTL of 2 hours) ✅

Invalid Renewal Request at 12:30 PM:
vault lease renew -increment=2h <lease_id>

Result:
• Requested expiration: 2:30 PM (2 hours from now)
• Total lifetime: 2.5 hours (exceeds max TTL) ❌
• Vault response: Lease extended to max available (1:30 PM)
⚠️ Max TTL Enforcement:
If your renewal request would push the total lease lifetime beyond the max TTL (calculated from creation time), Vault will extend the lease only to the maximum allowable duration.

Lease Revocation

Revocation Process:

🔴 Revocation Sequence:
  1. Lease Revocation - Vault immediately invalidates the lease
  2. Queue Deletion Request - Vault queues request to secrets engine
  3. External Cleanup - Secrets engine deletes credential in external system

Example Scenario:

AWS Secrets Engine:
1. You revoke AWS credentials lease
2. Vault immediately marks lease as invalid
3. Vault queues deletion request to AWS
4. AWS secrets engine contacts AWS API
5. IAM credentials deleted from AWS account

Note: Add -sync flag to wait for external confirmation

Token Revocation Cascade

🎯 Important Behavior:
When you revoke a token, Vault automatically revokes all dynamic secrets generated by that token.

Example:
• Token generates 5 AWS credentials
• Token generates 3 database credentials
• Revoke the token
• Result: All 8 credentials are automatically revoked

Prefix Revocation

Prefix revocation allows mass revocation of all leases matching a specific path prefix.

🚨 Critical Warnings:
  • Requires Elevated Permissions - Sudo capability needed
  • Extremely Destructive - Revokes ALL leases on path
  • No Confirmation Prompt - Immediate execution
  • Use Case - Security breach response, credential rotation
Prefix Revocation Example:
vault lease revoke -prefix consul/creds/web/

Effect: Revokes all Consul credentials from web role
Impact: All applications using these credentials lose access
Recovery: Applications must request new credentials

CLI Commands for Lease Management

Lease Command Overview

All lease management at the CLI uses the vault lease command set.

Renew a Lease

Syntax:
vault lease renew [options] <lease_id>

Example:
vault lease renew -increment=30m consul/creds/web/a1b2c3d4

Options:
• -increment=<duration> - Requested extension duration
• -format=json - Output in JSON format

Revoke a Single Lease

Syntax:
vault lease revoke [options] <lease_id>

Example:
vault lease revoke consul/creds/web/a1b2c3d4

Options:
• -sync - Wait for external system confirmation

Revoke by Prefix

Syntax:
vault lease revoke -prefix <path_prefix>

Example:
vault lease revoke -prefix consul/creds/web/

Effect: Revokes ALL leases starting with specified prefix

⚠️ Warning: Requires sudo permissions, extremely destructive

List Leases

Syntax:
vault list sys/leases/lookup/<path>

Example:
vault list sys/leases/lookup/consul/creds/web/

Output: List of active lease IDs at specified path

Note: Returns unique IDs only, prepend path to get full lease_id

Lookup Lease Properties

Syntax:
vault write sys/leases/lookup lease_id=<lease_id>

Example:
vault write sys/leases/lookup lease_id=consul/creds/web/a1b2c3d4

Output Properties:
• expire_time - When lease expires (calculated from last renewal)
• issue_time - Original creation timestamp
• last_renewal - Most recent renewal timestamp
• renewable - Boolean indicating if lease can be renewed
• ttl - Current remaining time to live
⚠️ Lookup Command Quirk:
Unlike most operations, lease lookup requires vault write (not vault read) because you must submit data (the lease_id) as part of the request.

Complete Command Reference

Operation Command Purpose
Renew vault lease renew -increment=30m <id> Extend lease lifetime
Revoke vault lease revoke <id> Terminate single lease
Prefix Revoke vault lease revoke -prefix <path> Mass revocation by path
List vault list sys/leases/lookup/<path> Get active lease IDs
Lookup vault write sys/leases/lookup lease_id=<id> Get lease properties

Production Use Cases

Use Case 1: AWS Credentials with Auto-Renewal

🎯 Globomantics Scenario:
Requirement: Application needs AWS resource access with automatic credential lifecycle management.

Requirements:
  • On-demand credential generation
  • Automatic revocation after 12 hours of inactivity
  • Application remains active with credential renewal

Solution Architecture:

  1. Enable AWS Secrets Engine
    vault secrets enable aws
  2. Configure Role with 12-Hour Lease
    vault write aws/roles/app-role \
        credential_type=iam_user \
        policy_document=@policy.json \
        default_ttl=12h \
        max_ttl=24h
  3. Application Behavior
    • Request AWS credentials at startup
    • Renew credentials every 11 hours (before expiration)
    • If inactive for 12 hours, credentials auto-revoke
    • On activity resume, request new credentials
🎯 Benefits:
  • No permanent credentials stored in application
  • Automatic cleanup of inactive application credentials
  • Active applications maintain access through renewal
  • 12-hour inactivity threshold ensures security

Use Case 2: Consul Tokens with Fixed Expiration

🎯 Globomantics Scenario:
Requirement: Multiple users need Consul tokens with strict expiration and breach response capability.

Requirements:
  • Regular Consul token access for multiple users
  • Fixed 60-minute token lifetime (non-renewable)
  • Ability to revoke all tokens instantly if breach detected

Solution Architecture:

  1. Enable Consul Secrets Engine
    vault secrets enable consul
  2. Configure Role with Non-Renewable 60-Minute TTL
    vault write consul/roles/user-role \
        policies="user-policy" \
        ttl=60m \
        max_ttl=60m \
        renewable=false
  3. Normal Operations
    • Users request Consul tokens as needed
    • Tokens expire after exactly 60 minutes
    • Users request new tokens when needed
  4. Breach Response
    vault lease revoke -prefix consul/creds/user-role/
    • Instantly revokes ALL user tokens
    • Users request new tokens after incident resolution
🎯 Benefits:
  • Fixed 60-minute maximum exposure window
  • No token renewal prevents indefinite access
  • Prefix revocation enables rapid breach response
  • Forces regular credential rotation through expiration

Complete Hands-On Lab

Lab Environment Setup

Terminal 1 - Start Vault Server:
vault server -dev

Terminal 2 - Configure Environment:
export VAULT_ADDR='http://127.0.0.1:8200'
export VAULT_TOKEN='<root_token>'
vault login ${VAULT_TOKEN}

Terminal 3 - Start Consul Agent:
consul agent -dev -config-dir=./config

Lab Prerequisites

This lab assumes you have already completed the Consul secrets engine setup from the previous module:

  • Consul agent running with ACL enabled
  • Consul secrets engine enabled in Vault
  • Consul role configured with 1h TTL and 2h max TTL

Lab 1: Generate Leases

Generate Multiple Consul Credentials:

# Generate first credential
vault read consul/creds/web

# Output shows:
# lease_id: consul/creds/web/a1b2c3d4-e5f6-7890...
# lease_duration: 3600 (1 hour)
# lease_renewable: true
# token: <consul_token>

# Generate three more credentials
vault read consul/creds/web
vault read consul/creds/web
vault read consul/creds/web
📊 Lease ID Structure:
consul/creds/web/a1b2c3d4-e5f6-7890-abcd-ef1234567890
• Path: consul/creds/web
• Unique ID: a1b2c3d4-e5f6-7890-abcd-ef1234567890

Lab 2: Renew a Lease

Standard Renewal:

# Renew with 30-minute increment
vault lease renew -increment=30m consul/creds/web/a1b2c3d4...

# Output:
# lease_id: consul/creds/web/a1b2c3d4...
# lease_duration: 1800 (30 minutes)
# lease_renewable: true

# Note: Original 1-hour lease shortened to 30 minutes!
⚠️ Renewal Behavior:
Specifying -increment=30m sets the lease duration to 30 minutes from NOW, not adding 30 minutes to remaining time. This can actually shorten the lease if the increment is less than remaining duration.

Lookup Lease Properties:

# Check lease details
vault write sys/leases/lookup lease_id=consul/creds/web/a1b2c3d4...

# Output shows:
# expire_time: 2025-11-20T13:30:00Z (calculated from last renewal)
# issue_time: 2025-11-20T12:00:00Z (original creation)
# last_renewal: 2025-11-20T13:00:00Z (most recent renewal)
# renewable: true
# ttl: 1757 (29 minutes, 17 seconds remaining)

# Run again to see countdown
vault write sys/leases/lookup lease_id=consul/creds/web/a1b2c3d4...
# ttl: 1719 (28 minutes, 39 seconds remaining)

Lab 3: Exceed Max TTL

Attempt to Exceed Maximum:

# Try to renew for 2 hours
vault lease renew -increment=2h consul/creds/web/a1b2c3d4...

# Vault response:
# WARNING: Request could not be honored
# Effective max TTL less than requested increment
# Max available from creation time: 2 hours
# Requested from renewal time: 2 hours
# Result: Lease capped at maximum available (1h 57m)

# lease_id: consul/creds/web/a1b2c3d4...
# lease_duration: 7020 (1 hour, 57 minutes)
# lease_renewable: true
🎯 Max TTL Calculation:
• Original creation: 12:00 PM
• Max TTL: 2 hours (expires at 2:00 PM)
• Renewal request at: 12:03 PM
• Requested increment: 2 hours (would expire at 2:03 PM)
• Vault caps at: 1:57 minutes remaining (expires at 2:00 PM exactly)

Lab 4: List Active Leases

# Get list of active lease IDs
vault list sys/leases/lookup/consul/creds/web/

# Output (unique IDs only):
# Keys
# ----
# a1b2c3d4-e5f6-7890-abcd-ef1234567890
# b2c3d4e5-f6a7-8901-bcde-f12345678901
# c3d4e5f6-a7b8-9012-cdef-123456789012
# d4e5f6a7-b8c9-0123-def1-234567890123

# Note: Prepend "consul/creds/web/" for full lease_id

Lab 5: Revoke Single Lease

# Revoke specific lease
vault lease revoke consul/creds/web/a1b2c3d4-e5f6-7890-abcd-ef1234567890

# Output:
# Success! Revoked lease: consul/creds/web/a1b2c3d4...
# (queued for deletion in Consul)

# Verify revocation
vault list sys/leases/lookup/consul/creds/web/

# Output (first ID now missing):
# Keys
# ----
# b2c3d4e5-f6a7-8901-bcde-f12345678901
# c3d4e5f6-a7b8-9012-cdef-123456789012
# d4e5f6a7-b8c9-0123-def1-234567890123

Lab 6: Prefix Revocation

# Revoke ALL leases at path
vault lease revoke -prefix consul/creds/web/

# Output:
# Success! Revoked leases (queued for deletion):
# consul/creds/web/b2c3d4e5...
# consul/creds/web/c3d4e5f6...
# consul/creds/web/d4e5f6a7...

# Verify all leases gone
vault list sys/leases/lookup/consul/creds/web/

# Output:
# No value found at sys/leases/lookup/consul/creds/web/
🚨 Production Warning:
Prefix revocation immediately invalidates ALL credentials at the specified path. In production:
  • Verify path before executing
  • Coordinate with application teams
  • Plan for credential reissuance
  • Document as part of incident response

Lab 7: Verify Consul Token Revocation

# List Consul ACL tokens
consul acl token list -format json | jq -r '.[].AccessorID'

# Before revocation: Shows multiple tokens
# After revocation: Vault-generated tokens removed

# Demonstrates end-to-end lifecycle:
# 1. Vault generates Consul token
# 2. Vault manages lease
# 3. Vault revokes lease
# 4. Vault deletes token in Consul

Production Best Practices

🎯 Deployment Guidelines:
  1. Renewal Strategy - Implement renewal before 75% of lease duration expires
  2. Error Handling - Handle renewal failures gracefully, request new credentials
  3. TTL Configuration - Set appropriate defaults for application types:
    • Short-lived: User sessions (30m-1h)
    • Medium-lived: Application credentials (4h-12h)
    • Long-lived: Service accounts (24h max)
  4. Max TTL Enforcement - Always set max TTL to enforce credential rotation
  5. Monitoring - Track lease expiration patterns and renewal failures
  6. Incident Response - Document prefix revocation procedures
  7. Testing - Test renewal and revocation in staging before production
  8. Automation - Automate lease renewal in application code

Key Takeaways

  • Universal Leases - All dynamic secrets and service tokens have leases/TTLs
  • Renewal Timing - Based on current time, not creation time
  • Max TTL Constraint - Total lifetime from creation cannot exceed max TTL
  • Revocation Process - Immediate lease invalidation, queued external deletion
  • Token Cascade - Revoking a token revokes all associated dynamic secrets
  • Prefix Power - Mass revocation requires sudo, use with extreme caution
  • No Direct Lookup - Use /sys/leases/lookup path for lease properties
  • Lifecycle Management - Implement automated renewal and error handling

What's Next?

With lease management mastered, you now have complete control over the Vault ecosystem: authentication, authorization, secrets storage and generation, and credential lifecycle management. The next steps involve production deployment topics like high availability, disaster recovery, and enterprise features.

🎯 Practice Challenge:
Build a complete credential lifecycle system:
  1. Configure multiple secrets engines with different TTL strategies
  2. Implement automated lease renewal in application code
  3. Create monitoring for lease expiration patterns
  4. Design incident response plan with prefix revocation procedures
  5. Test renewal failures and credential reacquisition
  6. Build dashboard showing active leases and expiration timeline

Congratulations! You've completed the HashiCorp Vault Associate certification learning path covering fundamentals, authentication, policies, tokens, secrets engines, and lease management. You're now equipped to implement enterprise-grade secrets management with complete lifecycle control!

HashiCorp Vault Secrets Engines

HashiCorp Vault Secrets Engines - Complete Implementation Guide

HashiCorp Vault Secrets Engines - Complete Implementation Guide

🎯 Prerequisites: Vault FundamentalsAuthentication MethodsPolicies & Access ControlToken Management
📚 What You'll Master:
Complete secrets engine implementation: static vs dynamic secrets, KV versioning, Transit encryption, Consul integration, response wrapping with production examples

Secrets Engines Overview

What Are Secrets Engines?

Secrets engines are the what of Vault - they define what Vault actually does. They are plugins incorporated into Vault that handle sensitive data in three fundamental ways:

🔑 Three Core Functions:
  • Store sensitive data - Manage access to externally-generated secrets
  • Generate sensitive data - Dynamically create credentials and manage their lifecycle
  • Encrypt data - Provide encryption services without storing the data itself

Secrets Engine Categories

Cloud Secrets Engines

  • AWS - Dynamic IAM credentials
  • Azure - Service principal management
  • GCP - Service account key generation

Database Secrets Engines

  • PostgreSQL - Dynamic database credentials
  • MySQL/MariaDB - User provisioning
  • MongoDB - Role-based access
  • Microsoft SQL Server - Dynamic login creation

Internal Vault Engines

  • Key-Value (KV) - Static secret storage
  • Identity - Client tracking and entity management
  • Transit - Encryption as a service
  • Cubbyhole - Per-token isolated storage

Identity Source Engines

  • Active Directory - AD credential rotation
  • OpenLDAP - LDAP credential management

Certificate Engines

  • PKI - Internal Certificate Authority
  • SSH - SSH certificate generation

HashiCorp Product Engines

  • Consul - ACL token generation
  • Nomad - Token management
📊 Engine Count: Vault includes approximately 22+ different secrets engines, each designed for specific use cases. Check the official documentation for the complete and current list.

Special Engines: Identity & Cubbyhole

Identity Secrets Engine

The Identity engine is a special internal engine that maintains client information within Vault.

✅ Identity Engine Characteristics:
  • Enabled by default - Active immediately when Vault starts
  • Cannot be disabled - Required for Vault operations
  • Single instance only - No multiple instances allowed
  • Tracks authenticated clients - Maintains entity records

Identity Engine Components:

  • Entities - Represent clients that have authenticated to Vault
  • Aliases - Map authentication method identities to entities
  • Groups - Organize entities for policy management

Cubbyhole Secrets Engine

The Cubbyhole engine provides per-token isolated storage - a private storage area for each service token.

🔒 Cubbyhole Unique Properties:
  • Enabled by default - Automatically available
  • Cannot be disabled or moved - Fixed infrastructure component
  • Per service token allocation - Each token gets its own cubby
  • Token-exclusive access - Only the owning token can access
  • Root token has NO access - True token isolation
🎯 Key Concept:
The Cubbyhole is one of the rare instances where the root token has no special access. Each token's cubbyhole is completely isolated and accessible only by that specific token.

Static vs Dynamic Secrets

Static Secrets

Static secrets store existing data securely within Vault.

Characteristics:

  • Store existing data - Data already generated externally
  • Manual lifecycle - You control when secrets are updated
  • No automatic expiration - Secrets persist until manually deleted
  • Version control - Track changes over time (KV v2)
  • Access control via policies - Define who can read/write

Primary Engine: Key-Value (KV) Secrets Engine

Dynamic Secrets

Dynamic secrets are generated on-demand by Vault and automatically managed throughout their lifecycle.

Characteristics:

  • Generated on demand - Created when requested
  • Lease-based lifetime - Every secret has an expiration
  • Automatic lifecycle management - Vault handles creation and revocation
  • Renewable (optional) - Extend lifetime within max TTL
  • Integration with external systems - Vault manages credentials in target systems

Common Dynamic Engines: Database, AWS, Azure, GCP, Consul, Nomad

Database Secrets Engine Use Case

🎯 Globomantics Scenario:
Requirement: Database administrators need to provide application and developer access to MySQL database with dynamically generated, short-lived credentials.

Solution:
  1. Enable database secrets engine with MySQL plugin
  2. Configure roles for applications (longer TTL) and developers (shorter TTL)
  3. Assign policies granting access to respective roles
  4. Applications and developers request credentials when needed
  5. Vault automatically revokes credentials when leases expire

Key-Value Engine Deep Dive

KV Engine Overview

The Key-Value engine stores static data as key-value pairs at specified paths.

Concept: Path = Key (storage location)
Storage: Key-value pairs stored at that path

KV Version Comparison

Feature Version 1 Version 2
Versioning ❌ No versioning - overwrites on update ✅ Maintains configurable version history
Metadata ❌ No metadata tracking ✅ Full metadata support
Performance ⚡ Faster - fewer storage calls ⚠️ Slightly slower - additional metadata
Delete Behavior ❌ Permanent deletion ✅ Soft delete - recoverable
Upgrade Path ✅ Can upgrade to v2 ❌ Cannot downgrade to v1
Default Version ✅ Default when enabling ⚠️ Must specify during creation

KV Engine Use Case

🎯 Globomantics Scenario:
Requirement: Application developer needs secure storage for API keys with versioning support.

Requirements:
  • Secure location for API key storage
  • Version tracking for API keys
  • Access to previous versions
  • Vault does not generate keys (developer-managed)
Solution:
  1. Enable KV engine version 2
  2. Create policy granting developers access to their path
  3. Developers store and retrieve versioned API keys

KV Version 2 Commands

Write Secret:
vault kv put secret/apikeys/app1 token=xyz123

Read Secret:
vault kv get secret/apikeys/app1
vault kv get -version=1 secret/apikeys/app1

List Keys:
vault kv list secret/apikeys

Delete (Soft):
vault kv delete -versions=1 secret/apikeys/app1

Undelete:
vault kv undelete -versions=1 secret/apikeys/app1

Destroy (Permanent):
vault kv destroy -versions=1 secret/apikeys/app1

Metadata Operations:
vault kv metadata get secret/apikeys/app1
vault kv metadata delete secret/apikeys/app1

Transit Engine - Encryption as a Service

Transit Engine Overview

🔐 Critical Concept:
The Transit engine provides Encryption as a Service - it does NOT store any data submitted to it. Transit only manages encryption keys and performs cryptographic operations.

Transit Engine Capabilities

  • Encrypt/Decrypt - Symmetric encryption operations
  • Sign/Verify - Cryptographic signatures
  • Hash - Generate cryptographic hashes
  • Random Bytes - High-quality random data generation
  • Key Management - Vault manages encryption keys
  • Key Rotation - Automatic key rotation support

Transit Engine Use Case

🎯 Globomantics Scenario:
Requirement: Application needs to encrypt data before writing to object storage.

Challenges:
  • Object storage encryption not trusted or unavailable
  • Application generates data dynamically
  • Vault should not store application data
  • Need centralized key management
Solution:
  1. Enable Transit secrets engine
  2. Create encryption key for application
  3. Grant application access via policy
  4. Application encrypts data before storage
  5. Application decrypts data after retrieval
  6. Vault manages keys, never sees data

Transit Engine Commands

Enable Transit Engine:
vault secrets enable transit

Create Encryption Key:
vault write -f transit/keys/my-key

Encrypt Data:
vault write transit/encrypt/my-key plaintext=$(base64 <<< "secret data")

Decrypt Data:
vault write transit/decrypt/my-key ciphertext="vault:v1:..."

Rotate Key:
vault write -f transit/keys/my-key/rotate

Enabling & Configuring Engines

Secrets Engine Lifecycle

  1. Enable - Mount plugin instance at specified path
  2. Configure - Set engine-specific settings
  3. Tune - Adjust common mount settings
  4. Use - Interact with the engine
  5. Move (optional) - Change mount path if needed
  6. Disable - Remove engine and all data

Core Management Paths

System Mount Path: /sys/mounts
Enable Engine: POST /sys/mounts/:path
Tune Engine: POST /sys/mounts/:path/tune
Move Engine: POST /sys/remount
Disable Engine: DELETE /sys/mounts/:path

CLI Commands

List Engines:

vault secrets list

Enable Engine:

# Default path (engine name)
vault secrets enable kv

# Custom path
vault secrets enable -path=globokv kv

# Specific version
vault secrets enable -path=globokv -version=2 kv

Tune Engine:

vault secrets tune -description="Globomantics KV" globokv
vault secrets tune -default-lease-ttl=30m globokv
vault secrets tune -max-lease-ttl=2h globokv

Move Engine:

vault secrets move globokv globokv-v2
⚠️ Move Impact:
  • Lease revocation - All existing leases are revoked
  • Policy updates required - Paths change, policies must be updated

Disable Engine:

vault secrets disable globokv
🚨 Warning: Disabling a secrets engine permanently deletes all data stored by that engine. This action cannot be undone!

Configuration vs Tuning

Tuning - Common settings for all engines:

  • Description
  • Default TTL
  • Max TTL
  • Force no-cache
  • Audit non-HMAC request/response keys

Configuration - Engine-specific settings:

  • External service connection details
  • Plugin-specific parameters
  • Role definitions
  • Access patterns

Consul Secrets Engine Integration

Consul Engine Overview

The Consul secrets engine dynamically generates Consul ACL tokens based on predefined roles.

Setup Process

Step 1: Enable Consul Engine

vault secrets enable consul

Step 2: Configure Consul Connection

vault write consul/config/access \
    address=127.0.0.1:8500 \
    token=${CONSUL_HTTP_TOKEN}

Step 3: Create Role

vault write consul/roles/web \
    policies="web" \
    ttl=1h \
    max_ttl=2h

Step 4: Generate Credentials

vault read consul/creds/web

Complete Consul Integration Example

# Start Consul agent
consul agent -dev -config-dir=./config

# Bootstrap ACL system
consul acl bootstrap
export CONSUL_HTTP_TOKEN=<SecretID>

# Create Consul policy
consul acl policy create -name web -rules @web-policy.hcl

# Configure Vault
vault write consul/config/access \
    address=127.0.0.1:8500 \
    token=${CONSUL_HTTP_TOKEN}

# Create Vault role
vault write consul/roles/web \
    name=web \
    policies=web \
    ttl=3600 \
    max_ttl=7200

# Generate credentials
vault read consul/creds/web

Response Wrapping & Secure Distribution

Response Wrapping Concept

Response wrapping enables secure secret distribution without the intermediary knowing the secret value.

Problem Statement

⚠️ Challenge:
Control server needs to distribute secrets to worker cluster members. If the control server retrieves secrets and forwards them, the control server knows all secret values. If compromised, all secrets are exposed.

Response Wrapping Solution

✅ Solution Flow:
  1. Control server requests secret with wrapping
  2. Vault creates cubbyhole with secret copy
  3. Vault generates single-use wrapping token
  4. Control server receives only the token (not secret)
  5. Control server distributes token to worker
  6. Worker unwraps token to retrieve secret
  7. Token and cubbyhole automatically destroyed after use

Response Wrapping Benefits

  • Intermediary protection - Distribution systems never see secrets
  • Single-use tokens - Cannot be replayed
  • Automatic cleanup - Cubbyhole destroyed after retrieval
  • Audit trail - Wrapping token usage tracked
  • Time-limited - Wrapping tokens expire

Response Wrapping Commands

Wrap KV Secret:

vault kv get -wrap-ttl=30m secret/apikeys/app1

Wrap Dynamic Credentials:

vault read -wrap-ttl=30m consul/creds/web

Unwrap Secret:

vault unwrap <wrapping_token>

Inspect Wrapping Token:

vault token lookup <wrapping_token>

Wrapping Token Properties

🔑 Token Characteristics:
  • TTL - Set via -wrap-ttl parameter
  • Non-renewable - Cannot extend lifetime
  • Single-use - Destroyed after unwrapping
  • Service token - Batch tokens don't support cubbyholes
  • No max TTL extension - Explicit max TTL equals creation TTL

Complete Hands-On Lab

Lab Environment Setup

Start Vault Dev Server:
vault server -dev

Configure Environment:
export VAULT_ADDR='http://127.0.0.1:8200'
export VAULT_TOKEN='<root_token>'

Login:
vault login ${VAULT_TOKEN}

Lab 1: KV Engine Configuration

Enable KV v2 Engine:

vault secrets enable -path=globokv -version=2 kv

Add Description:

vault secrets tune -description="Globomantics KV v2" globokv

Configure KV Settings:

# Check current config
vault read globokv/config

# Set max versions
vault write globokv/config max_versions=5

# Verify changes
vault read globokv/config

Store Secrets:

# Write initial version
vault kv put globokv/apitokens/d101 token=version1
vault kv put globokv/apitokens/d102 token=version1
vault kv put globokv/apitokens/d103 token=version1

# List keys
vault kv list globokv/apitokens

# Read secret
vault kv get globokv/apitokens/d101

# Update to version 2
vault kv put globokv/apitokens/d101 token=version2

# Read specific version
vault kv get -version=1 globokv/apitokens/d101
vault kv get -version=2 globokv/apitokens/d101

Version Management:

# Delete version (soft delete)
vault kv delete -versions=1 globokv/apitokens/d101

# Check metadata
vault kv metadata get globokv/apitokens/d101

# Undelete version
vault kv undelete -versions=1 globokv/apitokens/d101

# Destroy permanently
vault kv destroy -versions=1 globokv/apitokens/d101

# Delete entire key
vault kv metadata delete globokv/apitokens/d101

Lab 2: Consul Secrets Engine

Setup Consul:

# Create data directory
mkdir -p data

# Start Consul agent
consul agent -dev -config-dir=./config

# Bootstrap ACL (new terminal)
consul acl bootstrap
export CONSUL_HTTP_TOKEN=<SecretID>

# Create policy
consul acl policy create -name web -rules @web-policy.hcl

Configure Vault Consul Engine:

# Enable engine
vault secrets enable consul

# Configure connection
vault write consul/config/access \
    address=127.0.0.1:8500 \
    token=${CONSUL_HTTP_TOKEN}

# Create role
vault write consul/roles/web \
    name=web \
    policies=web \
    ttl=3600 \
    max_ttl=7200

# Generate credentials
vault read consul/creds/web

# Verify on Consul
consul acl token list

Lab 3: API Access

Read Secret via API:

# Get latest version
curl -H "X-Vault-Token: ${VAULT_TOKEN}" \
    ${VAULT_ADDR}/v1/globokv/data/apitokens/d102 | jq

# Get specific version
curl -H "X-Vault-Token: ${VAULT_TOKEN}" \
    "${VAULT_ADDR}/v1/globokv/data/apitokens/d102?version=1" | jq

Lab 4: Response Wrapping

# Wrap KV secret
vault kv get -wrap-ttl=30m globokv/apitokens/d102
# Returns: wrapping_token, wrapping_accessor, creation_time, ttl

# Lookup wrapping token
vault token lookup <wrapping_token>

# Unwrap secret
vault unwrap <wrapping_token>

# Try to lookup again (will fail - single use)
vault token lookup <wrapping_token>

# Wrap dynamic credentials
vault read -wrap-ttl=30m consul/creds/web

# Unwrap credentials
vault unwrap <wrapping_token>

Production Best Practices

🎯 Deployment Guidelines:
  1. Engine Selection - Choose appropriate engine for use case (static vs dynamic)
  2. Version Planning - KV v2 for versioning needs, v1 for performance
  3. TTL Configuration - Set reasonable defaults and maximums
  4. Response Wrapping - Use for secret distribution in automation
  5. Least Privilege - Grant minimal required permissions
  6. Regular Audits - Monitor engine usage and access patterns
  7. Backup Strategy - Regular backups before destructive operations
  8. Testing - Validate in dev before production deployment

Key Takeaways

  • Three Functions - Secrets engines store, generate, or encrypt data
  • Special Engines - Identity and Cubbyhole are unique, default-enabled engines
  • Static vs Dynamic - Choose based on lifecycle management needs
  • KV Versioning - Version 2 provides history, v1 provides performance
  • Transit for Encryption - Provides crypto without storing data
  • Dynamic Lifecycle - Vault manages creation and revocation automatically
  • Response Wrapping - Secure distribution without intermediary knowledge
  • Engine Mobility - Can move engines but impacts leases and policies

What's Next?

With secrets engines mastered, the next critical topic is lease management - understanding how Vault controls the lifetime of dynamically generated secrets and tokens, renewal strategies, and revocation patterns for production environments.

🎯 Practice Challenge:
Build a complete secrets management system:
  1. Deploy multiple KV engines for different application tiers
  2. Configure Consul engine with role-based access patterns
  3. Implement Transit engine for application encryption
  4. Design response wrapping workflow for CI/CD pipeline
  5. Create comprehensive policies for each engine
  6. Build monitoring for secret access patterns

Ready for enterprise secrets management? You now have the foundation to implement comprehensive secrets management with Vault - from simple key-value storage to dynamic credential generation and encryption services. Time to put these concepts into production!

Tuesday, November 18, 2025

HashiCorp Vault Token Management

HashiCorp Vault Token Management - Complete Lifecycle Guide

HashiCorp Vault Token Management - Complete Lifecycle Guide

🎯 Prerequisites: Vault FundamentalsAuthentication MethodsPolicies & Access Control
📚 What You'll Master:
Complete token lifecycle management from creation to revocation with service/batch patterns, TTL optimization, and hierarchy design

Token Overview & Architecture

What Are Vault Tokens?

Tokens are the fundamental currency of Vault operations. Every interaction with Vault requires a token - they're not just authentication artifacts, they're the primary mechanism for accessing any Vault functionality.

🔑 Core Concept:
Without a token, there's virtually nothing you can do with Vault. When you initialize Vault, the first thing generated is a root token because you need some way to access the system initially.

Token Creation Methods

There are three primary ways tokens are created in Vault:

  • Authentication Methods - After successful authentication (userpass, AppRole, etc.), the method returns a token
  • Existing Token Generation - Use an existing token (like root) to create child tokens
  • Root Token Generation - Special operator process using unseal/recovery keys

Token Access Patterns

# Authentication method creates token
vault login -method=userpass username=alice
# Returns: Token for subsequent operations

# Existing token creates child token
vault token create -policy=accounting
# Uses current token to generate new token

# Root token generation (emergency)
vault operator generate-root
# Requires unseal keys, multiple operators

Token Properties & Attributes

Essential Token Properties

Token ID - The actual value submitted for Vault operations

  • Primary credential for API calls
  • Required for all vault CLI operations
  • Sensitive value that must be protected

Accessor - Management handle without operational access

  • View token properties without using the token
  • Check capabilities on specific paths
  • Renew or revoke tokens safely
  • Audit logging without exposing token ID

Type - Defines token behavior (service or batch)

  • Service tokens: Full-featured, persistent storage
  • Batch tokens: Limited features, memory-only

Policies - Associated access control policies

  • Assigned during token creation
  • Can be continuously evaluated
  • Define what the token can access

TTL (Time to Live) - Token validity duration

  • Defines how long token remains valid
  • Can be renewed (for service tokens)
  • Maximum TTL constraints apply

Orphaned Status - Parent-child relationship indicator

  • Orphaned: No parent token
  • Child: Has parent token dependency
  • Affects revocation behavior

Token ID vs Accessor Pattern

🎯 Use Case Example:
Parent process manages worker tokens but shouldn't have operational access to those tokens. Solution: Store accessors in parent process, give token IDs to workers. Parent can monitor, renew, and revoke without being able to access secrets.
# Token operations using ID
vault auth -method=token token=s.xyz123
vault kv get secrets/myapp

# Management operations using accessor
vault token lookup -accessor 8fb95528-57c6-c0a4-514b-42066aae6d39
vault token renew -accessor 8fb95528-57c6-c0a4-514b-42066aae6d39
vault token revoke -accessor 8fb95528-57c6-c0a4-514b-42066aae6d39

Token Types: Service vs Batch

Service Tokens - Full-Featured Default

Characteristics:

  • Persistent Storage - Written to storage backend
  • Full Feature Set - All token capabilities available
  • Accessor Support - Can be managed via accessor
  • Renewable - TTL can be extended
  • Child Token Creation - Can spawn additional tokens
  • Token Prefix - Always begins with s.

Trade-offs:

  • Higher storage overhead
  • Slower creation/revocation
  • Better for long-lived services

Batch Tokens - High-Performance Limited

Characteristics:

  • Memory-Only - Not written to persistent storage
  • Limited Features - Reduced capability set
  • No Accessor - Cannot be managed externally
  • Non-Renewable - Fixed TTL, cannot be extended
  • No Child Tokens - Cannot create additional tokens
  • Token Prefix - Always begins with b.

Trade-offs:

  • Minimal storage overhead
  • Fast creation/automatic cleanup
  • Perfect for high-volume, short-lived operations

Service vs Batch Decision Matrix

✅ Choose Service Tokens When:
  • Long-running services requiring token renewal
  • Parent processes needing to create child tokens
  • Operations requiring accessor-based management
  • Interactive user sessions
  • CI/CD pipelines with complex workflows
⚡ Choose Batch Tokens When:
  • High-volume, short-lived container workloads
  • Horizontally scaling applications (100s-1000s of instances)
  • Limited lifetime jobs (processing, batch operations)
  • No token renewal requirements
  • Minimal security exposure needed

Real-World Scenario: Container Scaling

Scenario: Horizontally-scaling containerized job processor
Requirements:
  • Scales from 10 to 1000+ instances dynamically
  • Each container needs secrets access for job duration only
  • Tokens should automatically expire with container lifecycle
  • No token abuse if container is compromised
Solution: Authentication method configured for batch tokens
# Configure auth method for batch tokens
vault write auth/kubernetes/role/job-processor \
    bound_service_account_names=job-processor \
    bound_service_account_namespaces=production \
    policies=job-secrets \
    token_type=batch \
    ttl=30m

# Result: High-performance tokens for scaling workloads

Token Lifecycle & TTL Management

Token Lifetime Properties

Understanding token TTL involves several interconnected properties:

  • creation_time - UNIX timestamp of token creation
  • creation_ttl - Initial TTL set during creation
  • ttl - Current remaining time (computed value)
  • expire_time - Projected expiration time
  • explicit_max_ttl - Hard maximum limit (if set)
  • issue_time - Human-readable creation time

TTL Hierarchy & Effective Max TTL

Token maximum lifetime is determined by multiple factors in order of precedence:

  1. Explicit Max TTL - Set during token creation, overrides everything
  2. Auth Method Object Max TTL - Set on users/roles within auth method
  3. Mount Max TTL - Set on auth method mount
  4. System Max TTL - Global default (32 days if not configured)
⚠️ Important Rule:
Auth method object max TTL cannot exceed mount max TTL or system max TTL. However, mount max TTL can exceed system max TTL, providing more flexibility at the auth method level.

Token Lifecycle Commands

Create Token with TTL:

vault token create -policy=accounting -ttl=60m

Look Up Token Properties:

# Using token ID
vault token lookup s.xyz123

# Using accessor
vault token lookup -accessor 8fb95528-57c6-c0a4-514b-42066aae6d39

Renew Token:

# Renew current token
vault token renew -increment=60m

# Renew specific token
vault token renew s.xyz123 -increment=30m

Check Token Capabilities:

vault token capabilities s.xyz123 secrets/apikeys

Revoke Token:

# Revoke using token ID
vault token revoke s.xyz123

# Revoke using accessor
vault token revoke -accessor 8fb95528-57c6-c0a4-514b-42066aae6d39

# Revoke current token
vault token revoke -self

Root Tokens & Emergency Access

Root Token Characteristics

🚨 Critical Security Properties:
  • Unlimited Access - Can perform any operation in Vault
  • No Expiration - Only token type that doesn't expire
  • Dangerous - Can create additional root tokens
  • Emergency Use Only - Should be revoked immediately after use

Root Token Creation Methods

1. Vault Initialization:

vault operator init
# Returns: Unseal keys + initial root token

2. Existing Root Token:

vault token create -policy=root
# Creates new root token from existing root token

3. Emergency Generation Process:

# Multi-operator process
vault operator generate-root -init
vault operator generate-root [OTP] [unseal-key]
# Requires quorum of unseal keys

Root Token Use Cases

🎯 Legitimate Root Token Scenarios:
  • Initial Setup - Configuring first auth methods and policies
  • Auth Method Failure - Primary authentication system unavailable
  • Emergency Recovery - Critical system maintenance requiring full access
  • Disaster Recovery - Restoring Vault configuration from backup

Root Token Best Practices

⚠️ Security Protocol:
  1. Multiple Witnesses - Never use root tokens alone
  2. Immediate Revocation - Revoke as soon as task is complete
  3. Audit Everything - Log all root token activities
  4. No Persistence - Don't store root tokens anywhere
  5. Regular Review - Check for unexpected root tokens
# Always revoke root tokens immediately
vault token revoke -self

# Check for unexpected root tokens
vault list auth/token/accessors | \
  xargs -I {} vault token lookup -accessor {} | \
  grep -A 5 -B 5 "policies.*root"

Periodic Tokens & Long-Running Services

Periodic Token Concept

Periodic tokens solve the problem of long-running services that need persistent access but can't dynamically update their credentials.

Key Properties

  • No Max TTL - Can be renewed indefinitely
  • Period-Based Renewal - Must be renewed within defined period
  • Requires Sudo - Elevated permissions needed for creation
  • Service Token Type - Full-featured with persistent storage

How Periodic Renewal Works

Renewal Behavior:
When you renew a periodic token, Vault ignores your requested increment and always sets the TTL to the defined period. This ensures consistent renewal intervals regardless of the renewal request.
# Create periodic token with 2-hour period
vault token create -policy=database -period=2h

# Renewal always sets TTL to 2 hours
vault token renew s.xyz123 -increment=3h
# Result: TTL set to 2h (period), not 3h (requested)

Real-World Use Case: Legacy Database System

Scenario: Legacy database system integration
Challenge:
  • Database system can't dynamically update token values
  • Restarting database service is operationally expensive
  • Token must remain static for database lifetime
  • Regular token renewal required for security
Solution: Periodic token with automated renewal
# Create periodic token for database
vault token create -policy=database-secrets -period=10m

# Database configuration
VAULT_TOKEN=s.xyz123-periodic-token

# Automated renewal script (cron job)
*/5 * * * * vault token renew s.xyz123-periodic-token

Periodic Token Safety Features

Explicit Max TTL Override:

# Periodic token with absolute maximum
vault token create -policy=database \
    -period=10m \
    -explicit-max-ttl=30d

# Can be renewed every 10 minutes for max 30 days

Natural Expiration:

  • If renewal process stops, token expires after one period
  • Service shutdown automatically ends token lifecycle
  • No manual cleanup required for terminated services

Token Hierarchy & Parent-Child Relationships

Token Hierarchy Purpose

Token hierarchies prevent token escape attacks where users try to avoid revocation by creating child tokens with similar permissions.

Hierarchy Rules

  • Child Dependency - Child tokens depend on parent token
  • Cascade Revocation - Revoking parent revokes all children
  • Service Tokens Only - Batch tokens cannot create children
  • Unlimited Depth - Can create multi-level hierarchies

Orphan Tokens

Orphan tokens have no parent dependency and are created in three ways:

  1. Explicit Creation - Using -orphan flag
  2. Auth Method Tokens - First token from auth method is orphan
  3. Orphaning on Revocation - Convert children to orphans during parent revocation

Hierarchy Management Examples

Create Child Token:

# Child inherits parent relationship
vault token create -policy=worker

Create Orphan Token:

# No parent dependency
vault token create -policy=service -orphan

Revoke with Orphaning:

# Revoke parent, make children orphans
vault token revoke -mode=orphan s.parent-token

Hierarchy Visualization

Root Token (orphan)
├── Management Token (child)
│   ├── Operator Token (grandchild)
│   └── Audit Token (grandchild)
├── Service Token (child)
│   ├── Worker Token #1 (grandchild)
│   └── Worker Token #2 (grandchild)
└── Auth Method Token (orphan)
    ├── User Token (child)
    └── App Token (child)

Complete Implementation Guide

Environment Setup

# Start Vault development server
vault server -dev

# Configure environment
export VAULT_ADDR="http://127.0.0.1:8200"
export ROOT_TOKEN="dev-only-token"

# Login with root token
vault login $ROOT_TOKEN

Service Token Management

Create and Inspect Service Token:

# Create service token
vault token create -policy=default -ttl=60m

# Store token ID and accessor
TOKEN_ID="s.xyz123"
ACCESSOR="8fb95528-57c6-c0a4-514b-42066aae6d39"

# Inspect token properties
vault token lookup $TOKEN_ID

# Inspect via accessor (no ID in output)
vault token lookup -accessor $ACCESSOR

Token Renewal and Capabilities:

# Check current TTL
vault token lookup $TOKEN_ID | grep ttl

# Renew token
vault token renew $TOKEN_ID -increment=30m

# Check capabilities on specific path
vault token capabilities $TOKEN_ID secrets/myapp

# Revoke using accessor
vault token revoke -accessor $ACCESSOR

Batch Token Implementation

# Create batch token
vault token create -type=batch -policy=default -ttl=30m

# Store long batch token ID
BATCH_TOKEN="b.very-long-batch-token-string"

# Inspect batch token (note: no accessor)
vault token lookup $BATCH_TOKEN

# Try to renew (will fail)
vault token renew $BATCH_TOKEN
# Error: batch tokens cannot be renewed

Authentication Method with TTL Configuration

# Enable userpass with custom max TTL
vault auth enable -max-lease-ttl=776h userpass

# Create user with specific token max TTL
vault write auth/userpass/users/alice \
    password=secret123 \
    token_policies=default \
    token_max_ttl=784h

# Login as user
vault login -method=userpass username=alice
# Password: secret123

# Check inherited TTL (will be limited by mount max)
vault token lookup | grep ttl

Periodic Token Creation and Management

# Login as root (required for sudo)
vault login $ROOT_TOKEN

# Create periodic token
vault token create -policy=default -period=2h

# Store periodic token
PERIODIC_TOKEN="s.periodic-token-id"

# Inspect periodic token properties
vault token lookup $PERIODIC_TOKEN

# Renew with large increment (limited to period)
vault token renew $PERIODIC_TOKEN -increment=3h

# Verify TTL is set to period (2h), not increment (3h)
vault token lookup $PERIODIC_TOKEN | grep ttl

Token Hierarchy Testing

# Create parent token
vault token create -policy=default -ttl=1h
PARENT_TOKEN="s.parent-token-id"

# Login with parent token
vault login $PARENT_TOKEN

# Create child token
vault token create -policy=default -ttl=30m
CHILD_TOKEN="s.child-token-id"

# Create orphan token
vault token create -policy=default -orphan -ttl=30m
ORPHAN_TOKEN="s.orphan-token-id"

# Revoke parent (child should be revoked, orphan survives)
vault token revoke $PARENT_TOKEN

# Test child token (should fail)
vault login $CHILD_TOKEN
# Error: token not found

# Test orphan token (should work)
vault login $ORPHAN_TOKEN
# Success: orphan tokens survive parent revocation

Advanced Token Management

List All Token Accessors:

# List all token accessors
vault list auth/token/accessors

# Inspect each token
for accessor in $(vault list -format=json auth/token/accessors | jq -r '.[]'); do
  echo "Accessor: $accessor"
  vault token lookup -accessor $accessor | grep -E "(policies|ttl|type)"
  echo "---"
done

Token Audit and Monitoring:

# Enable audit logging
vault audit enable file file_path=/tmp/vault-audit.log

# Check audit log for accessor usage
tail -f /tmp/vault-audit.log | jq '.auth.accessor'

# Monitor token activities by accessor
grep "8fb95528-57c6-c0a4-514b-42066aae6d39" /tmp/vault-audit.log

Production Token Strategies

Token Type Selection Guidelines

🎯 Decision Framework:
  • Interactive Users → Service tokens with reasonable TTL
  • Long-Running Services → Service tokens with renewal automation
  • Legacy Systems → Periodic tokens with external renewal
  • Container Workloads → Batch tokens from auth methods
  • CI/CD Jobs → Service tokens with job-specific TTL
  • High-Volume APIs → Batch tokens for performance

TTL Configuration Best Practices

⚠️ TTL Strategy Guidelines:
  • Short TTLs - Reduce exposure window, require renewal automation
  • Appropriate Max TTLs - Set sensible limits at system/mount/object levels
  • Renewal Monitoring - Alert on renewal failures for critical tokens
  • Grace Periods - Renew tokens before 80% of TTL expires
  • Emergency Access - Maintain break-glass root token procedures

Token Security Checklist

🔒 Security Controls:
  • Accessor Management - Use accessors for token administration
  • Hierarchical Revocation - Leverage parent-child relationships
  • Regular Auditing - Monitor unexpected long-lived tokens
  • Root Token Governance - Multi-person approval and immediate revocation
  • Automated Cleanup - Remove unused tokens via accessor enumeration

Key Takeaways

  • Tokens Are Everything - All Vault operations require tokens; they're the primary access mechanism
  • Choose Token Types Wisely - Service tokens for flexibility, batch tokens for performance
  • Manage TTLs Strategically - Balance security (short TTLs) with operational efficiency
  • Root Tokens Are Dangerous - Use only for emergencies, always with multiple operators, revoke immediately
  • Accessors Enable Safe Management - Monitor and control tokens without operational access
  • Hierarchies Prevent Escape - Parent revocation cascades to children unless explicitly orphaned
  • Periodic Tokens Solve Legacy Problems - Enable indefinite renewal for systems that can't update credentials

What's Next?

With authentication, policies, and token management mastered, you're ready to explore Vault secrets engines - the core functionality that makes Vault valuable. Learn about static secrets (KV), dynamic secrets (databases, cloud providers), and advanced patterns like secrets rotation and leasing.

🎯 Practice Challenge:
Build a complete token management system:
  1. Create hierarchical token structure for different service tiers
  2. Implement batch tokens for high-volume container workloads
  3. Configure periodic tokens for legacy system integration
  4. Build automated renewal and monitoring for production tokens
  5. Establish root token emergency procedures with multi-operator approval

Ready for secrets management? Your Vault security foundation is complete - authentication methods for identity, policies for authorization, and tokens for access control. Time to put it all together with comprehensive secrets engine implementation!