Skip to main content

Table of Contents generated with DocToc

PyWebGuard

PyPI version Python Versions License All Contributors PyPI Downloads

Python FastAPI Flask Docker Memory Redis SQLite TinyDB PostgreSQL MongoDB Meilisearch Elasticsearch Pytest Pytest-Cov Black CORS GitHub Actions Telegram

A comprehensive security library for Python web applications, providing middleware for IP filtering, rate limiting, and other security features with both synchronous and asynchronous support.

For detailed installation instructions and configuration options, see Installation Guide.

Key Features

  • IP Whitelisting and Blacklisting: Control access based on IP addresses
  • User Agent Filtering: Block requests from specific user agents
  • Rate Limiting: Limit the number of requests from a single IP
    • Per-Route Rate Limiting: Set different rate limits for different endpoints
    • Bulk Configuration: Configure rate limits for multiple routes at once
    • Pattern Matching: Use wildcards to apply rate limits to groups of routes
  • Automatic IP Banning: Automatically ban IPs after a certain number of suspicious requests
  • Penetration Attempt Detection: Detect and log potential penetration attempts
  • Custom Logging: Log security events to a custom file
  • CORS Configuration: Configure CORS settings for your web application
  • IP Geolocation: Determine the country of an IP address
  • Flexible Storage: Redis-enabled distributed storage, nosql, sql or in-memory storage
  • Async/Sync Support: Works with both synchronous (Flask) and asynchronous (FastAPI) frameworks
  • Logging Backends: Configurable logging backends with current support for Meilisearch

Usage

Installation

PyWebGuard can be installed with various optional dependencies depending on your needs:

Basic Installation

pip install pywebguard

Storage Backends

pip install pywebguard[redis]

pip install pywebguard[sqlite]

pip install pywebguard[tinydb]

pip install pywebguard[mongodb]

pip install pywebguard[postgresql]

Framework Support

pip install pywebguard[flask]

pip install pywebguard[fastapi]

Search Engine Support

pip install pywebguard[meilisearch]

pip install pywebguard[elasticsearch]

Development Dependencies

pip install pywebguard[test]

pip install pywebguard[format]

Full Installation

To install all optional dependencies:

pip install pywebguard[all]

Quick Start

The short way, with a few flat options (FastAPI shown; FlaskGuard.install(app, ...) takes the same ones):

from fastapi import FastAPI
from pywebguard import FastAPIGuard

app = FastAPI()

FastAPIGuard.install(
    app,
    rate_limit="100/minute",
    route_limits={"/api/limited": "5/minute", "/api/admin/**": "20/minute"},
    blocked_agents=["curl", "wget", "bot"],
    ip_blacklist=["10.0.0.1", "172.16.0.0/16"],
)

Only rate limiting is on by default; the other features turn on when you pass their option. Without storage, state lives in memory and is per-process, so use Redis or another shared storage with multiple workers. See the FastAPI and Flask guides for every option.

Full configuration

For full control, build a GuardConfig and add the middleware yourself. Here is an example using FastAPI:

from fastapi import FastAPI
from pywebguard import FastAPIGuard, GuardConfig
from pywebguard.storage.memory import AsyncMemoryStorage

app = FastAPI(
    title="PyWebGuard FastAPI Example",
    description="A comprehensive example of PyWebGuard integration with FastAPI",
    version="1.0.0",
)
config = GuardConfig(
    ip_filter={
        "enabled": True,
        "whitelist": ["127.0.0.1", "::1", "192.168.1.0/24"],
        "blacklist": ["10.0.0.1", "172.16.0.0/16"],
    },
    rate_limit={
        "enabled": True,
        "requests_per_minute": 100,
        "burst_size": 20,
        "auto_ban_threshold": 200,
        "auto_ban_duration_minutes": 60,  # 1 hour
        "excluded_paths": ["/ready", "/healthz"]
    },
    user_agent={
        "enabled": True,
        "blocked_agents": ["curl", "wget", "Scrapy", "bot", "Bot"],
        "excluded_paths": ["/ready", "/healthz"]
    },
    cors={
        "enabled": True,
        "allow_origins": ["http://localhost:3000", "https://example.com"],
        "allow_methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
        "allow_headers": ["Content-Type", "Authorization"],
        "allow_credentials": True,
        "max_age": 3600,
    },
    penetration={
        "enabled": True,
        "detect_sql_injection": True,
        "detect_xss": True,
        "detect_path_traversal": True,
        "block_suspicious_requests": True,
    },
    logging={
        "enabled": True,
        "level": "DEBUG",  # Change to DEBUG to see all messages
        "log_blocked_requests": True,
        "stream": True,
        "stream_levels": ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
        "meilisearch": {
            "url": "https://meilisearch.dev.ktechhub.com",
            "api_key": os.getenv("MEILISEARCH_API_KEY"),
            "index_name": "pywebguard",
        },
    },
)

route_rate_limits = [
    {
        "endpoint": "/api/limited",
        "requests_per_minute": 5,
        "burst_size": 2,
        "auto_ban_threshold": 10,
        "auto_ban_duration_minutes": 30,
    },
    {
        "endpoint": "/api/uploads/*",
        "requests_per_minute": 10,
        "burst_size": 5,
        "auto_ban_duration_minutes": 30,
    },
    {
        "endpoint": "/api/admin/**",
        "requests_per_minute": 20,
        "burst_size": 5,
        "auto_ban_threshold": 50,
        "auto_ban_duration_minutes": 120,  # 2 hours
    },
]

storage = AsyncMemoryStorage()

app.add_middleware(
    FastAPIGuard,
    config=config,
    storage=storage,
    route_rate_limits=route_rate_limits,
)

@app.get("/", tags=["main"])
async def root():
    """Root endpoint with default rate limit (100 req/min)"""
    return {"message": "Hello World - Default rate limit (100 req/min)"}


@app.get("/api/limited", tags=["main"])
async def limited_endpoint():
    """Strictly rate limited endpoint (5 req/min)"""
    return {"message": "This endpoint is strictly rate limited (5 req/min)"}

For more detailed examples, check the examples folder.

Documentation

Full docs: py-daily.github.io/pywebguard

Contributors

Mumuni Mohammed
Mumuni Mohammed

📆
Hussein Baba Fuseini
Hussein Baba Fuseini

📖
Isaac kumi
Isaac kumi

💻

Contribution

We welcome contributions from the community! Whether it's bug reports, feature requests, or code contributions, every contribution helps make PyWebGuard better.

Please read our Contribution Guidelines before submitting any changes. This document provides detailed information about:

  • How to set up your development environment
  • Our coding standards and style guide
  • The process for submitting pull requests
  • How to report bugs and request features
  • Our commit message conventions
  • Testing requirements

Join our community and help make PyWebGuard even better! 🚀

License

This project is licensed under the MIT License.

Metadata

Release files for pywebguard 1.0.43

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pywebguard 1.0.43
File Size Uploaded Provenance Actions
pywebguard-1.0.43.tar.gz 78.2 kB Without provenance Details for pywebguard-1.0.43.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pywebguard 1.0.43
File Interpreter ABI Platform Actions
pywebguard-1.0.43-py3-none-any.whl Python 3 none any Details for pywebguard-1.0.43-py3-none-any.whl

Total release size: 145.6 kB

Release files / pywebguard-1.0.43.tar.gz

Download URL pywebguard-1.0.43.tar.gz
Size 78.2 kB
Tags Source
SHA-256 checksum
How to use checksums
e8d3671be0734f553d4d9788501c1e5d8116da4e79701761b8b878089d9a2168
BLAKE2b-256 checksum
How to use checksums
38dbe1f4714ef35fc581874f741cfc6259aac8a5271e6fc948b692b116515e0e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.17

Release files / pywebguard-1.0.43-py3-none-any.whl

Download URL pywebguard-1.0.43-py3-none-any.whl
Size 67.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
03e1345b3f9d929d88e0c9e858c3b9f7413f8e7fb4f9f5a6e822f13d2b1306d3
BLAKE2b-256 checksum
How to use checksums
57c17d300901399e5e4a6f51c7b8c8590b8917824b34d2858edaf2f61c467a7d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.17

Security for pywebguard 1.0.43

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.43 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page