mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
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]>
810 lines
34 KiB
HTML
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">"""
|
|
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
|
|
"""
|
|
|
|
# ❌ NEVER DO THIS - Hardcoded secrets (example only, never in production)
|
|
API_KEY = "sk_live_abc123def456" # Example of what NOT to do
|
|
DB_PASSWORD = "MyP@ssw0rd123" # Example of what NOT to do
|
|
|
|
# ✅ DO THIS - Environment variables or vault
|
|
import os
|
|
API_KEY = os.environ.get('API_KEY')
|
|
DB_PASSWORD = vault.get_secret('database/password')</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['DATABASE_URL'] # Raises KeyError if missing
|
|
API_KEY = os.environ.get('API_KEY') # Returns None if missing
|
|
API_KEY = os.environ.get('API_KEY', 'default-value') # With default
|
|
|
|
# Validation helper
|
|
def get_required_env(key: str) -> str:
|
|
"""Get required environment variable or raise error"""
|
|
value = os.environ.get(key)
|
|
if not value:
|
|
raise ValueError(f"Missing required environment variable: {key}")
|
|
return value
|
|
|
|
# Type conversion
|
|
PORT = int(os.environ.get('PORT', '8000'))
|
|
DEBUG = os.environ.get('DEBUG', 'false').lower() == 'true'
|
|
|
|
# Complex secrets (JSON)
|
|
import json
|
|
AWS_CREDENTIALS = json.loads(os.environ.get('AWS_CREDENTIALS', '{}'))</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('ENV') != 'production':
|
|
load_dotenv()
|
|
|
|
DATABASE_URL = os.environ['DATABASE_URL']</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:
|
|
"""external secret manager client wrapper"""
|
|
|
|
def __init__(self, url: str = None, token: str = None):
|
|
self.url = url or os.environ['VAULT_ADDR']
|
|
self.token = token or os.environ['VAULT_TOKEN']
|
|
|
|
self.client = hvac.Client(url=self.url, token=self.token)
|
|
|
|
if not self.client.is_authenticated():
|
|
raise Exception("Vault authentication failed")
|
|
|
|
def get_secret(self, path: str) -> Dict[str, Any]:
|
|
"""Read secret from Vault"""
|
|
response = self.client.secrets.kv.v2.read_secret_version(
|
|
path=path,
|
|
mount_point='secret'
|
|
)
|
|
return response['data']['data']
|
|
|
|
def write_secret(self, path: str, data: Dict[str, Any]):
|
|
"""Write secret to Vault"""
|
|
self.client.secrets.kv.v2.create_or_update_secret(
|
|
path=path,
|
|
secret=data,
|
|
mount_point='secret'
|
|
)
|
|
|
|
def delete_secret(self, path: str):
|
|
"""Delete secret from Vault"""
|
|
self.client.secrets.kv.v2.delete_metadata_and_all_versions(
|
|
path=path,
|
|
mount_point='secret'
|
|
)
|
|
|
|
# Usage
|
|
vault = VaultClient()
|
|
|
|
# Read database credentials
|
|
db_creds = vault.get_secret('database/postgres')
|
|
DATABASE_URL = (
|
|
f"postgresql://{db_creds['username']}:{db_creds['password']}"
|
|
f"@{db_creds['host']}:{db_creds['port']}/{db_creds['database']}"
|
|
)
|
|
|
|
# Write API key
|
|
vault.write_secret('api/stripe', {
|
|
'secret_key': 'sk_live_abc123',
|
|
'publishable_key': 'pk_live_def456'
|
|
})
|
|
|
|
# Read API key
|
|
stripe_keys = vault.get_secret('api/stripe')
|
|
STRIPE_SECRET = stripe_keys['secret_key']</code></pre>
|
|
<h3>Vault AppRole Authentication</h3>
|
|
<pre><code class="lang-python">class VaultAppRoleClient:
|
|
"""Vault client using AppRole authentication"""
|
|
|
|
def __init__(self, role_id: str, secret_id: str, url: str = None):
|
|
self.url = url or os.environ['VAULT_ADDR']
|
|
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['auth']['client_token']
|
|
|
|
# Renew token periodically
|
|
self._start_token_renewal()
|
|
|
|
def _start_token_renewal(self):
|
|
"""Automatically renew token before expiration"""
|
|
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"Token renewal failed: {e}")
|
|
|
|
thread = threading.Thread(target=renew, daemon=True)
|
|
thread.start()
|
|
|
|
# Usage (secure - no token in env)
|
|
vault = VaultAppRoleClient(
|
|
role_id=os.environ['VAULT_ROLE_ID'],
|
|
secret_id=os.environ['VAULT_SECRET_ID']
|
|
)</code></pre>
|
|
<h3>Dynamic Database Credentials</h3>
|
|
<pre><code class="lang-python">def get_dynamic_db_credentials(vault_client, role: str):
|
|
"""Get short-lived database credentials from Vault"""
|
|
|
|
# Vault generates credentials on-demand
|
|
response = vault_client.client.secrets.database.generate_credentials(
|
|
name=role,
|
|
mount_point='database'
|
|
)
|
|
|
|
return {
|
|
'username': response['data']['username'],
|
|
'password': response['data']['password'],
|
|
'ttl': response['lease_duration'] # Credentials expire
|
|
}
|
|
|
|
# Usage
|
|
creds = get_dynamic_db_credentials(vault, 'readonly-role')
|
|
|
|
# Connect with temporary credentials
|
|
conn = psycopg2.connect(
|
|
host='localhost',
|
|
database='mydb',
|
|
user=creds['username'],
|
|
password=creds['password']
|
|
)
|
|
|
|
# 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:
|
|
"""AWS Secrets Manager client"""
|
|
|
|
def __init__(self, region_name: str = 'us-east-1'):
|
|
self.client = boto3.client(
|
|
'secretsmanager',
|
|
region_name=region_name
|
|
)
|
|
|
|
def get_secret(self, secret_name: str) -> dict:
|
|
"""Retrieve secret from AWS Secrets Manager"""
|
|
try:
|
|
response = self.client.get_secret_value(SecretId=secret_name)
|
|
|
|
# Secret can be string or binary
|
|
if 'SecretString' in response:
|
|
return json.loads(response['SecretString'])
|
|
else:
|
|
import base64
|
|
return base64.b64decode(response['SecretBinary'])
|
|
|
|
except ClientError as e:
|
|
if e.response['Error']['Code'] == 'ResourceNotFoundException':
|
|
raise ValueError(f"Secret not found: {secret_name}")
|
|
raise
|
|
|
|
def create_secret(self, secret_name: str, secret_value: dict):
|
|
"""Create new secret"""
|
|
self.client.create_secret(
|
|
Name=secret_name,
|
|
SecretString=json.dumps(secret_value)
|
|
)
|
|
|
|
def update_secret(self, secret_name: str, secret_value: dict):
|
|
"""Update existing secret"""
|
|
self.client.update_secret(
|
|
SecretId=secret_name,
|
|
SecretString=json.dumps(secret_value)
|
|
)
|
|
|
|
def rotate_secret(self, secret_name: str, lambda_arn: str):
|
|
"""Enable automatic secret rotation"""
|
|
self.client.rotate_secret(
|
|
SecretId=secret_name,
|
|
RotationLambdaARN=lambda_arn,
|
|
RotationRules={'AutomaticallyAfterDays': 30}
|
|
)
|
|
|
|
# Usage
|
|
secrets = AWSSecretsManager(region_name='us-west-2')
|
|
|
|
# Get database credentials
|
|
db_secret = secrets.get_secret('prod/database/postgres')
|
|
DATABASE_URL = (
|
|
f"postgresql://{db_secret['username']}:{db_secret['password']}"
|
|
f"@{db_secret['host']}/{db_secret['dbname']}"
|
|
)
|
|
|
|
# Create API key secret
|
|
secrets.create_secret('prod/api/stripe', {
|
|
'secret_key': 'sk_live_abc123',
|
|
'publishable_key': 'pk_live_def456'
|
|
})</code></pre>
|
|
<h3>Caching Secrets</h3>
|
|
<pre><code class="lang-python">from functools import lru_cache
|
|
import time
|
|
|
|
class CachedSecretsManager:
|
|
"""Cache secrets to reduce API calls"""
|
|
|
|
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) -> dict:
|
|
"""Get secret with caching"""
|
|
now = time.time()
|
|
|
|
# Check cache
|
|
if secret_name in self.cache:
|
|
cached_value, cached_time = self.cache[secret_name]
|
|
if now - cached_time < 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):
|
|
"""Clear cache for secret or all secrets"""
|
|
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:
|
|
"""Google Cloud Secret Manager client"""
|
|
|
|
def __init__(self, project_id: str):
|
|
self.project_id = project_id
|
|
self.client = secretmanager.SecretManagerServiceClient()
|
|
|
|
def get_secret(self, secret_id: str, version: str = "latest") -> str:
|
|
"""Access secret version"""
|
|
name = f"projects/{self.project_id}/secrets/{secret_id}/versions/{version}"
|
|
|
|
response = self.client.access_secret_version(request={"name": name})
|
|
|
|
return response.payload.data.decode('UTF-8')
|
|
|
|
def create_secret(self, secret_id: str, secret_value: str):
|
|
"""Create new secret"""
|
|
parent = f"projects/{self.project_id}"
|
|
|
|
# Create secret
|
|
secret = self.client.create_secret(
|
|
request={
|
|
"parent": parent,
|
|
"secret_id": secret_id,
|
|
"secret": {"replication": {"automatic": {}}},
|
|
}
|
|
)
|
|
|
|
# Add secret version
|
|
self.client.add_secret_version(
|
|
request={
|
|
"parent": secret.name,
|
|
"payload": {"data": secret_value.encode('UTF-8')},
|
|
}
|
|
)
|
|
|
|
def update_secret(self, secret_id: str, secret_value: str):
|
|
"""Add new secret version (updates secret)"""
|
|
parent = f"projects/{self.project_id}/secrets/{secret_id}"
|
|
|
|
self.client.add_secret_version(
|
|
request={
|
|
"parent": parent,
|
|
"payload": {"data": secret_value.encode('UTF-8')},
|
|
}
|
|
)
|
|
|
|
# Usage
|
|
secrets = GCPSecretsManager(project_id='my-project')
|
|
|
|
# Get secret
|
|
api_key = secrets.get_secret('stripe-api-key')
|
|
|
|
# Create secret
|
|
secrets.create_secret('database-password', 'secure-password-123')</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:
|
|
"""Automated key rotation service"""
|
|
|
|
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]):
|
|
"""Rotate a secret key"""
|
|
|
|
# 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, {'value': new_key})
|
|
|
|
# Log rotation
|
|
logger.info(f"Rotated secret: {secret_name}")
|
|
|
|
# Notify team
|
|
if self.notification_service:
|
|
self.notification_service.send_alert(
|
|
f"Secret rotated: {secret_name}"
|
|
)
|
|
|
|
return new_key
|
|
|
|
except Exception as e:
|
|
# Rollback on failure
|
|
logger.error(f"Key rotation failed: {e}")
|
|
self.secrets_manager.update_secret(secret_name, old_key)
|
|
raise
|
|
|
|
def check_expiration(self, secret_name: str, max_age_days: int = 90):
|
|
"""Check if secret needs rotation"""
|
|
|
|
metadata = self.secrets_manager.get_secret_metadata(secret_name)
|
|
last_rotated = metadata['last_rotated']
|
|
|
|
age = datetime.now() - last_rotated
|
|
|
|
if age > timedelta(days=max_age_days):
|
|
logger.warning(f"Secret needs rotation: {secret_name} (age: {age.days} days)")
|
|
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('api/external-service', generate_api_key)
|
|
|
|
# Check if rotation needed
|
|
if rotation_service.check_expiration('database/password', max_age_days=30):
|
|
rotation_service.rotate_key('database/password', generate_strong_password)</code></pre>
|
|
<h3>Zero-Downtime Rotation</h3>
|
|
<pre><code class="lang-python">class ZeroDowntimeRotation:
|
|
"""Rotate secrets without downtime"""
|
|
|
|
def __init__(self, secrets_manager):
|
|
self.secrets_manager = secrets_manager
|
|
|
|
def rotate_with_overlap(self, secret_name: str, new_value: str):
|
|
"""
|
|
Dual-key rotation:
|
|
1. Add new key (both keys valid)
|
|
2. Update services to use new key
|
|
3. Remove old key after grace period
|
|
"""
|
|
|
|
# Get current secret
|
|
current = self.secrets_manager.get_secret(secret_name)
|
|
|
|
# Store both old and new
|
|
dual_secret = {
|
|
'primary': new_value,
|
|
'secondary': current['value'], # Old key still valid
|
|
'rotated_at': datetime.utcnow().isoformat()
|
|
}
|
|
|
|
self.secrets_manager.update_secret(secret_name, dual_secret)
|
|
|
|
logger.info(f"New key active, old key valid for grace period")
|
|
|
|
def complete_rotation(self, secret_name: str):
|
|
"""Remove old key after grace period"""
|
|
|
|
secret = self.secrets_manager.get_secret(secret_name)
|
|
|
|
# Keep only primary (new) key
|
|
updated = {'value': secret['primary']}
|
|
|
|
self.secrets_manager.update_secret(secret_name, updated)
|
|
|
|
logger.info(f"Rotation completed, old key removed")
|
|
|
|
# Usage
|
|
rotator = ZeroDowntimeRotation(secrets_manager)
|
|
|
|
# Phase 1: Add new key
|
|
rotator.rotate_with_overlap('database/password', 'new-password')
|
|
|
|
# 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('database/password')</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 "Using secrets from Vault"
|
|
./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 = "sk_live_abc123def456"
|
|
|
|
# ❌ VULNERABLE - Secrets in comments
|
|
# Production API key: sk_live_abc123def456
|
|
|
|
# ❌ VULNERABLE - Secrets in error messages (example of what NOT to do)
|
|
try:
|
|
connect(password="secret123") # Example only - never hardcode passwords
|
|
except Exception as e:
|
|
logger.error(f"Connection failed with password: {password}")
|
|
|
|
# ✅ SECURE - Environment variables
|
|
API_KEY = os.environ['API_KEY']
|
|
|
|
# ✅ SECURE - Vault integration
|
|
API_KEY = vault.get_secret('api/stripe')['key']
|
|
|
|
# ✅ SECURE - Sanitized errors
|
|
try:
|
|
connect(password=password)
|
|
except Exception as e:
|
|
logger.error("Connection failed (credentials redacted)")</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 > .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> |