secret-protection

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Secret Protection

Secret Protection

Description

描述

Secret Protection prevents credential leaks across the development lifecycle through
.env
scanning, pre-commit hooks, secret rotation policies, and runtime detection. The agent enforces a zero-tolerance policy for secrets in code, configuration, logs, or AI conversation history—catching leaks before they reach version control, CI artifacts, or production logs.
Secrets in source code are the most common cause of security breaches in modern applications. A single committed API key can compromise an entire cloud account within minutes of being pushed to a public repository. Automated bots continuously scan GitHub for exposed credentials, and the average time from commit to exploitation is under 15 minutes. This skill prevents that by intercepting secrets at every stage.
The protection operates in three rings: pre-commit (prevent secrets from entering the repository), CI/CD (catch secrets that bypass pre-commit), and runtime (detect and redact secrets in logs, error messages, and AI agent outputs). Each ring is independent—if one fails, the next catches the leak. Secret rotation is enforced on a schedule, ensuring that even an undetected exposure has a limited blast radius.
Secret Protection 通过
.env
扫描、pre-commit hook、密钥轮换策略和运行时检测,防止凭据在整个开发生命周期中泄露。该 Agent 对代码、配置、日志或 AI 对话历史中的密钥实行零容忍策略,在泄露进入版本控制、CI 构建产物或生产日志之前将其拦截。
源代码中的密钥是现代应用发生安全事件的最常见原因。一个被提交的 API key 在被推送到公开仓库后的几分钟内,就可能危及整个云账户。自动化机器人会持续扫描 GitHub 上暴露的凭据,而从提交到遭到利用的平均时间不足 15 分钟。此 skill 通过在每个阶段拦截密钥来防止这种情况。
防护分为三道防线:pre-commit(防止密钥进入仓库)、CI/CD(捕获绕过 pre-commit 的密钥)和运行时(检测并脱敏日志、错误消息及 AI Agent 输出中的密钥)。每道防线彼此独立——即使其中一道失效,下一道也会捕获泄露。密钥轮换按计划执行,确保任何未检测到的暴露都有有限的影响范围。

Use When

适用场景

  • Setting up a new repository with proper secret management
  • Adding pre-commit hooks to prevent credential leaks
  • Auditing existing repositories for committed secrets
  • Configuring CI/CD pipelines with secret scanning gates
  • Implementing secret rotation policies
  • Preventing agents from exposing secrets in their outputs
  • 为新仓库设置正确的密钥管理
  • 添加 pre-commit hook,防止凭据泄露
  • 审计现有仓库中已提交的密钥
  • 配置带密钥扫描门禁的 CI/CD pipeline
  • 实施密钥轮换策略
  • 防止 Agent 在输出中暴露密钥

How It Works

工作原理

mermaid
graph TD
    A[Developer / Agent Writes Code] --> B[Ring 1: Pre-Commit Hook]
    B --> C{Secrets Detected?}
    C -->|Yes| D[Block Commit + Alert]
    C -->|No| E[Allow Commit]
    E --> F[Ring 2: CI/CD Scan]
    F --> G{Secrets in Diff?}
    G -->|Yes| H[Fail Pipeline + Alert]
    G -->|No| I[Continue Pipeline]
    I --> J[Ring 3: Runtime Detection]
    J --> K[Redact Secrets in Logs]
    J --> L[Redact Secrets in Agent Output]
    K --> M[Production Safe]
    L --> M
    N[Rotation Schedule] --> O[Rotate Keys Monthly]
    O --> P[Update Secrets Manager]
    P --> Q[Deploy Updated References]
Three independent rings ensure that a secret leak must bypass all three layers to cause damage. The rotation schedule limits the blast radius of any undetected exposure.
mermaid
graph TD
    A[Developer / Agent Writes Code] --> B[Ring 1: Pre-Commit Hook]
    B --> C{Secrets Detected?}
    C -->|Yes| D[Block Commit + Alert]
    C -->|No| E[Allow Commit]
    E --> F[Ring 2: CI/CD Scan]
    F --> G{Secrets in Diff?}
    G -->|Yes| H[Fail Pipeline + Alert]
    G -->|No| I[Continue Pipeline]
    I --> J[Ring 3: Runtime Detection]
    J --> K[Redact Secrets in Logs]
    J --> L[Redact Secrets in Agent Output]
    K --> M[Production Safe]
    L --> M
    N[Rotation Schedule] --> O[Rotate Keys Monthly]
    O --> P[Update Secrets Manager]
    P --> Q[Deploy Updated References]
三道独立防线共同确保,密钥泄露必须绕过全部三层才能造成损害。轮换计划可限制任何未检测到的暴露所造成的影响范围。

Implementation

实现

yaml
undefined
yaml
undefined

.pre-commit-config.yaml

.pre-commit-config.yaml

repos:
  • repo: https://github.com/gitleaks/gitleaks rev: v8.18.0 hooks:
    • id: gitleaks
  • repo: local hooks:
    • id: dotenv-check name: Check .env files not committed entry: bash -c 'git diff --cached --name-only | grep -E ".env($|.)" && exit 1 || exit 0' language: system pass_filenames: false

```python
import re
from dataclasses import dataclass

@dataclass
class SecretPattern:
    name: str
    pattern: str
    severity: str

SECRET_PATTERNS = [
    SecretPattern("AWS Access Key", r"AKIA[0-9A-Z]{16}", "CRITICAL"),
    SecretPattern("AWS Secret Key", r"(?i)aws_secret_access_key\s*=\s*[A-Za-z0-9/+=]{40}", "CRITICAL"),
    SecretPattern("GitHub Token", r"gh[ps]_[A-Za-z0-9_]{36,}", "CRITICAL"),
    SecretPattern("Generic API Key", r"(?i)(api[_-]?key|apikey)\s*[:=]\s*['\"][A-Za-z0-9]{20,}['\"]", "HIGH"),
    SecretPattern("Private Key", r"-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----", "CRITICAL"),
    SecretPattern("Cloudflare Token", r"(?i)cloudflare.*(?:token|key)\s*[:=]\s*['\"][A-Za-z0-9_-]{40,}['\"]", "CRITICAL"),
    SecretPattern("JWT Token", r"eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}", "HIGH"),
    SecretPattern("Database URL", r"(?:postgres|mysql|mongodb)://\w+:[^@\s]+@", "CRITICAL"),
]

class SecretScanner:
    def __init__(self, patterns: list[SecretPattern] = SECRET_PATTERNS):
        self.patterns = [(p, re.compile(p.pattern)) for p in patterns]

    def scan_text(self, text: str, source: str = "unknown") -> list[dict]:
        findings = []
        for pattern, compiled in self.patterns:
            for match in compiled.finditer(text):
                findings.append({
                    "type": pattern.name,
                    "severity": pattern.severity,
                    "source": source,
                    "position": match.start(),
                    "preview": self._redact(match.group(), keep_chars=4),
                })
        return findings

    def redact_output(self, text: str) -> str:
        """Redact any detected secrets from agent output."""
        for pattern, compiled in self.patterns:
            text = compiled.sub(f"[REDACTED:{pattern.name}]", text)
        return text

    @staticmethod
    def _redact(secret: str, keep_chars: int = 4) -> str:
        if len(secret) <= keep_chars * 2:
            return "*" * len(secret)
        return secret[:keep_chars] + "*" * (len(secret) - keep_chars * 2) + secret[-keep_chars:]

class SecretRotationPolicy:
    ROTATION_SCHEDULES = {
        "CRITICAL": 30,
        "HIGH": 90,
        "MEDIUM": 180,
    }

    def check_rotation_due(self, secret_metadata: dict) -> bool:
        from datetime import datetime, timedelta
        last_rotated = datetime.fromisoformat(secret_metadata["last_rotated"])
        max_age = self.ROTATION_SCHEDULES[secret_metadata["severity"]]
        return datetime.now() - last_rotated > timedelta(days=max_age)
repos:
  • repo: https://github.com/gitleaks/gitleaks rev: v8.18.0 hooks:
    • id: gitleaks
  • repo: local hooks:
    • id: dotenv-check name: Check .env files not committed entry: bash -c 'git diff --cached --name-only | grep -E ".env($|.)" && exit 1 || exit 0' language: system pass_filenames: false

```python
import re
from dataclasses import dataclass

@dataclass
class SecretPattern:
    name: str
    pattern: str
    severity: str

SECRET_PATTERNS = [
    SecretPattern("AWS Access Key", r"AKIA[0-9A-Z]{16}", "CRITICAL"),
    SecretPattern("AWS Secret Key", r"(?i)aws_secret_access_key\s*=\s*[A-Za-z0-9/+=]{40}", "CRITICAL"),
    SecretPattern("GitHub Token", r"gh[ps]_[A-Za-z0-9_]{36,}", "CRITICAL"),
    SecretPattern("Generic API Key", r"(?i)(api[_-]?key|apikey)\s*[:=]\s*['\"][A-Za-z0-9]{20,}['\"]", "HIGH"),
    SecretPattern("Private Key", r"-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----", "CRITICAL"),
    SecretPattern("Cloudflare Token", r"(?i)cloudflare.*(?:token|key)\s*[:=]\s*['\"][A-Za-z0-9_-]{40,}['\"]", "CRITICAL"),
    SecretPattern("JWT Token", r"eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}", "HIGH"),
    SecretPattern("Database URL", r"(?:postgres|mysql|mongodb)://\w+:[^@\s]+@", "CRITICAL"),
]

class SecretScanner:
    def __init__(self, patterns: list[SecretPattern] = SECRET_PATTERNS):
        self.patterns = [(p, re.compile(p.pattern)) for p in patterns]

    def scan_text(self, text: str, source: str = "unknown") -> list[dict]:
        findings = []
        for pattern, compiled in self.patterns:
            for match in compiled.finditer(text):
                findings.append({
                    "type": pattern.name,
                    "severity": pattern.severity,
                    "source": source,
                    "position": match.start(),
                    "preview": self._redact(match.group(), keep_chars=4),
                })
        return findings

    def redact_output(self, text: str) -> str:
        """Redact any detected secrets from agent output."""
        for pattern, compiled in self.patterns:
            text = compiled.sub(f"[REDACTED:{pattern.name}]", text)
        return text

    @staticmethod
    def _redact(secret: str, keep_chars: int = 4) -> str:
        if len(secret) <= keep_chars * 2:
            return "*" * len(secret)
        return secret[:keep_chars] + "*" * (len(secret) - keep_chars * 2) + secret[-keep_chars:]

class SecretRotationPolicy:
    ROTATION_SCHEDULES = {
        "CRITICAL": 30,
        "HIGH": 90,
        "MEDIUM": 180,
    }

    def check_rotation_due(self, secret_metadata: dict) -> bool:
        from datetime import datetime, timedelta
        last_rotated = datetime.fromisoformat(secret_metadata["last_rotated"])
        max_age = self.ROTATION_SCHEDULES[secret_metadata["severity"]]
        return datetime.now() - last_rotated > timedelta(days=max_age)

Best Practices

最佳实践

  • Install pre-commit hooks as the first action in any new repository
  • Never suppress secret findings—fix them or demonstrate they are false positives
  • Store secrets in a dedicated secrets manager (Wrangler secrets, Vault, AWS Secrets Manager)
  • Rotate CRITICAL secrets (cloud credentials, API keys) every 30 days
  • Redact secrets from all log output, error messages, and agent conversation history
  • Scan git history (
    gitleaks detect
    ) periodically—secrets committed then deleted remain in history
  • 在任何新仓库中,将安装 pre-commit hook 作为第一步
  • 绝不忽略密钥扫描结果——应修复问题,或证明结果是误报
  • 将密钥存储在专用 secrets manager 中(Wrangler secrets、Vault、AWS Secrets Manager)
  • 每 30 天轮换 CRITICAL 密钥(云凭据、API key)
  • 从所有日志输出、错误消息和 Agent 对话历史中脱敏密钥
  • 定期扫描 git 历史(
    gitleaks detect
    )——提交后删除的密钥仍会留在历史记录中

Platform Compatibility

平台兼容性

PlatformSupportNotes
CursorFullPre-commit + scanning
VS CodeFullgitleaks extension
WindsurfFullSecret detection
Claude CodeFullPre-commit integration
ClineFullSecurity scanning
aiderFullPre-commit hook support
平台支持情况备注
Cursor完全支持Pre-commit + 扫描
VS Code完全支持gitleaks 扩展
Windsurf完全支持密钥检测
Claude Code完全支持Pre-commit 集成
Cline完全支持安全扫描
aider完全支持Pre-commit hook 支持

Related Skills

相关 Skill

  • Agent Security Scanning - Broader security analysis that includes secret detection within its three-layer scanning pipeline
  • Sandbox Hardening - Execution isolation that restricts agent access to secrets through filesystem scoping and permission boundaries
  • CodeQL & Semgrep - Static analysis rules that detect hardcoded credentials and insecure secret handling patterns in code
  • Agent Security Scanning - 更全面的安全分析,其三层扫描 pipeline 包含密钥检测
  • Sandbox Hardening - 通过文件系统范围界定和权限边界限制 Agent 访问密钥的执行隔离机制
  • CodeQL & Semgrep - 用于检测代码中硬编码凭据和不安全密钥处理模式的静态分析规则

Keywords

关键词

secret-protection
credential-leak
pre-commit
gitleaks
secret-rotation
redaction
.env-scanning
api-key-security

© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License
secret-protection
credential-leak
pre-commit
gitleaks
secret-rotation
redaction
.env-scanning
api-key-security

© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License