env-secrets-manager

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Env & 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

核心功能

  • .env
    and
    .env.example
    lifecycle guidance
  • 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
undefined
bash
undefined

Scan 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

推荐工作流

  1. Run
    scripts/env_auditor.py
    on the repository root.
  2. Prioritize
    critical
    and
    high
    findings first.
  3. Rotate real credentials and remove exposed values.
  4. Update
    .env.example
    and
    .gitignore
    as needed.
  5. Add or tighten pre-commit/CI secret scanning gates.

  1. 在代码库根目录运行
    scripts/env_auditor.py
  2. 优先处理
    critical
    (严重)和
    high
    (高风险)级别的检测结果。
  3. 轮换真实凭证并移除暴露的敏感值。
  4. 根据需要更新
    .env.example
    .gitignore
  5. 添加或强化提交前/CI阶段的密钥扫描机制。

Reference Docs

参考文档

  • references/validation-detection-rotation.md
  • references/secret-patterns.md

  • references/validation-detection-rotation.md
  • references/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

最佳实践

  1. Use a secret manager as the production source of truth.
  2. Keep dev env files local and gitignored.
  3. Enforce detection in CI before merge.
  4. Re-test application paths immediately after credential rotation.

  1. 将密钥管理器作为生产环境的可信数据源。
  2. 开发环境的配置文件仅保留在本地并加入git忽略列表。
  3. 在CI阶段强制启用密钥检测,通过后才可合并代码。
  4. 凭证轮换后立即重新测试应用路径。

Cloud Secret Store Integration

云密钥存储集成

Production applications should never read secrets from
.env
files or environment variables baked into container images. Use a dedicated secret store instead.
生产环境应用绝不应从
.env
文件或容器镜像中内置的环境变量读取密钥,应使用专用的密钥存储服务。

Provider Comparison

服务商对比

ProviderBest ForKey Feature
HashiCorp VaultMulti-cloud / hybridDynamic secrets, policy engine, pluggable backends
AWS Secrets ManagerAWS-native workloadsNative Lambda/ECS/EKS integration, automatic RDS rotation
Azure Key VaultAzure-native workloadsManaged HSM, Azure AD RBAC, certificate management
GCP Secret ManagerGCP-native workloadsIAM-based access, automatic replication, versioning
服务商适用场景核心特性
HashiCorp Vault多云/混合云环境动态密钥、策略引擎、可插拔后端
AWS Secrets ManagerAWS原生工作负载原生Lambda/ECS/EKS集成、自动RDS轮换
Azure Key VaultAzure原生工作负载托管HSM、Azure AD RBAC、证书管理
GCP Secret ManagerGCP原生工作负载基于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
    Secret
    objects without hardcoding.
  • 单一云服务商 — 使用云原生密钥管理器。它与IAM深度集成,降低运维成本,比自托管方案更经济。
  • 多云或混合云 — 使用HashiCorp Vault。它在不同环境中提供统一API,支持自动过期的动态密钥生成(数据库凭证、云IAM密钥)。
  • 以Kubernetes为主 — 将External Secrets Operator与上述任意后端结合,将密钥同步到K8s
    Secret
    对象中,避免硬编码。

Application Access Patterns

应用访问模式

  1. SDK/API pull — application fetches secret at startup or on-demand via provider SDK.
  2. Sidecar injection — a sidecar container (e.g., Vault Agent) writes secrets to a shared volume or injects them as environment variables.
  3. Init container — a Kubernetes init container fetches secrets before the main container starts.
  4. CSI driver — secrets mount as a filesystem volume via the Secrets Store CSI Driver.
Cross-reference: See
engineering/secrets-vault-manager
for production vault infrastructure patterns, HA deployment, and disaster recovery procedures.

  1. SDK/API拉取 — 应用在启动时或按需通过服务商SDK获取密钥。
  2. Sidecar注入 — 边车容器(如Vault Agent)将密钥写入共享卷或注入为环境变量。
  3. Init容器 — Kubernetes初始化容器在主容器启动前获取密钥。
  4. CSI驱动 — 通过Secrets Store CSI Driver将密钥挂载为文件系统卷。
交叉参考: 查看
engineering/secrets-vault-manager
获取生产环境Vault基础设施模式、高可用部署和灾难恢复流程。

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
    scripts/env_auditor.py
    to flag secrets with no recorded rotation date.
  • 在密钥存储元数据中跟踪密钥创建和过期日期。
  • 在过期前30、14和7天设置告警。
  • 使用
    scripts/env_auditor.py
    标记无记录轮换日期的密钥。

Phase 2: Rotation

阶段2:轮换

  1. Generate a new credential (API key, database password, certificate).
  2. Deploy the new credential to all consumers (apps, services, pipelines) in parallel.
  3. Verify each consumer can authenticate using the new credential.
  4. Revoke the old credential only after all consumers are confirmed healthy.
  5. Update metadata with the new rotation timestamp and next rotation date.
  1. 生成新凭证(API密钥、数据库密码、证书)。
  2. 部署新凭证至所有消费者(应用、服务、流水线)。
  3. 验证每个消费者均可使用新凭证完成认证。
  4. 仅在确认所有消费者健康后撤销旧凭证。
  5. 更新元数据中的新轮换时间戳和下一次轮换日期。

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:
  1. Immediately revoke the compromised credential at the provider level.
  2. Generate and deploy a replacement credential to all consumers.
  3. Audit access logs for unauthorized usage during the exposure window.
  4. Scan git history, CI logs, and artifact registries for the leaked value.
  5. File an incident report documenting scope, timeline, and remediation steps.
  6. Review and tighten detection controls to prevent recurrence.

当确认密钥泄露时:
  1. 立即在服务商层面撤销泄露的凭证。
  2. 生成并部署替代凭证至所有消费者。
  3. 审计暴露窗口期内的未授权访问日志。
  4. 扫描git历史、CI日志和制品仓库以查找泄露值。
  5. 提交事件报告,记录影响范围、时间线和修复步骤。
  6. 审查并强化检测控制以防止再次发生。

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 (
    aws-actions/configure-aws-credentials
    with
    role-to-assume
    ) over long-lived access keys.
  • Environment secrets with required reviewers add approval gates for production deployments.
  • GitHub automatically masks secrets in logs, but avoid
    echo
    or
    toJSON()
    on secret values.
  • 通过
    ${{ 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
    masked
    and
    protected
    flags enabled.
  • Use HashiCorp Vault integration (
    secrets:vault
    ) for dynamic secret injection without storing values in GitLab.
  • Scope variables to specific environments (
    production
    ,
    staging
    ) to enforce least privilege.
  • 将密钥存储为启用
    masked
    (屏蔽)和
    protected
    (保护)标记的CI/CD变量
  • 使用HashiCorp Vault集成
    secrets:vault
    )实现动态密钥注入,无需在GitLab中存储值。
  • 将变量限定到特定环境(
    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
undefined
toml
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
undefined
bash
undefined

Generate 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:

- Supports **custom plugins** for organization-specific patterns.
- Audit workflow: `detect-secrets audit .secrets.baseline` interactively marks true/false positives.
repos:

- 支持**自定义插件**以适配组织特定规则。
- 审计工作流:`detect-secrets audit .secrets.baseline` 可交互式标记真/假阳性结果。

False Positive Management

误报管理

  • Maintain
    .gitleaksignore
    or
    .secrets.baseline
    in version control so the whole team shares exclusions.
  • 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

云原生审计追踪

ProviderServiceWhat It Captures
AWSCloudTrailEvery
GetSecretValue
,
DescribeSecret
,
RotateSecret
API call
AzureActivity Log + Diagnostic LogsKey Vault access events, including caller identity and IP
GCPCloud Audit LogsData access logs for Secret Manager with principal and timestamp
VaultAudit BackendFull request/response logging (file, syslog, or socket backend)
服务商服务捕获内容
AWSCloudTrail所有
GetSecretValue
DescribeSecret
RotateSecret
API调用
Azure活动日志 + 诊断日志Key Vault访问事件,包括调用者身份和IP
GCPCloud Audit LogsSecret Manager的数据访问日志,包含主体和时间戳
VaultAudit 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:
SkillPathRelationship
Secrets Vault Manager
engineering/secrets-vault-manager
Production vault infrastructure, HA deployment, DR
Senior SecOps
engineering/senior-secops
Security operations perspective, incident response
CI/CD Pipeline Builder
engineering/ci-cd-pipeline-builder
Pipeline architecture, secret injection patterns
Infrastructure as Code
engineering/infrastructure-as-code
Terraform/Pulumi secret backend configuration
Container Orchestration
engineering/container-orchestration
Kubernetes secret mounting, sealed secrets
本技能涵盖环境合规和密钥检测。如需相关领域的深入内容,请查看:
技能路径关联关系
Secrets Vault Manager
engineering/secrets-vault-manager
生产环境Vault基础设施、高可用部署、灾难恢复
Senior SecOps
engineering/senior-secops
安全运维视角、事件响应
CI/CD Pipeline Builder
engineering/ci-cd-pipeline-builder
流水线架构、密钥注入模式
Infrastructure as Code
engineering/infrastructure-as-code
Terraform/Pulumi密钥后端配置
Container Orchestration
engineering/container-orchestration
Kubernetes密钥挂载、密封密钥