Metadata-Version: 2.4
Name: shieldlayer
Version: 0.3.0
Summary: Enterprise API Security Middleware for FastAPI and Flask
Author-email: KANAGARAJ M <kanagarajm638@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/KANAGARAJ-M/shieldlayer
Project-URL: Documentation, https://github.com/KANAGARAJ-M/shieldlayer#readme
Project-URL: Repository, https://github.com/KANAGARAJ-M/shieldlayer
Project-URL: Issues, https://github.com/KANAGARAJ-M/shieldlayer/issues
Keywords: security,api,rate-limiting,fastapi,flask,middleware
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Security
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Framework :: FastAPI
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: redis>=5.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: click>=8.0.0
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.110.0; extra == "fastapi"
Requires-Dist: uvicorn>=0.29.0; extra == "fastapi"
Provides-Extra: flask
Requires-Dist: flask>=3.0.0; extra == "flask"
Provides-Extra: geo
Requires-Dist: geoip2>=4.0.0; extra == "geo"
Provides-Extra: sqlalchemy
Requires-Dist: sqlalchemy>=2.0.0; extra == "sqlalchemy"
Provides-Extra: dashboard
Requires-Dist: fastapi>=0.110.0; extra == "dashboard"
Requires-Dist: uvicorn>=0.29.0; extra == "dashboard"
Provides-Extra: all
Requires-Dist: fastapi>=0.110.0; extra == "all"
Requires-Dist: uvicorn>=0.29.0; extra == "all"
Requires-Dist: flask>=3.0.0; extra == "all"
Requires-Dist: geoip2>=4.0.0; extra == "all"
Requires-Dist: sqlalchemy>=2.0.0; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
Requires-Dist: httpx>=0.27.0; extra == "dev"
Requires-Dist: black>=24.0.0; extra == "dev"
Requires-Dist: ruff>=0.4.0; extra == "dev"
Dynamic: license-file

# 🛡 ShieldLayer

**Enterprise API Security Middleware for FastAPI and Flask**

[![PyPI](https://img.shields.io/pypi/v/shieldlayer?color=blue)](https://pypi.org/project/shieldlayer/)
[![Python](https://img.shields.io/badge/python-3.9%2B-blue)](https://python.org)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![GitHub](https://img.shields.io/badge/GitHub-KANAGARAJ--M-black?logo=github)](https://github.com/KANAGARAJ-M/shieldlayer)

ShieldLayer provides plug-and-play enterprise-grade security for your Python APIs — covering rate limiting, abuse detection, API key management, geo-blocking, and threat scoring — all in **one package**.

---

## 🚀 Quick Start

### Install

```bash
pip install shieldlayer

# With FastAPI support
pip install shieldlayer[fastapi]

# With Flask support
pip install shieldlayer[flask]

# Everything
pip install shieldlayer[all]
```

### FastAPI — 3 lines of protection

```python
from shieldlayer import SecureAPI

secure = SecureAPI()
app.middleware("http")(secure.fastapi_middleware)
```

### Flask — 2 lines of protection

```python
from shieldlayer import SecureAPI

secure = SecureAPI()
secure.init_flask(app)
```

---

## ✨ Features

| Feature | Free | Pro |
|---------|:----:|:---:|
| Redis Rate Limiting (per IP, key, endpoint) | ✅ | ✅ |
| API Key Management (generate, rotate, revoke) | ✅ | ✅ |
| Brute Force Detection | ✅ | ✅ |
| Rapid Endpoint Switching Detection | ✅ | ✅ |
| Security Audit CLI | ✅ | ✅ |
| **Threat Scoring Engine** | ❌ | ✅ |
| **Geo Blocking** | ❌ | ✅ |
| **Behavior Pattern Detection** | ❌ | ✅ |
| **Webhook Alerts** | ❌ | ✅ |

---

## 🛡 Core Components

### 1. Rate Limiting

Uses a **sliding window algorithm** backed by Redis (with in-memory fallback for development).

```python
from shieldlayer import SecureAPI
from shieldlayer.config import ShieldLayerConfig, RateLimitConfig

config = ShieldLayerConfig(
    rate_limit=RateLimitConfig(
        requests_per_minute=60,
        requests_per_hour=1000,
        per_ip=True,
        per_api_key=True,
        per_endpoint=False,
    )
)
secure = SecureAPI(config=config)
```

Response headers automatically added:
```
X-RateLimit-Remaining: 42
Retry-After: 30        ← only when blocked
```

---

### 2. API Key Management

Full lifecycle: generate → validate → rotate → revoke.

```python
from shieldlayer.api_keys.manager import APIKeyManager
from shieldlayer.config import APIKeyConfig

mgr = APIKeyManager(APIKeyConfig())

# Create
key = mgr.create(user_id="user_123", name="Production Key")
print(key["plain_key"])   # sl_Xk7j... — store this once!

# Validate (in your auth middleware)
record = mgr.validate(request.headers["X-Api-Key"])

# Rotate
new_key = mgr.rotate(key["key_id"])

# Revoke
mgr.revoke(key["key_id"])
```

---

### 3. Abuse Detection

Catches: failed login floods, rapid endpoint scanning, and extreme request frequency.

```python
# Record a failed login attempt
secure._abuse_detector.record_failed_login(f"ip:{client_ip}", "/login")

# Record a request (called automatically by middleware)
secure._abuse_detector.record_request(f"ip:{client_ip}", request.path)
```

When threshold is hit → `AbuseDetected` exception → `403 Forbidden` response.

---

### 4. Threat Scoring Engine *(Pro)*

Composite scoring from multiple risk signals:

```python
from shieldlayer.core.scoring import ThreatScorer
from shieldlayer.config import ThreatScoringConfig

scorer = ThreatScorer(ThreatScoringConfig(
    block_threshold=7.5,
    alert_webhook_url="https://your-webhook.com/alerts",
))

report = scorer.assess(
    identifier="ip:1.2.3.4",
    failed_attempts=8,
    geo_mismatch=True,
    ip_reputation_score=6.5,
    unusual_patterns=3,
)

print(report.total_score)       # 0–10
print(report.recommendation)   # allow | monitor | temp_block | perm_block
```

---

### 5. Geo Blocking *(Pro)*

```python
from shieldlayer.config import GeoBlockConfig, ShieldLayerConfig

config = ShieldLayerConfig(
    geo_block=GeoBlockConfig(
        enabled=True,
        blocked_countries=["CN", "RU", "KP"],   # blocklist mode
        # OR
        allowed_countries=["US", "GB", "IN"],   # allowlist mode (stricter)
        geoip_db_path="/path/to/GeoLite2-Country.mmdb",  # optional
    )
)
```

---

## 🖥 CLI

```bash
# Initialize config file
shieldlayer init

# Run full security audit
shieldlayer audit

# Check component status
shieldlayer status

# Manage API keys
shieldlayer key create user_123 --name "Production"
shieldlayer key list user_123
shieldlayer key rotate <key_id>
shieldlayer key revoke <key_id>
```

Example audit output:
```
Check                                    Status     Points
─────────────────────────────────────────────────────────────
Redis connectivity                       ✅ PASS    +2.0
Database connectivity                    ✅ PASS    +1.0
Abuse detection (config)                 ✅ PASS    +2.0
Threat scoring (Pro)                     ❌ FAIL     2.0

🛡  Security Score: 7.4/10.0
```

---

## 📦 Package Structure

```
shieldlayer/
├── core/
│   ├── middleware.py      ← SecureAPI (main entry point)
│   ├── rate_limit.py      ← Sliding window rate limiter
│   ├── abuse.py           ← Abuse & brute-force detection
│   └── scoring.py         ← Threat scoring engine (Pro)
├── api_keys/
│   ├── manager.py         ← API key full lifecycle
│   └── rotation.py        ← Background rotation scheduler
├── geo/
│   └── geo_block.py       ← Country-based blocking (Pro)
├── cli/
│   └── main.py            ← CLI commands
├── config.py              ← All configuration dataclasses
├── exceptions.py          ← Custom exceptions
└── utils.py               ← Helpers
```

---

## 🔒 Security Response Headers

ShieldLayer automatically injects secure response headers:

| Header | Description |
|--------|-------------|
| `X-RateLimit-Remaining` | Requests remaining in current window |
| `X-ShieldLayer-Latency` | ShieldLayer middleware overhead (ms) |
| `Retry-After` | Seconds to wait after rate limit hit |

---

## ⚙ Full Configuration Reference

```python
from shieldlayer.config import ShieldLayerConfig

config = ShieldLayerConfig(
    redis_url="redis://localhost:6379/0",
    redis_prefix="myapp",

    # IP whitelisting / blacklisting
    whitelist_ips=["10.0.0.1"],
    blacklist_ips=["1.2.3.4"],

    rate_limit=RateLimitConfig(
        requests_per_minute=60,
        requests_per_hour=1000,
        burst_size=10,
        per_ip=True,
        per_api_key=True,
        per_endpoint=False,
    ),
    abuse_detection=AbuseDetectionConfig(
        enabled=True,
        max_failed_logins=5,
        failed_login_window=300,
        rapid_switch_threshold=20,
        suspicious_frequency_threshold=100,
        block_duration=3600,
    ),
    # Pro features:
    threat_scoring=ThreatScoringConfig(
        enabled=True,
        block_threshold=7.5,
        alert_threshold=5.0,
        perm_block_threshold=9.5,
        alert_webhook_url="https://hooks.slack.com/...",
    ),
    geo_block=GeoBlockConfig(
        enabled=True,
        blocked_countries=["CN", "RU"],
        geoip_db_path="/path/to/GeoLite2-Country.mmdb",
    ),
)
```

---

## 🧪 Running Tests

```bash
pip install shieldlayer[dev]
pytest tests/ -v
```

---

## 📄 License

MIT License. See [LICENSE](LICENSE).

---

## 💼 Commercial Licensing

For Pro features (Threat Scoring, Geo Blocking, Behavior Detection, Webhook Alerts), contact us at: **kanagarajm638@gmail.com**

Pricing:
- **Pro**: $79/month — Threat scoring, geo-blocking, webhooks
- **Enterprise**: $299/month — SLA, custom rules, dedicated support
