Files
skills/public/security-secrets-management.html
zeekayandHanzo Dev 9e10c1c10e Each llms index points at the other two
hanzoskills.com/llms.txt now opens with the install line, the API
reference index and the company index, so an agent that lands on any
one of the three can find the rest.

robots.txt claimed 537 documents while llms.txt counts 920. The number
is gone from robots.txt; llms.txt derives it.

public/ is regenerated from scripts/site.py, which it had fallen
behind: the copy-prompt menu and agent bar were in the generator and
not in the committed pages. tests/site.mjs passes against the result.

Co-authored-by: Hanzo Dev <[email protected]>
2026-09-11 00:27:59 -07:00

810 lines
34 KiB
HTML

<!doctype html>
<html lang="en"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>security-secrets-management</title>
<meta name="color-scheme" content="dark">
<style>
/* Committed to one visual world: a dark instrument panel. No light variant —
the dot field and the hairline rules only read on black, and a naive
inversion would wash both out. Every colour is painted explicitly so the page
never borrows a host background. */
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
:root{
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
--font-zen-pixel-square:'Zen Pixel Square',monospace;
--mono:var(--font-zen-mono);
--sans:var(--font-zen-sans);
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
--r:999px; --r-soft:14px;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
/* The dot field. A halftone made of one repeating radial-gradient, faded out
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
/* No overflow clip here: the dot field is inset to the box already, and a clip
would cut off the copy-prompt menu. */
.hero{position:relative;border-bottom:1px solid var(--line)}
.hero::before{content:"";position:absolute;inset:0;
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
background-size:7px 7px;
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
pointer-events:none}
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
nav{border-bottom:1px solid var(--line)}
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
justify-content:space-between;align-items:center;gap:1rem}
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--ink);text-decoration:none;
display:inline-flex;align-items:center;gap:.6rem}
.brand i{font-style:normal;color:var(--faint)}
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
text-transform:uppercase;color:var(--soft);text-decoration:none}
nav a.up:hover{color:var(--ink)}
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
h1 em{font-style:normal;color:var(--faint)}
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
line-height:1.2;font-weight:400}
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
.btn.solid:hover{background:#d8d8d4}
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
/* Copy-prompt selector. Each row copies the prompt for its own target. */
.copy{position:relative;display:inline-flex}
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
padding:.4rem;display:flex;flex-direction:column;
box-shadow:0 12px 32px rgba(0,0,0,.75)}
.menu[hidden]{display:none}
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
white-space:nowrap}
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
.mi:hover .mark{color:var(--ink)}
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
letter-spacing:.1em;text-transform:uppercase}
/* Works-with bar: one scrolling row, name and mark per agent. */
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
display:flex;align-items:center}
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
-webkit-overflow-scrolling:touch;
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
.bar::-webkit-scrollbar{display:none}
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
text-decoration:none;background:var(--ground)}
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
.agent .mark{width:.95rem;height:.95rem}
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
p{margin:0 0 1rem;max-width:70ch}
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
li{margin:.22rem 0}
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
text-decoration-color:var(--line-hi)}
a:hover{text-decoration-color:var(--ink)}
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
display:block;overflow-x:auto}
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
.curl{display:block;background:var(--panel);border:1px solid var(--line);
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
white-space:pre;line-height:1.9}
.curl b{color:var(--ink);font-weight:400}
.curl i{font-style:normal;color:var(--faint)}
/* index */
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
#q:focus{outline:none;border-color:var(--soft)}
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
text-transform:uppercase;margin:0 0 2rem}
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
padding-bottom:.45rem}
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
border-radius:var(--r-soft);text-decoration:none}
.row:hover{background:#0a0a0a}
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
color:var(--faint);font-size:.85rem}
footer a{color:var(--soft)}
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
margin:0 0 2rem;font-size:.85rem}
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
border-bottom:1px solid var(--line);padding-bottom:.4rem}
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
.fmap a:hover{text-decoration:underline}
.fmap div{color:var(--faint);line-height:1.5}
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
@media (max-width:640px){
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
.btns{gap:.5rem}
.btn{padding:.75rem 1.15rem;font-size:.68rem}
.copy,.copy .btn{width:100%;justify-content:center}
.menu{left:0;right:0;min-width:0}
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
.strip b{border-right:0;padding-right:0}
.bar{width:100%}
}
</style>
<link rel="alternate" type="text/markdown" href="/security-secrets-management.md">
<link rel="icon" href="/favicon.svg">
<link rel="canonical" href="https://hanzoskills.com/security-secrets-management">
</head>
<!-- Reading this with a machine? Every page here is also plain markdown.
This one: https://hanzoskills.com/security-secrets-management.md
Index: https://hanzoskills.com/llms.txt
Corpus: https://hanzoskills.com/all.md
Append .md to any path for the markdown twin. -->
<body>
<nav><div class="in">
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
<a class="up" href="/">All skills</a>
</div></nav>
<div class="wrap">
<h1>security-secrets-management</h1><p class="lede">Secrets management patterns including vaults, environment variables, key rotation, and secure credential handling for applications</p><h1>Security: Secrets Management</h1>
<p><strong>Scope</strong>: Secrets vaults, credential management, key rotation, secure storage <strong>Lines</strong>: ~380 <strong>Last Updated</strong>: 2025-10-27</p>
<h2>When to Use This Skill</h2>
<p>Activate this skill when:</p>
<ul><li>Storing API keys, passwords, or credentials</li><li>Implementing secrets management for applications</li><li>Integrating with external secret manager, AWS Secrets Manager, or similar</li><li>Rotating encryption keys or credentials</li><li>Managing secrets in CI/CD pipelines</li><li>Preventing credential exposure in code or logs</li><li>Designing multi-environment secret strategies</li></ul>
<h2>Secrets Management Fundamentals</h2>
<h3>What Are Secrets?</h3>
<pre><code class="lang-python">&quot;&quot;&quot;
Secrets are sensitive data that must be protected:
- API keys and tokens
- Database passwords
- Encryption keys
- TLS/SSL certificates
- OAuth client secrets
- Service account credentials
- Signing keys
&quot;&quot;&quot;
# ❌ NEVER DO THIS - Hardcoded secrets (example only, never in production)
API_KEY = &quot;sk_live_abc123def456&quot; # Example of what NOT to do
DB_PASSWORD = &quot;MyP@ssw0rd123&quot; # Example of what NOT to do
# ✅ DO THIS - Environment variables or vault
import os
API_KEY = os.environ.get(&#x27;API_KEY&#x27;)
DB_PASSWORD = vault.get_secret(&#x27;database/password&#x27;)</code></pre>
<h2>Environment Variables</h2>
<h3>Using Environment Variables</h3>
<pre><code class="lang-python">import os
from typing import Optional
# Basic usage
DATABASE_URL = os.environ[&#x27;DATABASE_URL&#x27;] # Raises KeyError if missing
API_KEY = os.environ.get(&#x27;API_KEY&#x27;) # Returns None if missing
API_KEY = os.environ.get(&#x27;API_KEY&#x27;, &#x27;default-value&#x27;) # With default
# Validation helper
def get_required_env(key: str) -&gt; str:
&quot;&quot;&quot;Get required environment variable or raise error&quot;&quot;&quot;
value = os.environ.get(key)
if not value:
raise ValueError(f&quot;Missing required environment variable: {key}&quot;)
return value
# Type conversion
PORT = int(os.environ.get(&#x27;PORT&#x27;, &#x27;8000&#x27;))
DEBUG = os.environ.get(&#x27;DEBUG&#x27;, &#x27;false&#x27;).lower() == &#x27;true&#x27;
# Complex secrets (JSON)
import json
AWS_CREDENTIALS = json.loads(os.environ.get(&#x27;AWS_CREDENTIALS&#x27;, &#x27;{}&#x27;))</code></pre>
<h3>.env Files (Development Only)</h3>
<pre><code class="lang-python"># .env file (NEVER commit to git)
DATABASE_URL=postgresql://user:password@localhost/db
API_KEY=sk_test_abc123
STRIPE_SECRET=sk_test_def456
DEBUG=true
# Load with python-dotenv
from dotenv import load_dotenv
import os
# Load .env file in development
if os.environ.get(&#x27;ENV&#x27;) != &#x27;production&#x27;:
load_dotenv()
DATABASE_URL = os.environ[&#x27;DATABASE_URL&#x27;]</code></pre>
<p><strong>.gitignore</strong>:</p>
<pre><code class="lang-gitignore"># Never commit secrets
.env
.env.local
.env.*.local
secrets.json
credentials.json
*.pem
*.key</code></pre>
<h2>external secret manager</h2>
<h3>Vault Integration (Python)</h3>
<pre><code class="lang-python">import hvac
from typing import Dict, Any
class VaultClient:
&quot;&quot;&quot;external secret manager client wrapper&quot;&quot;&quot;
def __init__(self, url: str = None, token: str = None):
self.url = url or os.environ[&#x27;VAULT_ADDR&#x27;]
self.token = token or os.environ[&#x27;VAULT_TOKEN&#x27;]
self.client = hvac.Client(url=self.url, token=self.token)
if not self.client.is_authenticated():
raise Exception(&quot;Vault authentication failed&quot;)
def get_secret(self, path: str) -&gt; Dict[str, Any]:
&quot;&quot;&quot;Read secret from Vault&quot;&quot;&quot;
response = self.client.secrets.kv.v2.read_secret_version(
path=path,
mount_point=&#x27;secret&#x27;
)
return response[&#x27;data&#x27;][&#x27;data&#x27;]
def write_secret(self, path: str, data: Dict[str, Any]):
&quot;&quot;&quot;Write secret to Vault&quot;&quot;&quot;
self.client.secrets.kv.v2.create_or_update_secret(
path=path,
secret=data,
mount_point=&#x27;secret&#x27;
)
def delete_secret(self, path: str):
&quot;&quot;&quot;Delete secret from Vault&quot;&quot;&quot;
self.client.secrets.kv.v2.delete_metadata_and_all_versions(
path=path,
mount_point=&#x27;secret&#x27;
)
# Usage
vault = VaultClient()
# Read database credentials
db_creds = vault.get_secret(&#x27;database/postgres&#x27;)
DATABASE_URL = (
f&quot;postgresql://{db_creds[&#x27;username&#x27;]}:{db_creds[&#x27;password&#x27;]}&quot;
f&quot;@{db_creds[&#x27;host&#x27;]}:{db_creds[&#x27;port&#x27;]}/{db_creds[&#x27;database&#x27;]}&quot;
)
# Write API key
vault.write_secret(&#x27;api/stripe&#x27;, {
&#x27;secret_key&#x27;: &#x27;sk_live_abc123&#x27;,
&#x27;publishable_key&#x27;: &#x27;pk_live_def456&#x27;
})
# Read API key
stripe_keys = vault.get_secret(&#x27;api/stripe&#x27;)
STRIPE_SECRET = stripe_keys[&#x27;secret_key&#x27;]</code></pre>
<h3>Vault AppRole Authentication</h3>
<pre><code class="lang-python">class VaultAppRoleClient:
&quot;&quot;&quot;Vault client using AppRole authentication&quot;&quot;&quot;
def __init__(self, role_id: str, secret_id: str, url: str = None):
self.url = url or os.environ[&#x27;VAULT_ADDR&#x27;]
self.client = hvac.Client(url=self.url)
# Authenticate with AppRole
response = self.client.auth.approle.login(
role_id=role_id,
secret_id=secret_id
)
self.client.token = response[&#x27;auth&#x27;][&#x27;client_token&#x27;]
# Renew token periodically
self._start_token_renewal()
def _start_token_renewal(self):
&quot;&quot;&quot;Automatically renew token before expiration&quot;&quot;&quot;
import threading
def renew():
while True:
time.sleep(3600) # Renew every hour
try:
self.client.auth.token.renew_self()
except Exception as e:
logger.error(f&quot;Token renewal failed: {e}&quot;)
thread = threading.Thread(target=renew, daemon=True)
thread.start()
# Usage (secure - no token in env)
vault = VaultAppRoleClient(
role_id=os.environ[&#x27;VAULT_ROLE_ID&#x27;],
secret_id=os.environ[&#x27;VAULT_SECRET_ID&#x27;]
)</code></pre>
<h3>Dynamic Database Credentials</h3>
<pre><code class="lang-python">def get_dynamic_db_credentials(vault_client, role: str):
&quot;&quot;&quot;Get short-lived database credentials from Vault&quot;&quot;&quot;
# Vault generates credentials on-demand
response = vault_client.client.secrets.database.generate_credentials(
name=role,
mount_point=&#x27;database&#x27;
)
return {
&#x27;username&#x27;: response[&#x27;data&#x27;][&#x27;username&#x27;],
&#x27;password&#x27;: response[&#x27;data&#x27;][&#x27;password&#x27;],
&#x27;ttl&#x27;: response[&#x27;lease_duration&#x27;] # Credentials expire
}
# Usage
creds = get_dynamic_db_credentials(vault, &#x27;readonly-role&#x27;)
# Connect with temporary credentials
conn = psycopg2.connect(
host=&#x27;localhost&#x27;,
database=&#x27;mydb&#x27;,
user=creds[&#x27;username&#x27;],
password=creds[&#x27;password&#x27;]
)
# Credentials automatically expire after TTL</code></pre>
<h2>AWS Secrets Manager</h2>
<h3>AWS Secrets Manager Integration</h3>
<pre><code class="lang-python">import boto3
import json
from botocore.exceptions import ClientError
class AWSSecretsManager:
&quot;&quot;&quot;AWS Secrets Manager client&quot;&quot;&quot;
def __init__(self, region_name: str = &#x27;us-east-1&#x27;):
self.client = boto3.client(
&#x27;secretsmanager&#x27;,
region_name=region_name
)
def get_secret(self, secret_name: str) -&gt; dict:
&quot;&quot;&quot;Retrieve secret from AWS Secrets Manager&quot;&quot;&quot;
try:
response = self.client.get_secret_value(SecretId=secret_name)
# Secret can be string or binary
if &#x27;SecretString&#x27; in response:
return json.loads(response[&#x27;SecretString&#x27;])
else:
import base64
return base64.b64decode(response[&#x27;SecretBinary&#x27;])
except ClientError as e:
if e.response[&#x27;Error&#x27;][&#x27;Code&#x27;] == &#x27;ResourceNotFoundException&#x27;:
raise ValueError(f&quot;Secret not found: {secret_name}&quot;)
raise
def create_secret(self, secret_name: str, secret_value: dict):
&quot;&quot;&quot;Create new secret&quot;&quot;&quot;
self.client.create_secret(
Name=secret_name,
SecretString=json.dumps(secret_value)
)
def update_secret(self, secret_name: str, secret_value: dict):
&quot;&quot;&quot;Update existing secret&quot;&quot;&quot;
self.client.update_secret(
SecretId=secret_name,
SecretString=json.dumps(secret_value)
)
def rotate_secret(self, secret_name: str, lambda_arn: str):
&quot;&quot;&quot;Enable automatic secret rotation&quot;&quot;&quot;
self.client.rotate_secret(
SecretId=secret_name,
RotationLambdaARN=lambda_arn,
RotationRules={&#x27;AutomaticallyAfterDays&#x27;: 30}
)
# Usage
secrets = AWSSecretsManager(region_name=&#x27;us-west-2&#x27;)
# Get database credentials
db_secret = secrets.get_secret(&#x27;prod/database/postgres&#x27;)
DATABASE_URL = (
f&quot;postgresql://{db_secret[&#x27;username&#x27;]}:{db_secret[&#x27;password&#x27;]}&quot;
f&quot;@{db_secret[&#x27;host&#x27;]}/{db_secret[&#x27;dbname&#x27;]}&quot;
)
# Create API key secret
secrets.create_secret(&#x27;prod/api/stripe&#x27;, {
&#x27;secret_key&#x27;: &#x27;sk_live_abc123&#x27;,
&#x27;publishable_key&#x27;: &#x27;pk_live_def456&#x27;
})</code></pre>
<h3>Caching Secrets</h3>
<pre><code class="lang-python">from functools import lru_cache
import time
class CachedSecretsManager:
&quot;&quot;&quot;Cache secrets to reduce API calls&quot;&quot;&quot;
def __init__(self, secrets_manager):
self.secrets_manager = secrets_manager
self.cache = {}
self.cache_ttl = 300 # 5 minutes
def get_secret(self, secret_name: str) -&gt; dict:
&quot;&quot;&quot;Get secret with caching&quot;&quot;&quot;
now = time.time()
# Check cache
if secret_name in self.cache:
cached_value, cached_time = self.cache[secret_name]
if now - cached_time &lt; self.cache_ttl:
return cached_value
# Fetch from source
value = self.secrets_manager.get_secret(secret_name)
# Update cache
self.cache[secret_name] = (value, now)
return value
def invalidate_cache(self, secret_name: str = None):
&quot;&quot;&quot;Clear cache for secret or all secrets&quot;&quot;&quot;
if secret_name:
self.cache.pop(secret_name, None)
else:
self.cache.clear()</code></pre>
<h2>GCP Secret Manager</h2>
<h3>Google Cloud Secret Manager</h3>
<pre><code class="lang-python">from google.cloud import secretmanager
class GCPSecretsManager:
&quot;&quot;&quot;Google Cloud Secret Manager client&quot;&quot;&quot;
def __init__(self, project_id: str):
self.project_id = project_id
self.client = secretmanager.SecretManagerServiceClient()
def get_secret(self, secret_id: str, version: str = &quot;latest&quot;) -&gt; str:
&quot;&quot;&quot;Access secret version&quot;&quot;&quot;
name = f&quot;projects/{self.project_id}/secrets/{secret_id}/versions/{version}&quot;
response = self.client.access_secret_version(request={&quot;name&quot;: name})
return response.payload.data.decode(&#x27;UTF-8&#x27;)
def create_secret(self, secret_id: str, secret_value: str):
&quot;&quot;&quot;Create new secret&quot;&quot;&quot;
parent = f&quot;projects/{self.project_id}&quot;
# Create secret
secret = self.client.create_secret(
request={
&quot;parent&quot;: parent,
&quot;secret_id&quot;: secret_id,
&quot;secret&quot;: {&quot;replication&quot;: {&quot;automatic&quot;: {}}},
}
)
# Add secret version
self.client.add_secret_version(
request={
&quot;parent&quot;: secret.name,
&quot;payload&quot;: {&quot;data&quot;: secret_value.encode(&#x27;UTF-8&#x27;)},
}
)
def update_secret(self, secret_id: str, secret_value: str):
&quot;&quot;&quot;Add new secret version (updates secret)&quot;&quot;&quot;
parent = f&quot;projects/{self.project_id}/secrets/{secret_id}&quot;
self.client.add_secret_version(
request={
&quot;parent&quot;: parent,
&quot;payload&quot;: {&quot;data&quot;: secret_value.encode(&#x27;UTF-8&#x27;)},
}
)
# Usage
secrets = GCPSecretsManager(project_id=&#x27;my-project&#x27;)
# Get secret
api_key = secrets.get_secret(&#x27;stripe-api-key&#x27;)
# Create secret
secrets.create_secret(&#x27;database-password&#x27;, &#x27;secure-password-123&#x27;)</code></pre>
<h2>Key Rotation</h2>
<h3>Automated Key Rotation</h3>
<pre><code class="lang-python">from datetime import datetime, timedelta
from typing import Callable
class KeyRotationService:
&quot;&quot;&quot;Automated key rotation service&quot;&quot;&quot;
def __init__(self, secrets_manager, notification_service=None):
self.secrets_manager = secrets_manager
self.notification_service = notification_service
def rotate_key(self, secret_name: str, generator: Callable[[], str]):
&quot;&quot;&quot;Rotate a secret key&quot;&quot;&quot;
# Generate new key
new_key = generator()
# Store old key for rollback
old_key = self.secrets_manager.get_secret(secret_name)
try:
# Update with new key
self.secrets_manager.update_secret(secret_name, {&#x27;value&#x27;: new_key})
# Log rotation
logger.info(f&quot;Rotated secret: {secret_name}&quot;)
# Notify team
if self.notification_service:
self.notification_service.send_alert(
f&quot;Secret rotated: {secret_name}&quot;
)
return new_key
except Exception as e:
# Rollback on failure
logger.error(f&quot;Key rotation failed: {e}&quot;)
self.secrets_manager.update_secret(secret_name, old_key)
raise
def check_expiration(self, secret_name: str, max_age_days: int = 90):
&quot;&quot;&quot;Check if secret needs rotation&quot;&quot;&quot;
metadata = self.secrets_manager.get_secret_metadata(secret_name)
last_rotated = metadata[&#x27;last_rotated&#x27;]
age = datetime.now() - last_rotated
if age &gt; timedelta(days=max_age_days):
logger.warning(f&quot;Secret needs rotation: {secret_name} (age: {age.days} days)&quot;)
return True
return False
# Usage
rotation_service = KeyRotationService(secrets_manager)
# Generate new API key
import secrets
def generate_api_key():
return secrets.token_urlsafe(32)
# Rotate key
new_key = rotation_service.rotate_key(&#x27;api/external-service&#x27;, generate_api_key)
# Check if rotation needed
if rotation_service.check_expiration(&#x27;database/password&#x27;, max_age_days=30):
rotation_service.rotate_key(&#x27;database/password&#x27;, generate_strong_password)</code></pre>
<h3>Zero-Downtime Rotation</h3>
<pre><code class="lang-python">class ZeroDowntimeRotation:
&quot;&quot;&quot;Rotate secrets without downtime&quot;&quot;&quot;
def __init__(self, secrets_manager):
self.secrets_manager = secrets_manager
def rotate_with_overlap(self, secret_name: str, new_value: str):
&quot;&quot;&quot;
Dual-key rotation:
1. Add new key (both keys valid)
2. Update services to use new key
3. Remove old key after grace period
&quot;&quot;&quot;
# Get current secret
current = self.secrets_manager.get_secret(secret_name)
# Store both old and new
dual_secret = {
&#x27;primary&#x27;: new_value,
&#x27;secondary&#x27;: current[&#x27;value&#x27;], # Old key still valid
&#x27;rotated_at&#x27;: datetime.utcnow().isoformat()
}
self.secrets_manager.update_secret(secret_name, dual_secret)
logger.info(f&quot;New key active, old key valid for grace period&quot;)
def complete_rotation(self, secret_name: str):
&quot;&quot;&quot;Remove old key after grace period&quot;&quot;&quot;
secret = self.secrets_manager.get_secret(secret_name)
# Keep only primary (new) key
updated = {&#x27;value&#x27;: secret[&#x27;primary&#x27;]}
self.secrets_manager.update_secret(secret_name, updated)
logger.info(f&quot;Rotation completed, old key removed&quot;)
# Usage
rotator = ZeroDowntimeRotation(secrets_manager)
# Phase 1: Add new key
rotator.rotate_with_overlap(&#x27;database/password&#x27;, &#x27;new-password&#x27;)
# Update applications to use new key (manual or automated)
# Wait for all services to migrate (e.g., 24 hours)
# Phase 2: Remove old key
rotator.complete_rotation(&#x27;database/password&#x27;)</code></pre>
<h2>CI/CD Secrets Management</h2>
<h3>GitHub Actions Secrets</h3>
<pre><code class="lang-yaml"># .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Deploy to production
env:
# Access GitHub secrets
DATABASE_URL: ${{ secrets.DATABASE_URL }}
API_KEY: ${{ secrets.API_KEY }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
run: |
./deploy.sh</code></pre>
<h3>Vault Integration in CI/CD</h3>
<pre><code class="lang-yaml"># .github/workflows/deploy.yml
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Import Secrets from Vault
uses: hashicorp/vault-action@v2
with:
url: https://vault.example.com
token: ${{ secrets.VAULT_TOKEN }}
secrets: |
secret/data/database username | DATABASE_USER ;
secret/data/database password | DATABASE_PASSWORD ;
secret/data/api stripe_key | STRIPE_KEY
- name: Deploy
run: |
echo &quot;Using secrets from Vault&quot;
./deploy.sh</code></pre>
<h2>Security Best Practices</h2>
<h3>Secrets Management Checklist</h3>
<p><strong>Storage</strong>:</p>
<ul><li>[ ] Never commit secrets to version control</li><li>[ ] Use secrets manager (Vault, AWS, GCP)</li><li>[ ] Encrypt secrets at rest and in transit</li><li>[ ] Use separate secrets per environment</li><li>[ ] Implement access control (least privilege)</li></ul>
<p><strong>Rotation</strong>:</p>
<ul><li>[ ] Rotate secrets regularly (30-90 days)</li><li>[ ] Automate rotation where possible</li><li>[ ] Support zero-downtime rotation</li><li>[ ] Audit rotation events</li><li>[ ] Have rollback plan</li></ul>
<p><strong>Access</strong>:</p>
<ul><li>[ ] Use short-lived credentials when possible</li><li>[ ] Implement audit logging</li><li>[ ] Restrict secret access by role</li><li>[ ] Monitor secret access patterns</li><li>[ ] Alert on unauthorized access</li></ul>
<p><strong>Development</strong>:</p>
<ul><li>[ ] Use different secrets for dev/staging/prod</li><li>[ ] Never log secrets</li><li>[ ] Sanitize secrets in error messages</li><li>[ ] Use .gitignore for local secret files</li><li>[ ] Document secret requirements</li></ul>
<p><strong>Detection</strong>:</p>
<ul><li>[ ] Scan commits for secrets (git-secrets, truffleHog)</li><li>[ ] Monitor for exposed secrets (GitHub, public repos)</li><li>[ ] Alert on secret usage anomalies</li><li>[ ] Regular security audits</li></ul>
<h2>Common Vulnerabilities</h2>
<h3>Secrets in Code</h3>
<pre><code class="lang-python"># ❌ VULNERABLE - Hardcoded secrets
API_KEY = &quot;sk_live_abc123def456&quot;
# ❌ VULNERABLE - Secrets in comments
# Production API key: sk_live_abc123def456
# ❌ VULNERABLE - Secrets in error messages (example of what NOT to do)
try:
connect(password=&quot;secret123&quot;) # Example only - never hardcode passwords
except Exception as e:
logger.error(f&quot;Connection failed with password: {password}&quot;)
# ✅ SECURE - Environment variables
API_KEY = os.environ[&#x27;API_KEY&#x27;]
# ✅ SECURE - Vault integration
API_KEY = vault.get_secret(&#x27;api/stripe&#x27;)[&#x27;key&#x27;]
# ✅ SECURE - Sanitized errors
try:
connect(password=password)
except Exception as e:
logger.error(&quot;Connection failed (credentials redacted)&quot;)</code></pre>
<h3>Secrets Detection Tools</h3>
<pre><code class="lang-bash"># git-secrets (prevent committing secrets)
git secrets --install
git secrets --register-aws
git secrets --scan
# truffleHog (scan repository history)
trufflehog git https://github.com/user/repo
# detect-secrets (baseline scanning)
detect-secrets scan &gt; .secrets.baseline
detect-secrets audit .secrets.baseline
# gitleaks (fast secrets scanner)
gitleaks detect --source . --verbose</code></pre>
<h2>Related Skills</h2>
<ul><li><code>security-authentication.md</code> - Password and credential management</li><li><code>security-authorization.md</code> - Access control for secrets</li><li><code>cryptography-encryption.md</code> - Encrypting secrets</li><li><code>cicd-github-actions.md</code> - CI/CD secrets management</li></ul>
<hr>
<p><strong>Last Updated</strong>: 2025-10-27 <strong>Format Version</strong>: 1.0 (Atomic)</p>
<footer>
<div class="fmap">
<div><b>Build</b>
<a href="https://hanzo.app">hanzo.app</a> app builder
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
<div><b>Run</b>
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
<div><b>Account</b>
<a href="https://hanzo.id">hanzo.id</a> sign in
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
<div><b>Company</b>
<a href="https://hanzo.ai">hanzo.ai</a> canonical
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
</div>
<div class="fend"><a href="/security-secrets-management.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
</footer>
</div></body></html>