Lesson 4 of 10
Secrets Management
Secrets - API keys, database passwords, certificates, tokens - are the keys to your kingdom. Hardcoded or poorly managed secrets are responsible for hundreds of major breaches. Proper secrets management treats credentials like sensitive data: short-lived, access-controlled, and audited.
Why Secrets Leak and How to Prevent It
# Common secrets leakage vectors
1. Hardcoded in source code (committed to git):
# config.py
DATABASE_URL = "postgresql://admin:SuperSecret123@db.prod:5432/app"
AWS_SECRET_KEY = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
# These are now in git history FOREVER even if deleted later
2. Environment variable leak (process listing):
# ps aux shows: python app.py DATABASE_PASSWORD=secret
# docker inspect shows all env vars including secrets
3. Log file leakage:
# Error logging request headers: Authorization: Bearer sk-prod-AbCdEf...
# Logging request bodies containing passwords
4. Docker image history:
docker history myimage # Shows each RUN layer - ENV commands visible
# BAD Dockerfile:
# ENV SECRET_KEY="my-production-secret" ← permanent in image history!
# CORRECT approaches:
# Environment variables (better - but still check docker inspect/logs)
import os
db_url = os.environ.get('DATABASE_URL')
if not db_url:
raise ValueError("DATABASE_URL environment variable not set")
# Better: Use a secrets manager (BEST)
import boto3
client = boto3.client('secretsmanager', region_name='us-east-1')
secret = client.get_secret_value(SecretId='prod/app/database')
db_password = json.loads(secret['SecretString'])['password']HashiCorp Vault
# HashiCorp Vault - enterprise secrets management platform
# Start development Vault server
vault server -dev -dev-root-token-id="dev-token"
# Store a secret
export VAULT_ADDR='http://127.0.0.1:8200'
export VAULT_TOKEN='dev-token'
vault kv put secret/app/database \
password="Sup3rS3curePass!" \
host="db.internal.company.com" \
port="5432"
# Read a secret
vault kv get secret/app/database
vault kv get -field=password secret/app/database
# Dynamic secrets (best practice) - database secrets engine
vault secrets enable database
vault write database/config/my-postgresql \
plugin_name=postgresql-database-plugin \
allowed_roles="app-role" \
connection_url="postgresql://vault:VaultPass@db:5432/app"
vault write database/roles/app-role \
db_name=my-postgresql \
creation_statements="CREATE ROLE {{name}} WITH PASSWORD '{{password}}' ..." \
default_ttl="1h" max_ttl="24h"
# Each application request generates a UNIQUE database user that expires in 1 hour
vault read database/creds/app-role
# Key Value
# lease_duration 1h0m0s
# username v-app-xyz12345
# password random-generated
# Python integration
import hvac
client = hvac.Client(url='https://vault.internal:8200', token=os.environ['VAULT_TOKEN'])
secret = client.secrets.kv.v2.read_secret_version(path='app/database')
password = secret['data']['data']['password']Common Mistakes
- Rotating leaked secrets after public disclosure is enough - if a secret appeared in any public git commit, assume it's been scraped and used. Rotate AND audit access logs for the exposure window
- Using long-lived static credentials instead of short-lived dynamic ones - a 90-day database password provides a 90-day window if compromised; dynamic Vault credentials expire in 1 hour
- Application secrets in Kubernetes ConfigMaps - ConfigMaps are not encrypted; use Kubernetes Secrets (base64 encoded - still need encryption at rest enabled) or integrate with Vault/AWS Secrets Manager
Tip
Tip
Practice Secrets Management in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Practice Task
Note
Practice Task - (1) Write a working example of Secrets Management from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Secrets Management is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Key Takeaways
- Secrets - API keys, database passwords, certificates, tokens - are the keys to your kingdom.
- Rotating leaked secrets after public disclosure is enough - if a secret appeared in any public git commit, assume it's been scraped and used. Rotate AND audit access logs for the exposure window
- Using long-lived static credentials instead of short-lived dynamic ones - a 90-day database password provides a 90-day window if compromised; dynamic Vault credentials expire in 1 hour
- Application secrets in Kubernetes ConfigMaps - ConfigMaps are not encrypted; use Kubernetes Secrets (base64 encoded - still need encryption at rest enabled) or integrate with Vault/AWS Secrets Manager
Finished this lesson?