Skip to content

Latest commit

Β 

History

History
131 lines (93 loc) Β· 3.06 KB

File metadata and controls

131 lines (93 loc) Β· 3.06 KB

πŸ” AI Secure Code Review Pre-commit Hook

Runs an AI-based secure code review on staged changes (changed hunks only) during git commit.
It uses the same prompt.txt as GitHub Action, so local and PR reviews stay consistent.


✨ Features

  • Reviews only staged hunks (not whole files).
  • Uses secure prompt instructions (copied from the GitHub Action).
  • Summarizes High/Medium/Low risks with clear remediation.
  • Warn-only by default (commits go through even with findings).
  • Strict mode available β†’ block commits if high-risk issues are detected.
  • Only two environment variables are configurable for simplicity.

πŸš€ Installation

  1. Add this repo to your project’s .pre-commit-config.yaml:
repos:
  - repo: https://github.com/DevSecOps-AppSec/ai-secure-code-review-precommit
    rev: v1.0.0
    hooks:
      - id: ai-secure-review-staged
  1. Install pre-commit:
pip install pre-commit
pre-commit install

Now, the hook will run automatically on each commit.


πŸ”‘ Configuration

Required

export OPENAI_API_KEY="sk-..."

Optional

export PRECOMMIT_STRICT=1   # Block commit on High-risk findings (default: warn-only)

πŸ‘‰ To persist, add them to ~/.bashrc, ~/.zshrc, or your shell profile.


βš™οΈ Behavior

  • Collects unified diffs of staged files with risky extensions (.js, .py, .go, .java, etc.).
  • Sends trimmed hunks to the model with secure prompt instructions (prompt.txt).
  • Prints review results inline before commit finishes.
  • In default mode β†’ warnings are shown but commit proceeds.
  • With PRECOMMIT_STRICT=1 β†’ commit is blocked if AI flags High-risk issues.

πŸ“‚ File Structure

ai-secure-code-review-precommit/
β”œβ”€ .pre-commit-hooks.yaml   # hook manifest
β”œβ”€ scripts/
β”‚  └─ ai_precommit_review.js  # Node.js script for staged diff review
β”œβ”€ prompt.txt               # Secure review prompt (same as Action)
β”œβ”€ README.md
└─ LICENSE

πŸ› οΈ Example Workflow

# Stage a risky file
git add app.js

# Try to commit
git commit -m "Add new feature"

# Output:
# ── AI Secure Review (pre-commit) ──
# Risk Summary: High:1, Medium:2, Low:0
# 1. [Finding] Possible SQL Injection...
#    Why it matters...
#    Evidence: + db.query("SELECT * FROM " + userInput)
#    Fix: Use parameterized queries.
#
# Safeguards Checklist:
# - [x] Input validation
# - [ ] SQL injection prevention
#
# ❌ Commit blocked (if PRECOMMIT_STRICT=1)

🧰 Troubleshooting

  • [pre-commit] OPENAI_API_KEY not set β€” skipping AI review.
    β†’ Make sure you exported your key (export OPENAI_API_KEY=...).

  • API quota exceeded / 429
    β†’ Upgrade your API plan or use another base URL (hardcoded to OpenAI default).

  • Timeout
    β†’ Reduce diff size or line counts (hardcoded MAX_LINES=1200).


❌ Uninstall

pre-commit uninstall

πŸ“œ License

MIT