AgentSkillsCN

security-audit

分析PR变更中的安全漏洞——对文件进行分类,识别OWASP相关问题,生成带有严重程度评级的漏洞分析报告

SKILL.md
--- frontmatter
name: security-audit
description: Analyze PR changes for security vulnerabilities — classify files, detect OWASP issues, produce severity-rated findings report
argument-hint: <pr-number>

Security Audit

You are the security-engineer for {{PROJECT_NAME}}. Analyze PR #$ARGUMENTS for security vulnerabilities.

Step 1: Gather PR Context

bash
# Get PR metadata
gh pr view $ARGUMENTS --json title,body,files,additions,deletions,baseRefName,headRefName

# Get full diff
gh pr diff $ARGUMENTS

If the PR number is invalid or the diff is empty, print an error and stop:

code
Error: PR #$ARGUMENTS not found or has no file changes.

Step 2: Classify Changed Files

Categorize each changed file by security risk tier:

Risk TierFile PatternsPriority
Critical**/auth/**, **/tokens/**, **/crypto/**, **/*secret*, **/*credential*, **/.env*, **/services/api/**Analyze first
High**/services/**, **/database/**, **/sync/**, **/stores/**, **/*fetch*, **/*request*, **/hooks/useAuth*Analyze second
Medium**/features/**, **/app/**, **/components/**, **/utils/**Check for input handling
Low**/__tests__/**, **/__mocks__/**, **/design-system/**, **/*.md, **/.claude/**Scan for leaked secrets only
Config**/package.json, **/*.lockb, **/*.lock, **/*.config.*, **/.github/**Check dependency and CI changes

For files not matching any pattern, default to Medium.

Step 3: Security Analysis

For each changed file, run these checks in priority order:

3a: Secret Detection (ALL files)

Scan for patterns that indicate hardcoded secrets:

  • API keys: (api[_-]?key|apikey)\s*[:=]\s*['"][^'"]+['"]
  • Tokens: (token|bearer|jwt)\s*[:=]\s*['"][^'"]+['"]
  • Passwords: (password|passwd|pwd)\s*[:=]\s*['"][^'"]+['"]
  • Connection strings: (connection[_-]?string|database[_-]?url)\s*[:=]
  • Private keys: -----BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY-----
  • Cloud credentials: (AKIA|az_|gcp_|sk-live_|sk_test_)

Exclude: test fixtures, mock data, documentation examples, __mocks__/ files.

3b: OWASP Checks

Apply the appropriate OWASP checklist based on the type of files changed:

For mobile/client files:

OWASPWhat to CheckRed Flags
M1: Credential UsageToken storage, credential handlingInsecure storage for tokens
M2: Supply ChainNew dependenciesUnvetted packages, no lockfile update
M3: Auth/AuthZAuth flow changes, permission checksMissing token validation, no expiry check
M4: Input ValidationUser input handling, URL parsingNo schema validation, eval(), innerHTML, dynamic require()
M5: CommunicationNetwork requests, URL constructionHTTP (not HTTPS), missing cert pinning discussion
M6: PrivacyData collection, analytics eventsNew PII collection without privacy policy update
M7: Binary ProtectionsBuild config, debugging flagsDebug checks missing, debug logging in production
M8: MisconfigurationApp config, permissionsOver-broad permissions, debug mode in release
M9: Data StorageLocal data persistenceSensitive data in local DB without encryption
M10: CryptographyEncryption usage, hashingWeak algorithms (MD5, SHA1 for security), hardcoded IVs/salts

For API/backend files:

OWASPWhat to CheckRed Flags
API1: Broken Object Level AuthorizationResource access checksMissing ownership validation
API2: Broken AuthenticationAuth endpoints, token handlingWeak password policy, no rate limiting
API3: Broken Object Property Level AuthorizationField-level accessMass assignment, exposing internal fields
API4: Unrestricted Resource ConsumptionRate limits, paginationNo pagination, unbounded queries
API5: Broken Function Level AuthorizationAdmin endpointsMissing role checks

3c: Dependency Analysis (Config files)

For changes to dependency files:

  • Flag new dependencies for manual review
  • Check if removed dependencies might break security features
  • Note major version bumps that might change security behavior

3d: CI/CD Security (Workflow files)

For changes to .github/workflows/:

  • Check permissions: block is minimal (not write-all)
  • Verify actions are pinned to SHA (not just major version tag)
  • Check for secret exposure in logs (echo ${{ secrets.* }})
  • Verify --no-verify is not used to skip hooks

3e: Navigation Safety (Route files)

For changes to routing/navigation:

  • Check for unvalidated deep links / URL parameters
  • Verify authentication guards on protected routes
  • Check for open redirects via URL parameters

Step 4: Rate Findings

Apply severity levels:

SeverityCriteriaAction Required
CriticalCredentials in code, SQL injection, RCEBlock merge, fix immediately
HighMissing auth checks, insecure storage, unvalidated redirectsBlock merge, fix before merge
MediumMissing input validation, verbose errors, weak rate limitingShould fix, can defer with tracking
LowMissing audit logging, hardcoded non-secret URLs, outdated patternsInformational, fix when convenient
InfoDefense-in-depth suggestions, style improvementsOptional, no action required

Step 5: Produce Findings Report

Save the report to .architecture/security/audit-findings-pr-$ARGUMENTS.md:

markdown
# Security Audit: PR #$ARGUMENTS — {PR Title}

**Date:** YYYY-MM-DD
**Auditor:** security-engineer (agent)
**PR:** #{number} — {title}
**Branch:** {head} -> {base}
**Files analyzed:** {count}

## Summary

| Severity | Count |
|----------|-------|
| Critical | N |
| High | N |
| Medium | N |
| Low | N |
| Info | N |
| **Total** | **N** |

**Verdict:** {PASS | FAIL — N Critical/High findings must be resolved}

## File Classification

| File | Risk Tier | Findings |
|------|-----------|----------|
| path/to/file.ts | Critical | 2 |
| path/to/other.ts | Medium | 0 |

## Findings

### [SEVERITY] FINDING-NNN: {Title}

**File:** `{path}:{line}`
**OWASP:** {reference, e.g., M1: Credential Usage}
**Description:** {what the issue is}
**Evidence:** {code snippet or pattern found}
**Recommendation:** {how to fix}
**Backlog:** `/bug {ready-to-file description}` (for Medium+ deferred findings)

---

## Dependency Changes

| Package | Change | Action |
|---------|--------|--------|
| {name} | Added v{x.y.z} | Manual review required |
| {name} | Upgraded {old} -> {new} | Verify changelog for security fixes |

## OWASP Coverage

| OWASP Item | Checked | Finding? |
|------------|---------|----------|
| M1-M10 / API1-API10 | Yes/No/N/A | {finding ref or "Clear"} |

## Notes

{Any additional context, limitations, or observations}

Step 6: Present Summary

code
Security Audit: PR #{number}
=============================

Files analyzed: {count} ({critical tier}: {n}, {high tier}: {n}, {medium tier}: {n})

Verdict: {PASS / FAIL}

Findings: {total}
  Critical: {n}
  High: {n}
  Medium: {n}
  Low: {n}
  Info: {n}

{If FAIL:}
Merge blocked: {n} Critical/High findings require resolution.

{Top findings:}
  1. [SEVERITY] {title} — {file}:{line}
  2. [SEVERITY] {title} — {file}:{line}

Report: .architecture/security/audit-findings-pr-{number}.md

Step 7: CI Integration Output

When invoked from CI, also output a machine-readable JSON summary to stdout:

json
{
  "pr": "$ARGUMENTS",
  "verdict": "PASS|FAIL",
  "critical": 0,
  "high": 0,
  "medium": 0,
  "low": 0,
  "info": 0,
  "findings": [
    {
      "id": "FINDING-001",
      "severity": "critical",
      "title": "...",
      "file": "...",
      "line": 0,
      "owasp": "M1"
    }
  ]
}

Edge Cases

  • PR with no security-relevant files (only .md, __tests__/, design-system): Produce a report with "No findings. All changes are in low-risk categories (docs, tests, design system)."
  • Very large PR (>50 files): Focus on Critical and High tier files first. Note in the report if Medium/Low files were not fully analyzed.
  • Mixed file types (client + backend + CI): Apply appropriate rules per file type.