Defense in Depth

Multiple layers of security: AI instructions, pre-commit hooks, commit message validation, and CI scanning.

Why Defense in Depth?

Defense in depth is a security strategy that uses multiple layers of protection. If one layer fails, others still provide protection. This is crucial for AI-assisted development because:

  • AI can make mistakes - Even with instructions, AI might generate insecure code
  • Developers can bypass warnings - Humans can ignore or miss AI suggestions
  • Tools have blind spots - No single tool catches everything
  • Environments vary - Different developers might have different tool configurations

Guardrails-AI implements three complementary layers that work together to prevent security issues from reaching production.

Layer 1: AI Instructions

1

🤖 AI Coding Assistant Rules

What: Configuration files that teach AI assistants your security standards

When: Active while AI generates code (real-time, before code is written)

Tools: Cursor rules, Claude instructions, Copilot guidelines

What This Layer Does:

  • Instructs AI to NEVER include hardcoded secrets
  • Teaches proper use of environment variables
  • Enforces type hints, docstrings, and error handling
  • Promotes secure coding patterns (parameterized queries, input validation)

✓ Defense Strength

Proactive Prevention - Stops issues before code is even written. Most effective when AI follows instructions correctly.

✗ Can Be Bypassed By

  • AI hallucinations or misunderstanding instructions
  • Developer manually editing AI-generated code to include secrets
  • AI tool not loading or respecting configuration files
  • Copy-pasting code from external sources

Example Configuration:

# .cursor/rules/006_security.mdc
priority: 100  # HIGHEST PRIORITY

## NEVER Commit Secrets
 NEVER generate:
  - API keys, tokens, passwords
  - Private keys (SSH, TLS, GPG)
  - Cloud credentials (AWS, GCP, Azure)
  - Database connection strings with passwords

 ALWAYS use:
  - Environment variables: os.environ.get("API_KEY")
  - Configuration files (gitignored): .env
  - Secret management services: AWS Secrets Manager

Layer 2: Pre-commit Hooks

2

🔒 Local Commit-Time Validation

What: Automated checks that run on your machine before code is committed

When: Every time you run git commit

Tools: detect-secrets, shellcheck, black, pylint, yamllint

What This Layer Does:

  • Scans staged files for secrets (API keys, passwords, private keys)
  • Validates code quality (linting, formatting)
  • Checks file integrity (no broken symlinks, no large files)
  • Validates commit message format
  • Blocks the commit if any check fails

✓ Defense Strength

Local Enforcement - Catches issues before they enter git history. Works offline. Immediate feedback to developer.

✗ Can Be Bypassed By

  • Using --no-verify flag: git commit --no-verify
  • Not installing pre-commit hooks
  • Disabling specific hooks in configuration
  • Committing from a different machine without hooks installed

Example Detection:

$ git commit -m "Add API integration"

detect-secrets............................Failed
- hook id: detect-secrets

Potential secret found:
  File: config/settings.py
  Line 15: api_key = "sk-1234567890abcdef"
  Type: Secret Keyword

❌ Commit blocked!

Fix:
1. Remove hardcoded secret
2. Move to environment variable
3. Add to .env.example (without real value)

Layer 3: CI/CD Scanning

3

☁️ Centralized Repository Scanning

What: Comprehensive security scans in GitHub Actions on every push

When: Automatically on push, pull requests, and scheduled runs

Tools: Gitleaks, TruffleHog, Bandit, Semgrep

What This Layer Does:

  • Scans entire git history - Not just current files, but all past commits
  • Multiple scanning tools in parallel (Gitleaks + TruffleHog + Bandit + Semgrep)
  • Blocks pull request merges if issues found
  • Runs on scheduled basis (daily) to catch newly-discovered vulnerabilities
  • Enforced for all team members - no one can bypass

✓ Defense Strength

Comprehensive & Mandatory - Scans full history. Cannot be bypassed. Protects entire team. Catches secrets committed from any environment.

✗ Limitations

  • Only catches issues after they're pushed to GitHub
  • Secret is already in git history (requires history rewriting to remove)
  • Slower feedback loop (minutes vs seconds for pre-commit)

Example CI Workflow:

# .github/workflows/security-ci.yml
name: Security Scanning

on: [push, pull_request, schedule]

jobs:
  gitleaks:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Full history
      
      - name: Run Gitleaks
        uses: gitleaks/gitleaks-action@v2
        
  trufflehog:
    # Entropy-based secret detection
    
  bandit:
    # Python security linter
    
  semgrep:
    # SAST scanner

Real-World Attack Scenarios

Scenario 1: AI Generates Secret (Caught by Layer 1)

🚨 Attack

Developer asks AI: "Add AWS S3 integration"

AI generates code with hardcoded AWS keys

✓ Defense

Layer 1: AI Rules - If AI follows instructions, it won't generate hardcoded keys. Instead generates:

aws_access_key = os.environ.get("AWS_ACCESS_KEY_ID")
aws_secret_key = os.environ.get("AWS_SECRET_ACCESS_KEY")

Scenario 2: Developer Hardcodes Secret (Caught by Layer 2)

🚨 Attack

Developer manually adds database password for "quick testing"

Tries to commit: git commit -m "Add DB connection"

✓ Defense

Layer 2: Pre-commit Hooks - detect-secrets scans staged files, finds password, blocks commit

Scenario 3: Bypass Pre-commit (Caught by Layer 3)

🚨 Attack

Developer bypasses pre-commit: git commit --no-verify

Pushes to GitHub: git push origin main

✓ Defense

Layer 3: CI/CD - Gitleaks scans git history, finds secret, blocks PR merge, alerts team

Scenario 4: Secret in Old Commit (Caught by Layer 3)

🚨 Attack

Secret was committed 6 months ago (before Guardrails-AI was installed)

Still present in git history, accessible to anyone who clones the repo

✓ Defense

Layer 3: Scheduled CI Scans - Daily security scans catch the old secret, alert team to rewrite history and rotate credentials

Why All Three Layers?

Complementary Protection

Layer 1 (AI Rules) - Proactive

  • ✓ Prevents issues before code is written
  • ✓ Educates developers through AI suggestions
  • ✗ Can be bypassed by manual edits

Layer 2 (Pre-commit) - Reactive Local

  • ✓ Catches issues before entering git history
  • ✓ Fast feedback (seconds)
  • ✗ Can be bypassed with --no-verify
  • ✗ Only protects if installed

Layer 3 (CI/CD) - Mandatory Centralized

  • ✓ Cannot be bypassed
  • ✓ Scans full git history
  • ✓ Protects entire team
  • ✗ Slower feedback (minutes)
  • ✗ Secret already in history (requires cleanup)

Together, these layers provide comprehensive protection: proactive prevention, fast local enforcement, and mandatory centralized scanning.

Ready to Implement Defense in Depth?

Set up all three layers of protection in your project.

Get Started with Guardrails-AI