diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..6c36812 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,27 @@ +{ + "name": "PatchPro CI Demo Environment", + "image": "mcr.microsoft.com/devcontainers/python:3.11", + "features": { + "ghcr.io/devcontainers/features/github-cli:1": {}, + "ghcr.io/devcontainers/features/git:1": {}, + "ghcr.io/devcontainers/features/common-utils:2": { + "installZsh": true, + "configureZshAsDefaultShell": true, + "installOhMyZsh": true + } + }, + "customizations": { + "vscode": { + "extensions": [ + "ms-python.python", + "ms-python.pylint", + "ms-python.flake8", + "GitHub.copilot", + "GitHub.copilot-chat" + ] + } + }, + "postCreateCommand": "bash .devcontainer/setup.sh", + "remoteUser": "vscode", + "workspaceFolder": "/workspaces/patchpro-demo-repo-waigi-ci-test-demo" +} \ No newline at end of file diff --git a/.devcontainer/setup.sh b/.devcontainer/setup.sh new file mode 100644 index 0000000..daa7c65 --- /dev/null +++ b/.devcontainer/setup.sh @@ -0,0 +1,34 @@ +#!/bin/bash + +# PatchPro CI Demo Environment Setup +echo "🚀 Setting up PatchPro CI Demo environment..." + +# Install PatchPro (from source since not on PyPI) +echo "📦 Installing PatchPro..." +pip install git+https://github.com/A3copilotprogram/patchpro-bot.git + +# Verify installation +echo "✅ Verifying PatchPro installation..." +patchpro version + +# Configure git (required for CI demos) +echo "🔧 Configuring git..." +git config --global user.name "Judge Demo User" +git config --global user.email "judge@demo.patchpro" +git config --global init.defaultBranch main + +# Set up GitHub CLI authentication hint +echo "🔑 GitHub CLI setup:" +echo "Run 'gh auth login' to authenticate with GitHub for PR demos" + +# Make demo scripts executable +echo "🎬 Making demo scripts executable..." +chmod +x *.sh 2>/dev/null || true + +echo "✨ Setup complete! Ready for PatchPro CI demos." +echo "" +echo "Available demo scripts:" +echo " • ./create-judge-demo.sh - Quick CI trigger demo" +echo " • ./demo-complete-pr-workflow.sh - Full PR workflow demo" +echo "" +echo "📖 See JUDGES_DEMO_GUIDE.md for detailed instructions" \ No newline at end of file diff --git a/.patchpro.toml b/.patchpro.toml new file mode 100644 index 0000000..8fdd82d --- /dev/null +++ b/.patchpro.toml @@ -0,0 +1,31 @@ +[analysis] +tools = ["ruff", "semgrep"] +exclude_patterns = ["tests/", "__pycache__/", ".venv/", ".git/"] +max_findings_per_file = 50 +severity_threshold = "info" + +[ruff] +config_file = "pyproject.toml" +select = ["E", "F", "W", "C90", "I", "N", "UP", "B", "A", "C4", "SIM", "ARG", "PTH"] +line_length = 88 +target_version = "py312" + +[semgrep] +config = ".semgrep.yml" + +[llm] +model = "gpt-4o-mini" +max_tokens = 4000 +temperature = 0.1 +api_key_env = "OPENAI_API_KEY" + +[output] +artifacts_dir = ".patchpro" +format = "table" +include_patches = true +verbose = false + +[agent] +enable_agentic_mode = true +agentic_max_retries = 3 +agentic_enable_planning = true diff --git a/JUDGES_DEMO_GUIDE.md b/JUDGES_DEMO_GUIDE.md new file mode 100644 index 0000000..32b2719 --- /dev/null +++ b/JUDGES_DEMO_GUIDE.md @@ -0,0 +1,85 @@ +# 🛡️ PatchPro: See It in Action + +## 🎯 Quick Demo Options + +### Option 1: Watch Real CI/CD in Action (Recommended) +**See PatchPro running live in GitHub Actions:** + +📋 **Step-by-step:** +1. 🔗 **[View Live Workflow Runs](https://github.com/A3copilotprogram/patchpro-demo-repo-waigi-ci-test-demo/actions)** +2. Click any recent "PatchPro Agent-Dev" workflow +3. Click "Run PatchPro analyze-pr" step to see full output +4. Scroll through to see: + - ✅ Code analysis with Ruff + Semgrep + - ✅ AI patch generation with GPT-4o-mini + - ✅ Git validation and telemetry + - ✅ PR comment posting + +**What you'll see:** +- Real vulnerability detection +- AI-powered patch generation +- Self-correction attempts +- Comprehensive telemetry +- PR integration + +### Option 2: Interactive Demo (Zero Setup) +**Try it yourself in browser:** + +[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/A3copilotprogram/patchpro-demo-repo-waigi-ci-test-demo?quickstart=1) + +1. Click the button above +2. Wait 2-3 minutes for setup +3. Run: `./demo-real-workflow.sh` + +### Option 3: Create Your Own PR +**Trigger PatchPro yourself:** + +1. 🍴 Fork this repository +2. 🔧 Edit any `.py` file (introduce a security issue) +3. 📝 Create a Pull Request +4. 🤖 Watch PatchPro analyze and comment automatically + +## 🎬 Recent Demo Runs + +**Live examples you can view right now:** + +- 🔗 [Latest Workflow Run](https://github.com/A3copilotprogram/patchpro-demo-repo-waigi-ci-test-demo/actions/runs/latest) +- 🔗 [Example PR with PatchPro Comments](https://github.com/A3copilotprogram/patchpro-demo-repo-waigi-ci-test-demo/pulls) +- 🔗 [Download Artifacts](https://github.com/A3copilotprogram/patchpro-demo-repo-waigi-ci-test-demo/actions) (patches, traces, reports) + +## 📊 What PatchPro Does + +**In the GitHub Action, you'll see:** + +1. **Code Analysis** + ```bash + python -m patchpro_bot.cli analyze-pr --base origin/main --head HEAD --with-llm + ``` + +2. **AI Patch Generation** + - GPT-4o-mini analyzes findings + - Generates production-ready unified diffs + - Validates with `git apply --check` + +3. **PR Integration** + - Posts detailed analysis comment + - Uploads artifacts (patches, traces, reports) + - Shows telemetry and performance metrics + +4. **Self-Learning** + - Captures traces in SQLite database + - Records prompt/response pairs for ML training + - Tracks success/failure patterns + +## 🚀 Key Features Demonstrated + +- ✅ **Multi-Tool Analysis**: Ruff + Semgrep integration +- ✅ **AI-Powered Patches**: GPT-4o-mini generates fixes +- ✅ **Git Validation**: Every patch tested before delivery +- ✅ **Self-Learning**: SQLite traces for continuous improvement +- ✅ **CI/CD Integration**: Seamless GitHub Actions workflow +- ✅ **PR Comments**: Actionable insights posted automatically + +## 🏆 Built for Andela GenAI Mastery Program 2025 + +**Team PLG_5** | [patchpro.ai](https://patchpro.ai) | [Documentation](https://github.com/A3copilotprogram/patchpro-bot) \ No newline at end of file diff --git a/create-judge-demo.sh b/create-judge-demo.sh new file mode 100755 index 0000000..f25df68 --- /dev/null +++ b/create-judge-demo.sh @@ -0,0 +1,127 @@ +#!/bin/bash +# Trigger Real PatchPro CI Demo +# Creates a PR with security issues and lets judges watch the real CI workflow + +set -e + +echo "🛡️ Creating Real PatchPro CI Demo..." +echo "" + +# Create a branch with timestamp +DEMO_BRANCH="demo/judge-test-$(date +%s)" +echo "📝 Creating branch: $DEMO_BRANCH" +git checkout -b "$DEMO_BRANCH" + +# Add a file with real security vulnerabilities +echo "🔴 Adding vulnerable code..." +cat > judge_demo_vulnerable.py << 'EOF' +# PatchPro Judge Demo - Vulnerable Code +# This file contains REAL security issues that PatchPro will detect and fix + +import sqlite3 +import hashlib + +# SECURITY ISSUE: Hardcoded database password +DB_PASSWORD = "super_secret_admin_password_123" + +def authenticate_user(username, password): + """VULNERABLE: SQL Injection""" + conn = sqlite3.connect("users.db") + # SECURITY ISSUE: Direct string interpolation = SQL injection + query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'" + cursor = conn.execute(query) + return cursor.fetchone() is not None + +def hash_password(password): + """VULNERABLE: Weak hashing""" + # SECURITY ISSUE: MD5 is cryptographically broken + return hashlib.md5(password.encode()).hexdigest() + +# SECURITY ISSUE: Hardcoded API key +API_KEY = "sk-1234567890abcdef" +API_SECRET = "secret-key-please-dont-share" + +class UserSession: + def __init__(self): + # SECURITY ISSUE: Predictable session tokens + self.session_token = "user_session_" + str(hash("admin")) + + def validate_input(self, user_input): + """VULNERABLE: No input sanitization""" + # SECURITY ISSUE: Direct eval() execution + return eval(user_input) + +# SECURITY ISSUE: Debug mode with sensitive info +DEBUG = True +if DEBUG: + print(f"Database password: {DB_PASSWORD}") + print(f"API key: {API_KEY}") +EOF + +# Commit the vulnerable code +git add judge_demo_vulnerable.py +git commit -m "feat: add user authentication system (JUDGE DEMO) + +This commit introduces authentication functionality but contains +deliberate security vulnerabilities for PatchPro to detect: + +- SQL injection in authenticate_user() +- Hardcoded credentials (DB_PASSWORD, API_KEY) +- Weak MD5 hashing +- Dangerous eval() usage +- Debug info leakage + +PatchPro should detect and fix all these issues automatically." + +# Push the branch +echo "📤 Pushing branch to trigger CI..." +git push origin "$DEMO_BRANCH" + +# Create the PR +echo "📝 Creating Pull Request..." +PR_URL=$(gh pr create \ + --title "🔴 JUDGE DEMO: Security vulnerabilities for PatchPro to fix" \ + --body "## 🛡️ PatchPro Judge Demonstration + +This PR contains **real security vulnerabilities** for demonstration purposes. + +### 🔴 Security Issues Included: +- **SQL Injection** (line 13): Direct string interpolation in SQL query +- **Hardcoded Credentials** (lines 8, 27-28): Database password and API keys in plaintext +- **Weak Hashing** (line 19): MD5 instead of secure hashing +- **Code Injection** (line 37): Dangerous \`eval()\` usage +- **Information Disclosure** (lines 42-44): Debug mode leaking sensitive data + +### 🤖 Watch PatchPro in Action: + +1. **Check the 'Actions' tab** to see PatchPro CI running +2. **View this PR** for automated comment with analysis +3. **Download artifacts** to see generated patches and telemetry + +### ⏱️ Expected Timeline: +- **Analysis**: 30-60 seconds +- **AI Patch Generation**: 1-2 minutes +- **PR Comment**: Within 3 minutes + +PatchPro will automatically: +✅ Detect all security issues +✅ Generate production-ready patches +✅ Validate patches with git apply +✅ Post comprehensive analysis report +✅ Capture telemetry for self-learning + +**This demonstrates the complete CI/CD integration that judges need to see!**" 2>/dev/null) + +echo "" +echo "🎉 SUCCESS! Real PatchPro demo created:" +echo "" +echo "📋 What to do next:" +echo "1. 🔗 View PR: $PR_URL" +echo "2. 🔗 Watch CI: https://github.com/A3copilotprogram/patchpro-demo-repo-waigi-ci-test-demo/actions" +echo "3. ⏱️ Wait 2-3 minutes for PatchPro to analyze and comment" +echo "4. 📊 Download artifacts to see patches and telemetry" +echo "" +echo "🎯 This shows the REAL PatchPro workflow that judges need to see!" + +# Return to original branch +git checkout main 2>/dev/null || git checkout - \ No newline at end of file diff --git a/demo-single-file-pr.sh b/demo-single-file-pr.sh new file mode 100755 index 0000000..4942049 --- /dev/null +++ b/demo-single-file-pr.sh @@ -0,0 +1,132 @@ +#!/bin/bash +# PatchPro CI/PR Demo - Single File +# Shows PatchPro analyzing one vulnerable file in CI + +set -e + +# Colors +GREEN='\033[0;32m' +BLUE='\033[0;34m' +PURPLE='\033[0;35m' +CYAN='\033[0;36m' +YELLOW='\033[1;33m' +NC='\033[0m' + +clear +echo "" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +echo "🛡️ PatchPro: Single File CI Demo" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +echo " Watch PatchPro analyze vulnerable authentication code" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +echo "" + +echo -e "${CYAN}Step 1: Show the vulnerable file we're submitting${NC}" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +echo "$ cat src/python/auth.py | head -20" +cat src/python/auth.py | head -20 +echo "... (showing first 20 lines)" +echo "" +echo -e "${YELLOW}🚨 This authentication module contains multiple security issues:${NC}" +echo " • Hardcoded database credentials" +echo " • SQL injection vulnerability" +echo " • Weak MD5 hashing" +echo " • Predictable session tokens" +echo " • Debug mode enabled in production" +echo "" +sleep 3 + +echo -e "${PURPLE}Step 2: Create Pull Request from Current Branch${NC}" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" + +# Close any existing PR from this branch to main for repeatability +echo "$ gh pr close --head demo/patchpro-ci-test --base main 2>/dev/null || echo 'No existing PR to close'" +gh pr close --head demo/patchpro-ci-test --base main 2>/dev/null || echo "No existing PR to close" +echo "" + +echo "$ git status" +git status +echo "" + +echo "$ git push origin demo/patchpro-ci-test" +git push origin demo/patchpro-ci-test || echo "✓ Branch pushed" +echo "" + +echo "$ gh pr create --base main --title 'Security Demo: Authentication Module' --body 'Demo PR with vulnerabilities'" +PR_URL=$(gh pr create --base main --title "Security Demo: Authentication Module with Vulnerabilities" --body "This PR adds a new authentication system for demo purposes. Contains deliberate security vulnerabilities for PatchPro CI analysis: + +- Hardcoded database credentials +- SQL injection vulnerabilities +- Weak MD5 hashing +- Predictable session tokens +- Debug mode enabled + +**This is a demo PR** - PatchPro will analyze and provide security fixes." 2>&1 | grep -o 'https://github.com/[^[:space:]]*') + +if [ -n "$PR_URL" ]; then + echo "✅ Pull Request created: $PR_URL" + # Extract repo info for Actions URL + REPO_URL=$(echo "$PR_URL" | sed 's|/pull/.*||') + ACTIONS_URL="${REPO_URL}/actions" +else + echo "✅ Pull Request created successfully" + # Fallback - construct URLs from git remote + REPO_URL=$(git remote get-url origin | sed 's/git@github.com:/https:\/\/github.com\//' | sed 's/\.git$//') + ACTIONS_URL="${REPO_URL}/actions" + PR_URL="${REPO_URL}/pulls" +fi +echo "" +sleep 2 + +echo -e "${BLUE}Step 3: Watch PatchPro CI in Action${NC}" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +echo "🎬 Now it's time to see PatchPro in action!" +echo "" +echo -e "${YELLOW}� CLICK THESE LINKS TO WATCH:${NC}" +echo "" +echo -e "${CYAN}1. 🔄 GitHub Actions (watch PatchPro CI running):${NC}" +echo " $ACTIONS_URL" +echo "" +echo -e "${CYAN}2. 💬 Pull Request (see PatchPro comments):${NC}" +echo " $PR_URL" +echo "" +echo -e "${PURPLE}📋 STEP-BY-STEP INSTRUCTIONS:${NC}" +echo "" +echo "🔄 GitHub Actions Tab:" +echo " 1. Click the Actions link above" +echo " 2. Look for the workflow run that just started" +echo " 3. Click on the running workflow to see live logs" +echo " 4. Watch PatchPro analyze your vulnerable code in real-time" +echo "" +echo "💬 Pull Request Tab:" +echo " 1. Click the PR link above" +echo " 2. Wait 1-2 minutes for PatchPro to complete analysis" +echo " 3. Refresh the page to see PatchPro's comment with:" +echo " • Security vulnerabilities found" +echo " • AI-generated patches for each issue" +echo " • Cost estimate and fix recommendations" +echo "" +echo "🔍 What PatchPro CI will do:" +echo " • Analyze the auth.py file for security vulnerabilities" +echo " • Generate AI-powered patches for each issue" +echo " • Post detailed findings and fixes as PR comments" +echo " • Provide cost estimate and implementation guidance" +echo "" +echo "⏱️ Expected analysis time: 1-2 minutes" +echo "" + +if [ -n "$PR_URL" ]; then + echo "🌐 PR URL: $PR_URL" +fi + +echo "" +echo "🚀 PatchPro CI is now analyzing your code..." +echo -e "${GREEN}✨ Demo complete! PatchPro is working in the background.${NC}" +echo "" +echo -e "${YELLOW}🎯 Next Steps for Judges:${NC}" +echo "1. Click the GitHub Actions link above to watch live analysis" +echo "2. Click the PR link to see results when analysis completes" +echo "3. Experience the power of AI-driven security fixes!" +echo "" +echo -e "${CYAN}🔄 To run demo again:${NC}" +echo " Simply run ./demo-single-file-pr.sh again - it will close the old PR and create a fresh one" \ No newline at end of file diff --git a/src/python/auth.py b/src/python/auth.py new file mode 100644 index 0000000..8fbfb04 --- /dev/null +++ b/src/python/auth.py @@ -0,0 +1,54 @@ +""" +Authentication module with deliberate security vulnerabilities. +This file contains various security issues that PatchPro should detect. +""" + +import hashlib +import sqlite3 +import secrets + +# SECURITY ISSUE: Hardcoded database credentials +DB_PASSWORD = "admin123" +DB_HOST = "prod-db.company.com" + +class AuthManager: + def __init__(self): + # SECURITY ISSUE: Hardcoded secret key + self.secret_key = "my-super-secret-key-2024" + self.db_path = "users.db" + + def authenticate_user(self, username, password): + """Authenticate user - VULNERABLE TO SQL INJECTION""" + conn = sqlite3.connect(self.db_path) + cursor = conn.cursor() + + # SECURITY ISSUE: SQL injection vulnerability + query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'" + cursor.execute(query) + result = cursor.fetchone() + + conn.close() + return result is not None + + def hash_password(self, password): + """Hash password - WEAK HASHING""" + # SECURITY ISSUE: Using MD5 (cryptographically broken) + return hashlib.md5(password.encode()).hexdigest() + + def generate_session_token(self): + """Generate session token - PREDICTABLE""" + # SECURITY ISSUE: Predictable token generation + import time + return f"session_{int(time.time())}" + + def reset_password(self, email): + """Password reset - INSECURE""" + # SECURITY ISSUE: Weak random token + reset_token = str(hash(email)) + return reset_token + +# SECURITY ISSUE: Debug mode enabled in production +DEBUG = True +if DEBUG: + print(f"Database password: {DB_PASSWORD}") + print(f"Secret key: {AuthManager().secret_key}")# Test comment to trigger workflow diff --git a/src/python/payments.py b/src/python/payments.py new file mode 100644 index 0000000..2222083 --- /dev/null +++ b/src/python/payments.py @@ -0,0 +1,58 @@ +""" +Payment processing module with security vulnerabilities. +Demonstrates financial data handling security issues. +""" + +import json +import requests + +class PaymentProcessor: + def __init__(self): + # SECURITY ISSUE: Hardcoded API keys + self.stripe_key = "sk_live_abcd1234567890" + self.paypal_secret = "paypal_secret_key_12345" + + def process_payment(self, card_number, amount, user_data): + """Process payment - MULTIPLE SECURITY ISSUES""" + + # SECURITY ISSUE: Logging sensitive data + print(f"Processing payment: Card {card_number}, Amount ${amount}") + + # SECURITY ISSUE: Storing PII in plaintext + customer_data = { + "card_number": card_number, + "ssn": user_data.get("ssn"), + "full_name": user_data.get("name"), + "address": user_data.get("address") + } + + # SECURITY ISSUE: Writing sensitive data to file + with open("payments.log", "a") as f: + f.write(f"{json.dumps(customer_data)}\n") + + # SECURITY ISSUE: Insecure HTTP for financial API + api_url = f"http://payment-api.company.com/charge" + + # SECURITY ISSUE: No SSL verification + response = requests.post( + api_url, + json=customer_data, + verify=False # Disables SSL verification + ) + + return response.json() + + def validate_card(self, card_number): + """Validate credit card - WEAK VALIDATION""" + # SECURITY ISSUE: No proper card validation + return len(card_number) == 16 + + def calculate_fees(self, amount): + """Calculate fees - POTENTIAL OVERFLOW""" + # SECURITY ISSUE: No bounds checking + fee_rate = 0.029 + return amount * fee_rate * 1000000 # Could cause overflow + +# SECURITY ISSUE: Global variables with sensitive data +MASTER_ENCRYPTION_KEY = "1234567890abcdef" +ADMIN_OVERRIDE_PASSWORD = "backdoor123" \ No newline at end of file