Enterprise API Security Middleware for FastAPI and Flask
Project description
๐ก ShieldLayer
Enterprise API Security Middleware for FastAPI and Flask
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
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
from shieldlayer import SecureAPI
secure = SecureAPI()
app.middleware("http")(secure.fastapi_middleware)
Flask โ 2 lines of protection
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).
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.
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.
# 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:
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)
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
# 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
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
pip install shieldlayer[dev]
pytest tests/ -v
๐ License
MIT License. See 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
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file shieldlayer-0.3.0.tar.gz.
File metadata
- Download URL: shieldlayer-0.3.0.tar.gz
- Upload date:
- Size: 47.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c70c153349e635a7651508e0d191d268775a1f4b07a6057c436b77880cc90649
|
|
| MD5 |
c771faa1ce47958240fcf20b47524301
|
|
| BLAKE2b-256 |
9bf1d37ae1adcf5d90fe482b05c8fe370d3a433459e57d7665aade9c9403a9e3
|
File details
Details for the file shieldlayer-0.3.0-py3-none-any.whl.
File metadata
- Download URL: shieldlayer-0.3.0-py3-none-any.whl
- Upload date:
- Size: 43.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
0d3e162494fa844967ad0c4ad2ddfe0309361a42ce156c19569a513fc5b84545
|
|
| MD5 |
cf4478c1e58a2fefafe0c8b67418ce1b
|
|
| BLAKE2b-256 |
8485682c38c6a42fdcddc1221f2c4ab89642a6b5951c70cfd3468ed7726cdf4d
|