Metadata-Version: 2.4
Name: secuguard
Version: 0.1.0
Summary: Security assumption auditor for backend codebases - catches what checklists miss
Project-URL: Homepage, https://github.com/nikita-ravi/Secugaurd
Project-URL: Documentation, https://github.com/nikita-ravi/Secugaurd#readme
Project-URL: Repository, https://github.com/nikita-ravi/Secugaurd
Project-URL: Issues, https://github.com/nikita-ravi/Secugaurd/issues
Author: Nikita Ravi
License-Expression: MIT
License-File: LICENSE
Keywords: api,audit,authentication,authorization,backend,django,fastapi,flask,idor,security,vulnerability
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.10
Requires-Dist: click>=8.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: rich>=13.0
Provides-Extra: all
Requires-Dist: anthropic>=0.20; extra == 'all'
Requires-Dist: mypy>=1.0; extra == 'all'
Requires-Dist: pytest-cov>=4.0; extra == 'all'
Requires-Dist: pytest>=7.0; extra == 'all'
Requires-Dist: ruff>=0.1.0; extra == 'all'
Provides-Extra: dev
Requires-Dist: mypy>=1.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Provides-Extra: llm
Requires-Dist: anthropic>=0.20; extra == 'llm'
Description-Content-Type: text/markdown

# SecuGuard 🛡️

[![CI](https://github.com/nikita-ravi/Secugaurd/actions/workflows/ci.yml/badge.svg)](https://github.com/nikita-ravi/Secugaurd/actions/workflows/ci.yml)
[![PyPI version](https://badge.fury.io/py/secuguard.svg)](https://badge.fury.io/py/secuguard)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**Security assumption auditor for backend codebases**

SecuGuard finds the vulnerabilities that checklists miss. It analyzes your backend code for security assumption gaps—IDOR vulnerabilities, authentication holes, JWT misconfigurations, race conditions, and broken access control patterns.

## Why SecuGuard?

Traditional security tools (SAST/DAST scanners) find SQL injection and XSS. SecuGuard finds the **logical vulnerabilities**:

- User A can access User B's orders by incrementing IDs (**IDOR**)
- JWT tokens that never expire
- Endpoints with inconsistent authentication
- State-changing operations without auth
- Race conditions in balance updates
- Hardcoded secrets that will be committed to git
- Missing audit logging on sensitive operations

These are the vulnerabilities that happen when engineers think:
> "auth ✅, RBAC ✅, done"

...but forgot to check if **THIS user** owns **THIS resource**.

## Installation

```bash
pip install secuguard
```

With LLM support (for semantic analysis):
```bash
pip install secuguard[llm]
```

Or install from source:
```bash
git clone https://github.com/nikita-ravi/Secugaurd
cd secuguard
pip install -e ".[dev]"
```

## Quick Start

```bash
# Scan current directory
secuguard scan .

# Scan specific path
secuguard scan ./src/api

# JSON output
secuguard scan . --format json --output report.json

# SARIF output (for GitHub Security tab)
secuguard scan . --format sarif --output results.sarif

# Only high severity issues
secuguard scan . --severity high

# Run specific detectors
secuguard scan . --detectors idor --detectors jwt-hygiene

# CI mode (exit non-zero on findings)
secuguard scan . --ci --fail-on medium
```

## Detectors

SecuGuard includes 11 security detectors:

| Detector | Category | What It Catches |
|----------|----------|-----------------|
| `idor` | Authorization | Endpoints accessing resources by ID without ownership verification |
| `jwt-hygiene` | Session | Missing expiration, hardcoded secrets, weak algorithms, verify=False |
| `auth-depth` | Authentication | Unprotected endpoints, inconsistent auth across related routes |
| `rate-limiting` | DoS | Authentication endpoints without rate limiting (brute force risk) |
| `data-exposure` | Privacy | Stack traces in errors, sensitive fields in responses, debug mode |
| `ssrf` | Injection | User-controlled URLs in HTTP requests |
| `race-condition` | Logic | TOCTOU bugs, non-atomic read-modify-write on balances/inventory |
| `audit-logging` | Compliance | Missing audit logs on sensitive operations |
| `mass-assignment` | Authorization | Direct spreading of user input into model updates |
| `secrets` | Credentials | Hardcoded API keys, AWS credentials, tokens in code |
| `injection` | Injection | SQL injection via string formatting, command injection with shell=True |

### List Available Detectors

```bash
secuguard list-detectors
```

## Supported Frameworks

- **FastAPI** - Full support
- **Flask** - Full support
- **Django / Django REST Framework** - Full support

Framework is auto-detected, or specify with `--framework`:
```bash
secuguard scan . --framework flask
```

## GitHub Actions Integration

Add to your workflow:

```yaml
name: Security Scan

on: [push, pull_request]

jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Run SecuGuard
        uses: nikita-ravi/Secugaurd-action@v1
        with:
          path: ./src
          fail-on: high
          output-format: sarif
          output-file: results.sarif

      - name: Upload SARIF
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: results.sarif
```

Or manually:

```yaml
- uses: actions/setup-python@v5
  with:
    python-version: '3.11'
- run: pip install secuguard
- run: secuguard scan . --format sarif --output results.sarif --ci --fail-on high
- uses: github/codeql-action/upload-sarif@v3
  with:
    sarif_file: results.sarif
```

## Configuration

Create `.secuguard.yaml` in your project root:

```yaml
# Framework (auto, fastapi, flask, django)
framework: auto

# Minimum severity to report
min_severity: medium

# Specific detectors to run (omit for all)
detectors:
  - idor
  - jwt-hygiene
  - auth-depth
  - rate-limiting
  - secrets

# Paths to ignore
ignore_paths:
  - tests/
  - test_
  - migrations/
  - __pycache__/
  - .venv/
  - node_modules/

# CI settings
ci:
  fail_on: high
```

Initialize with defaults:
```bash
secuguard init
```

## Python API

```python
from secuguard import SecurityAnalyzer
from secuguard.core.report import Severity

# Basic scan
analyzer = SecurityAnalyzer(path="./src")
report = analyzer.analyze()

print(f"Found {report.summary['total']} issues")
for finding in report.findings:
    print(f"[{finding.severity.value}] {finding.title}")
    print(f"  Location: {finding.location}")
    print(f"  {finding.description}")

# With options
analyzer = SecurityAnalyzer(
    path="./src",
    framework="fastapi",
    detectors=["idor", "jwt-hygiene", "auth-depth"],
    min_severity=Severity.MEDIUM,
    ignore_paths=["tests/", "migrations/"],
)
report = analyzer.analyze()

# Export
report.save("report.json", format="json")
report.save("results.sarif", format="sarif")
report.save("report.md", format="markdown")
```

## LLM-Powered Analysis (Optional)

SecuGuard includes an optional LLM layer for semantic security analysis:

```python
from secuguard.llm import create_analyzer

# Requires ANTHROPIC_API_KEY environment variable
llm = create_analyzer()

# Analyze authentication flow
result = llm.analyze_auth_flow(parsed_codebase)

# Generate attack narratives
narratives = llm.generate_attack_narrative(parsed_codebase)
```

## Docker

```bash
# Build
docker build -t secuguard .

# Scan a directory
docker run -v $(pwd):/code secuguard scan /code

# With options
docker run -v $(pwd):/code secuguard scan /code --format json --output /code/report.json
```

## Example Output

```
$ secuguard scan ./examples

╭─────────────────────────────────────────────╮
│ SecuGuard - Security Assumption Auditor     │
│          Finding what checklists miss       │
╰─────────────────────────────────────────────╯

Path:          ./examples
Framework:     fastapi
Files Scanned: 1
Duration:      0.05s

Found 2 critical, 4 high, 3 medium

🔴 [CRITICAL] Hardcoded JWT secret
   Location: examples/app.py:21

   JWT secret key appears to be hardcoded in source code.

   Recommendation:
   Move secrets to environment variables or a secrets manager.

🟠 [HIGH] Potential IDOR in GET /orders/{order_id}
   Location: examples/app.py:58

   Endpoint uses resource identifier [order_id] from the path
   but does not verify the authenticated user owns the resource.

   Recommendation:
   Add ownership verification:
     db.query(Order).filter(Order.id == order_id, Order.user_id == current_user.id)

🟠 [HIGH] Unprotected DELETE endpoint
   Location: examples/app.py:121

   State-changing endpoint DELETE /orders/{order_id} has no authentication.

   Recommendation:
   Add authentication: Depends(get_current_user)
```

## How It Works

1. **Parse**: AST analysis extracts routes, middleware, auth decorators, database queries
2. **Model**: Build a semantic model of endpoints with auth requirements and data access patterns
3. **Detect**: Run rule-based and heuristic detectors to find security assumption gaps
4. **Report**: Generate actionable findings with specific file/line locations and fix recommendations

## Contributing

Contributions welcome! Areas where help is needed:

- **New detectors**: CSRF, XXE, deserialization, GraphQL-specific issues
- **Parser improvements**: Better database query analysis, more frameworks
- **LLM integration**: Improved semantic analysis, business logic detection
- **Testing**: More test cases, real-world vulnerability samples

### Development Setup

```bash
git clone https://github.com/nikita-ravi/Secugaurd
cd secuguard
pip install -e ".[dev]"

# Run tests
pytest

# Run linting
ruff check src/ tests/

# Run type checking
mypy src/secuguard
```

## License

MIT

## Acknowledgments

- OWASP API Security Top 10
- CWE (Common Weakness Enumeration)
- The security research community

---

**SecuGuard** - Because security is not a checklist. It's an adversarial systems problem.
