env-secrets-manager
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseEnv & Secrets Manager
环境变量与密钥管理器
Tier: POWERFUL
Category: Engineering
Domain: Security / DevOps / Configuration Management
级别: POWERFUL
分类: 工程类
领域: 安全 / DevOps / 配置管理
Overview
概述
Manage environment-variable hygiene and secrets safety across local development and production workflows. This skill focuses on practical auditing, drift awareness, and rotation readiness.
在本地开发和生产工作流中管理环境变量合规性与密钥安全性。本技能聚焦于实用审计、变更感知和轮换就绪能力。
Core Capabilities
核心功能
- and
.envlifecycle guidance.env.example - Secret leak detection for repository working trees
- Severity-based findings for likely credentials
- Operational pointers for rotation and containment
- Integration-ready outputs for CI checks
- 和
.env生命周期指导.env.example - 代码库工作区的密钥泄露检测
- 基于风险等级的疑似凭证识别
- 密钥轮换与泄露遏制的操作指引
- 适用于CI检查的可集成输出
When to Use
适用场景
- Before pushing commits that touched env/config files
- During security audits and incident triage
- When onboarding contributors who need safe env conventions
- When validating that no obvious secrets are hardcoded
- 推送涉及环境/配置文件的代码提交前
- 安全审计和事件分类期间
- 为需要安全环境规范的新贡献者提供入职指导时
- 验证是否存在硬编码的明显密钥时
Quick Start
快速开始
bash
undefinedbash
undefinedScan a repository for likely secret leaks
扫描代码库以检测疑似密钥泄露
python3 scripts/env_auditor.py /path/to/repo
python3 scripts/env_auditor.py /path/to/repo
JSON output for CI pipelines
生成适用于CI流水线的JSON格式输出
python3 scripts/env_auditor.py /path/to/repo --json
---python3 scripts/env_auditor.py /path/to/repo --json
---Recommended Workflow
推荐工作流
- Run on the repository root.
scripts/env_auditor.py - Prioritize and
criticalfindings first.high - Rotate real credentials and remove exposed values.
- Update and
.env.exampleas needed..gitignore - Add or tighten pre-commit/CI secret scanning gates.
- 在代码库根目录运行 。
scripts/env_auditor.py - 优先处理 (严重)和
critical(高风险)级别的检测结果。high - 轮换真实凭证并移除暴露的敏感值。
- 根据需要更新 和
.env.example。.gitignore - 添加或强化提交前/CI阶段的密钥扫描机制。
Reference Docs
参考文档
references/validation-detection-rotation.mdreferences/secret-patterns.md
references/validation-detection-rotation.mdreferences/secret-patterns.md
Common Pitfalls
常见误区
- Committing real values in
.env.example - Rotating one system but missing downstream consumers
- Logging secrets during debugging or incident response
- Treating suspected leaks as low urgency without validation
- 在 中提交真实敏感值
.env.example - 轮换单个系统但遗漏下游依赖消费者
- 调试或事件响应期间记录密钥
- 未经验证就将疑似泄露视为低优先级问题
Best Practices
最佳实践
- Use a secret manager as the production source of truth.
- Keep dev env files local and gitignored.
- Enforce detection in CI before merge.
- Re-test application paths immediately after credential rotation.
- 将密钥管理器作为生产环境的可信数据源。
- 开发环境的配置文件仅保留在本地并加入git忽略列表。
- 在CI阶段强制启用密钥检测,通过后才可合并代码。
- 凭证轮换后立即重新测试应用路径。
Cloud Secret Store Integration
云密钥存储集成
Production applications should never read secrets from files or environment variables baked into container images. Use a dedicated secret store instead.
.env生产环境应用绝不应从 文件或容器镜像中内置的环境变量读取密钥,应使用专用的密钥存储服务。
.envProvider Comparison
服务商对比
| Provider | Best For | Key Feature |
|---|---|---|
| HashiCorp Vault | Multi-cloud / hybrid | Dynamic secrets, policy engine, pluggable backends |
| AWS Secrets Manager | AWS-native workloads | Native Lambda/ECS/EKS integration, automatic RDS rotation |
| Azure Key Vault | Azure-native workloads | Managed HSM, Azure AD RBAC, certificate management |
| GCP Secret Manager | GCP-native workloads | IAM-based access, automatic replication, versioning |
| 服务商 | 适用场景 | 核心特性 |
|---|---|---|
| HashiCorp Vault | 多云/混合云环境 | 动态密钥、策略引擎、可插拔后端 |
| AWS Secrets Manager | AWS原生工作负载 | 原生Lambda/ECS/EKS集成、自动RDS轮换 |
| Azure Key Vault | Azure原生工作负载 | 托管HSM、Azure AD RBAC、证书管理 |
| GCP Secret Manager | GCP原生工作负载 | 基于IAM的访问控制、自动复制、版本管理 |
Selection Guidance
选型指南
- Single cloud provider — use the cloud-native secret manager. It integrates tightly with IAM, reduces operational overhead, and costs less than self-hosting.
- Multi-cloud or hybrid — use HashiCorp Vault. It provides a uniform API across environments and supports dynamic secret generation (database credentials, cloud IAM keys) that expire automatically.
- Kubernetes-heavy — combine External Secrets Operator with any backend above to sync secrets into K8s objects without hardcoding.
Secret
- 单一云服务商 — 使用云原生密钥管理器。它与IAM深度集成,降低运维成本,比自托管方案更经济。
- 多云或混合云 — 使用HashiCorp Vault。它在不同环境中提供统一API,支持自动过期的动态密钥生成(数据库凭证、云IAM密钥)。
- 以Kubernetes为主 — 将External Secrets Operator与上述任意后端结合,将密钥同步到K8s 对象中,避免硬编码。
Secret
Application Access Patterns
应用访问模式
- SDK/API pull — application fetches secret at startup or on-demand via provider SDK.
- Sidecar injection — a sidecar container (e.g., Vault Agent) writes secrets to a shared volume or injects them as environment variables.
- Init container — a Kubernetes init container fetches secrets before the main container starts.
- CSI driver — secrets mount as a filesystem volume via the Secrets Store CSI Driver.
Cross-reference: Seefor production vault infrastructure patterns, HA deployment, and disaster recovery procedures.engineering/secrets-vault-manager
- SDK/API拉取 — 应用在启动时或按需通过服务商SDK获取密钥。
- Sidecar注入 — 边车容器(如Vault Agent)将密钥写入共享卷或注入为环境变量。
- Init容器 — Kubernetes初始化容器在主容器启动前获取密钥。
- CSI驱动 — 通过Secrets Store CSI Driver将密钥挂载为文件系统卷。
交叉参考: 查看获取生产环境Vault基础设施模式、高可用部署和灾难恢复流程。engineering/secrets-vault-manager
Secret Rotation Workflow
密钥轮换工作流
Stale secrets are a liability. Rotation ensures that even if a credential leaks, its useful lifetime is bounded.
过期密钥是安全隐患。轮换机制可确保即使凭证泄露,其有效生命周期也会被限制。
Phase 1: Detection
阶段1:检测
- Track secret creation and expiry dates in your secret store metadata.
- Set alerts at 30, 14, and 7 days before expiry.
- Use to flag secrets with no recorded rotation date.
scripts/env_auditor.py
- 在密钥存储元数据中跟踪密钥创建和过期日期。
- 在过期前30、14和7天设置告警。
- 使用 标记无记录轮换日期的密钥。
scripts/env_auditor.py
Phase 2: Rotation
阶段2:轮换
- Generate a new credential (API key, database password, certificate).
- Deploy the new credential to all consumers (apps, services, pipelines) in parallel.
- Verify each consumer can authenticate using the new credential.
- Revoke the old credential only after all consumers are confirmed healthy.
- Update metadata with the new rotation timestamp and next rotation date.
- 生成新凭证(API密钥、数据库密码、证书)。
- 部署新凭证至所有消费者(应用、服务、流水线)。
- 验证每个消费者均可使用新凭证完成认证。
- 仅在确认所有消费者健康后撤销旧凭证。
- 更新元数据中的新轮换时间戳和下一次轮换日期。
Phase 3: Automation
阶段3:自动化
- AWS Secrets Manager — use built-in Lambda-based rotation for RDS, Redshift, and DocumentDB.
- HashiCorp Vault — configure dynamic secrets with TTLs; credentials are generated on-demand and auto-expire.
- Azure Key Vault — use Event Grid notifications to trigger rotation functions.
- GCP Secret Manager — use Pub/Sub notifications tied to Cloud Functions for rotation logic.
- AWS Secrets Manager — 使用内置的基于Lambda的轮换功能处理RDS、Redshift和DocumentDB。
- HashiCorp Vault — 配置带TTL的动态密钥;凭证按需生成并自动过期。
- Azure Key Vault — 使用Event Grid通知触发轮换函数。
- GCP Secret Manager — 使用与Cloud Functions绑定的Pub/Sub通知实现轮换逻辑。
Emergency Rotation Checklist
紧急轮换清单
When a secret is confirmed leaked:
- Immediately revoke the compromised credential at the provider level.
- Generate and deploy a replacement credential to all consumers.
- Audit access logs for unauthorized usage during the exposure window.
- Scan git history, CI logs, and artifact registries for the leaked value.
- File an incident report documenting scope, timeline, and remediation steps.
- Review and tighten detection controls to prevent recurrence.
当确认密钥泄露时:
- 立即在服务商层面撤销泄露的凭证。
- 生成并部署替代凭证至所有消费者。
- 审计暴露窗口期内的未授权访问日志。
- 扫描git历史、CI日志和制品仓库以查找泄露值。
- 提交事件报告,记录影响范围、时间线和修复步骤。
- 审查并强化检测控制以防止再次发生。
CI/CD Secret Injection
CI/CD密钥注入
Secrets in CI/CD pipelines require careful handling to avoid exposure in logs, artifacts, or pull request contexts.
CI/CD流水线中的密钥需谨慎处理,避免在日志、制品或拉取请求上下文暴露。
GitHub Actions
GitHub Actions
- Use repository secrets or environment secrets via .
${{ secrets.SECRET_NAME }} - Prefer OIDC federation (with
aws-actions/configure-aws-credentials) over long-lived access keys.role-to-assume - Environment secrets with required reviewers add approval gates for production deployments.
- GitHub automatically masks secrets in logs, but avoid or
echoon secret values.toJSON()
- 通过 使用仓库密钥或环境密钥。
${{ secrets.SECRET_NAME }} - 优先使用OIDC联邦(搭配
aws-actions/configure-aws-credentials)而非长期访问密钥。role-to-assume - 带有必填审核人的环境密钥可为生产部署添加审批环节。
- GitHub会自动在日志中屏蔽密钥,但避免使用 或
echo输出密钥值。toJSON()
GitLab CI
GitLab CI
- Store secrets as CI/CD variables with the and
maskedflags enabled.protected - Use HashiCorp Vault integration () for dynamic secret injection without storing values in GitLab.
secrets:vault - Scope variables to specific environments (,
production) to enforce least privilege.staging
- 将密钥存储为启用 (屏蔽)和
masked(保护)标记的CI/CD变量。protected - 使用HashiCorp Vault集成()实现动态密钥注入,无需在GitLab中存储值。
secrets:vault - 将变量限定到特定环境(、
production)以遵循最小权限原则。staging
Universal Patterns
通用模式
- Never echo or print secret values in pipeline output, even for debugging.
- Use short-lived tokens (OIDC, STS AssumeRole) instead of static credentials wherever possible.
- Restrict PR access — do not expose secrets to pipelines triggered by forks or untrusted branches.
- Rotate CI secrets on the same schedule as application secrets; pipeline credentials are attack vectors too.
- Audit pipeline logs periodically for accidental secret exposure that masking may have missed.
- 切勿在流水线输出中回显或打印密钥值,即使是调试场景。
- 尽可能使用短期令牌(OIDC、STS AssumeRole)而非静态凭证。
- 限制PR访问 — 不要向由分叉或不可信分支触发的流水线暴露密钥。
- 按应用密钥的相同计划轮换CI密钥;流水线凭证也是攻击向量。
- 定期审计流水线日志,检查屏蔽机制可能遗漏的意外密钥暴露。
Pre-Commit Secret Detection
提交前密钥检测
Catching secrets before they reach version control is the most cost-effective defense. Two leading tools cover this space.
在密钥进入版本控制前拦截是最具成本效益的防御手段。以下是两款主流工具:
gitleaks
gitleaks
toml
undefinedtoml
undefined.gitleaks.toml — minimal configuration
.gitleaks.toml — 最小配置
[extend]
useDefault = true
[[rules]]
id = "custom-internal-token"
description = "Internal service token pattern"
regex = '''INTERNAL_TOKEN_[A-Za-z0-9]{32}'''
secretGroup = 0
- Install: `brew install gitleaks` or download from GitHub releases.
- Pre-commit hook: `gitleaks git --pre-commit --staged`
- Baseline scanning: `gitleaks detect --source . --report-path gitleaks-report.json`
- Manage false positives in `.gitleaksignore` (one fingerprint per line).[extend]
useDefault = true
[[rules]]
id = "custom-internal-token"
description = "内部服务令牌规则"
regex = '''INTERNAL_TOKEN_[A-Za-z0-9]{32}'''
secretGroup = 0
- 安装:`brew install gitleaks` 或从GitHub Releases下载。
- 提交前钩子:`gitleaks git --pre-commit --staged`
- 基线扫描:`gitleaks detect --source . --report-path gitleaks-report.json`
- 在 `.gitleaksignore` 中管理误报(每行一个指纹)。detect-secrets
detect-secrets
bash
undefinedbash
undefinedGenerate baseline
生成基线
detect-secrets scan --all-files > .secrets.baseline
detect-secrets scan --all-files > .secrets.baseline
Pre-commit hook (via pre-commit framework)
提交前钩子(通过pre-commit框架)
.pre-commit-config.yaml
.pre-commit-config.yaml
repos:
- repo: https://github.com/Yelp/detect-secrets
rev: v1.5.0
hooks:
- id: detect-secrets args: ['--baseline', '.secrets.baseline']
- Supports **custom plugins** for organization-specific patterns.
- Audit workflow: `detect-secrets audit .secrets.baseline` interactively marks true/false positives.repos:
- repo: https://github.com/Yelp/detect-secrets
rev: v1.5.0
hooks:
- id: detect-secrets args: ['--baseline', '.secrets.baseline']
- 支持**自定义插件**以适配组织特定规则。
- 审计工作流:`detect-secrets audit .secrets.baseline` 可交互式标记真/假阳性结果。False Positive Management
误报管理
- Maintain or
.gitleaksignorein version control so the whole team shares exclusions..secrets.baseline - Review false positive lists during security audits — patterns may mask real leaks over time.
- Prefer tightening regex patterns over broadly ignoring files.
- 在版本控制中维护 或
.gitleaksignore,确保团队共享排除规则。.secrets.baseline - 安全审计期间复查误报列表 — 规则可能随时间掩盖真实泄露。
- 优先收紧正则规则而非宽泛忽略文件。
Audit Logging
审计日志
Knowing who accessed which secret and when is critical for incident investigation and compliance.
了解谁在何时访问了哪些密钥,对事件调查和合规性至关重要。
Cloud-Native Audit Trails
云原生审计追踪
| Provider | Service | What It Captures |
|---|---|---|
| AWS | CloudTrail | Every |
| Azure | Activity Log + Diagnostic Logs | Key Vault access events, including caller identity and IP |
| GCP | Cloud Audit Logs | Data access logs for Secret Manager with principal and timestamp |
| Vault | Audit Backend | Full request/response logging (file, syslog, or socket backend) |
| 服务商 | 服务 | 捕获内容 |
|---|---|---|
| AWS | CloudTrail | 所有 |
| Azure | 活动日志 + 诊断日志 | Key Vault访问事件,包括调用者身份和IP |
| GCP | Cloud Audit Logs | Secret Manager的数据访问日志,包含主体和时间戳 |
| Vault | Audit Backend | 完整请求/响应日志(支持文件、syslog或套接字后端) |
Alerting Strategy
告警策略
- Alert on access from unknown IP ranges or service accounts outside the expected set.
- Alert on bulk secret reads (more than N secrets accessed within a time window).
- Alert on access outside deployment windows when no CI/CD pipeline is running.
- Feed audit logs into your SIEM (Splunk, Datadog, Elastic) for correlation with other security events.
- Review audit logs quarterly as part of access recertification.
- 对未知IP范围或预期外服务账号的访问触发告警。
- 对批量密钥读取(特定时间窗口内访问超过N个密钥)触发告警。
- 对非部署窗口的访问(无CI/CD流水线运行时)触发告警。
- 将审计日志导入SIEM(Splunk、Datadog、Elastic)以关联其他安全事件。
- 每季度复查审计日志,作为访问重新认证的一部分。
Cross-References
交叉引用
This skill covers env hygiene and secret detection. For deeper coverage of related domains, see:
| Skill | Path | Relationship |
|---|---|---|
| Secrets Vault Manager | | Production vault infrastructure, HA deployment, DR |
| Senior SecOps | | Security operations perspective, incident response |
| CI/CD Pipeline Builder | | Pipeline architecture, secret injection patterns |
| Infrastructure as Code | | Terraform/Pulumi secret backend configuration |
| Container Orchestration | | Kubernetes secret mounting, sealed secrets |
本技能涵盖环境合规和密钥检测。如需相关领域的深入内容,请查看:
| 技能 | 路径 | 关联关系 |
|---|---|---|
| Secrets Vault Manager | | 生产环境Vault基础设施、高可用部署、灾难恢复 |
| Senior SecOps | | 安全运维视角、事件响应 |
| CI/CD Pipeline Builder | | 流水线架构、密钥注入模式 |
| Infrastructure as Code | | Terraform/Pulumi密钥后端配置 |
| Container Orchestration | | Kubernetes密钥挂载、密封密钥 |