Skip to main content

Enterprise API Security Middleware for FastAPI and Flask

Project description

๐Ÿ›ก ShieldLayer

Enterprise API Security Middleware for FastAPI and Flask

PyPI Python License: MIT GitHub

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: pro@shieldlayer.io

Pricing:

  • Pro: $79/month โ€” Threat scoring, geo-blocking, webhooks
  • Enterprise: $299/month โ€” SLA, custom rules, dedicated support

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

shieldlayer-0.2.0.tar.gz (44.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

shieldlayer-0.2.0-py3-none-any.whl (40.8 kB view details)

Uploaded Python 3

File details

Details for the file shieldlayer-0.2.0.tar.gz.

File metadata

  • Download URL: shieldlayer-0.2.0.tar.gz
  • Upload date:
  • Size: 44.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for shieldlayer-0.2.0.tar.gz
Algorithm Hash digest
SHA256 6704cc116ce75356570af506b7f0e2ff2f9016c1ca1e3ad8ee678b6d2d6e01ac
MD5 60158e737cfaa91a963331c35317d620
BLAKE2b-256 66010430df6094df718b7d0000b03bdb0c87d45798e1d00607d5789ec323a805

See more details on using hashes here.

File details

Details for the file shieldlayer-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: shieldlayer-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 40.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for shieldlayer-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 898baa2f965ce4858b4d83531dea67c87e863942934264f1bea045927ba777fa
MD5 e2dea84b79f7dd7c2476a056390f03ae
BLAKE2b-256 4b54a0b7cdf758882e59eea3276529985f91aedce3fa415e98e5ae0e78e12046

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page