# 🛡️ GuardRails Security Scanner (Python)

**AI-powered security scanner for modern development workflows**

GuardRails uses advanced AI (Gemini) to detect security vulnerabilities in your code, providing detailed explanations and fix suggestions.

## 🚀 Quick Start

```bash
# Install from PyPI
pip install guardrails-security

# Or install from source
pip install git+https://github.com/guardrails/guardrails-security.git

# Scan your code
guardrails scan .

# Initialize in your project
guardrails init
```

## 📋 Features

- ✅ **AI-Powered Analysis** - Uses Gemini AI for intelligent vulnerability detection
- ✅ **Multi-Language Support** - Python, JavaScript, TypeScript, Java, Go, PHP, Ruby, C#
- ✅ **Detailed Fix Suggestions** - Get specific code fixes for each vulnerability
- ✅ **CI/CD Integration** - Easy integration with GitHub Actions, GitLab CI, etc.
- ✅ **Git Hooks** - Automatic scanning before commits
- ✅ **Multiple Output Formats** - Text, JSON, table formats
- ✅ **Configurable** - Customize scan rules and ignore patterns

## 🔧 Installation

### From PyPI (Recommended)
```bash
pip install guardrails-security
```

### From Source
```bash
git clone https://github.com/guardrails/guardrails-security.git
cd guardrails-security
pip install -e .
```

### Development Installation
```bash
git clone https://github.com/guardrails/guardrails-security.git
cd guardrails-security
pip install -e ".[dev]"
```

## 📖 Usage

### Basic Scanning

```bash
# Scan current directory
guardrails scan .

# Scan specific file
guardrails scan app.py

# Scan with JSON output
guardrails scan . --format json

# Save report to file
guardrails scan . --output security-report.json
```

### CI/CD Integration

```bash
# Fail build on critical issues
guardrails scan . --fail-on-critical

# Generate JSON report for CI
guardrails scan . --format json --output guardrails-report.json
```

### Git Hooks

```bash
# Install pre-commit hook
guardrails install-hook

# Install hook that blocks commits on critical issues
guardrails install-hook --fail-on-critical
```

### Project Initialization

```bash
# Initialize GuardRails in your project
guardrails init
```

This creates:
- `guardrails.config.json` - Configuration file
- `.guardrailsignore` - Ignore patterns
- Updates `requirements.txt` if it exists

## ⚙️ Configuration

Create a `guardrails.config.json` file:

```json
{
  "version": "1.0.0",
  "scan": {
    "extensions": [".py", ".js", ".ts", ".jsx", ".tsx", ".java", ".go"],
    "ignore": ["node_modules/**", ".git/**", "dist/**", "build/**"],
    "failOnCritical": true
  },
  "ci": {
    "enabled": true,
    "output": "guardrails-report.json"
  }
}
```

## 🔗 CI/CD Integration

### GitHub Actions

```yaml
name: Security Scan
on: [push, pull_request]

jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Setup Python
        uses: actions/setup-python@v2
        with:
          python-version: '3.9'
      - name: Install GuardRails
        run: pip install guardrails-security
      - name: Run Security Scan
        run: guardrails scan . --fail-on-critical
```

### GitLab CI

```yaml
security_scan:
  stage: test
  image: python:3.9
  script:
    - pip install guardrails-security
    - guardrails scan . --format json --output guardrails-report.json
  artifacts:
    reports:
      junit: guardrails-report.json
```

### Makefile Integration

```makefile
.PHONY: security-scan
security-scan:
	guardrails scan . --fail-on-critical

.PHONY: security-report
security-report:
	guardrails scan . --format json --output security-report.json
```

## 🎯 Supported Languages

- **Python** - `.py`
- **JavaScript/TypeScript** - `.js`, `.ts`, `.jsx`, `.tsx`
- **Java** - `.java`
- **Go** - `.go`
- **PHP** - `.php`
- **Ruby** - `.rb`
- **C#** - `.cs`

## 🔍 Vulnerability Types

GuardRails detects:

- **SQL Injection** - Database query vulnerabilities
- **XSS (Cross-Site Scripting)** - Web application vulnerabilities
- **Hardcoded Credentials** - Exposed passwords and API keys
- **Insecure Dependencies** - Vulnerable third-party packages
- **Authentication Issues** - Weak authentication mechanisms
- **Authorization Flaws** - Access control problems
- **Data Exposure** - Sensitive data leaks
- **Cryptographic Issues** - Weak encryption and hashing

## 📊 Output Formats

### Text Format (Default)
```
🛡️  GuardRails Security Report
═══════════════════════════════════════

📊 Security Score: 75/100
📁 Files Scanned: 15
🚨 Total Issues: 3

📋 Issues by Severity:
   🔴 Critical: 1
   🟡 High: 1
   🔵 Medium: 1
   🟢 Low: 0

🔍 Detailed Findings:

1. SQL INJECTION
   📁 File: src/database.py:25
   ⚠️  Potential SQL injection detected
   💡 Fix: Use parameterized queries to prevent SQL injection...
```

### JSON Format
```json
{
  "securityScore": 75,
  "summary": {
    "totalFiles": 15,
    "vulnerabilities": 3,
    "critical": 1,
    "high": 1,
    "medium": 1,
    "low": 0
  },
  "findings": [
    {
      "id": "sql-injection-123",
      "type": "SQL_INJECTION",
      "severity": "CRITICAL",
      "file": "src/database.py",
      "line": 25,
      "message": "Potential SQL injection detected",
      "fix": "Use parameterized queries...",
      "analysis": "Detailed AI analysis..."
    }
  ]
}
```

## 🛠️ API Usage

```python
from guardrails import GuardRailsScanner

# Initialize scanner
scanner = GuardRailsScanner(
    api_key="your-api-key",  # Optional for local server
    base_url="https://api.guardrails.dev"  # Or local server
)

# Scan directory
results = scanner.scan("./src")

# Check for critical issues
if scanner.has_critical_issues(results):
    print("Critical security issues found!")
    exit(1)

# Get formatted report
report = scanner.format_report(results, "text")
print(report)

# Check server status
status = scanner.check_server_status()
print(f"Server status: {status['status']}")
```

## 🔧 Command Line Options

```bash
guardrails scan <target> [options]

Options:
  -f, --format <format>     Output format (text, json, table)
  -o, --output <file>       Output file path
  --fail-on-critical        Exit with error code if critical issues found
  --ignore <patterns>       Ignore patterns (comma-separated)
  --extensions <exts>       File extensions to scan (comma-separated)
  --api-key <key>           GuardRails API key
  --server <url>            GuardRails server URL
  --timeout <seconds>       Request timeout
  -h, --help                Display help
  -V, --version             Display version
```

## 🌐 Server Setup

GuardRails requires a backend server for AI analysis:

```bash
# Clone the repository
git clone https://github.com/guardrails/guardrails.git
cd guardrails

# Install dependencies
pip install -r requirements.txt

# Set up environment
cp env.example .env
# Edit .env with your Gemini API key

# Start the server
python -m guardrails.server
```

## 📈 Business Model

GuardRails offers multiple pricing tiers:

### 🆓 Free Tier
- Individual developers
- Public repositories
- 100 scans/month
- Basic vulnerability detection

### 💼 Team ($49/month)
- Up to 5 developers
- Private repositories
- 1,000 scans/month
- AI-powered fix suggestions
- CI/CD integration

### 🏢 Enterprise ($299/month)
- Unlimited developers
- Unlimited scans
- Advanced reporting
- Priority support
- Custom rules

### 🏛️ Enterprise+ ($999/month)
- On-premise deployment
- SLA guarantee
- Dedicated support
- Custom integrations

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md).

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## 📄 License

MIT License - see [LICENSE](LICENSE) file.

## 🔗 Links

- **Website**: https://guardrails.dev
- **Documentation**: https://docs.guardrails.dev
- **GitHub**: https://github.com/guardrails/guardrails-security
- **PyPI**: https://pypi.org/project/guardrails-security/
- **Support**: support@guardrails.dev

## 🆘 Support

- **Documentation**: https://docs.guardrails.dev
- **Issues**: https://github.com/guardrails/guardrails-security/issues
- **Email**: support@guardrails.dev
- **Discord**: https://discord.gg/guardrails

---

**Made with ❤️ by the GuardRails team**
