Skip to main content

A comprehensive security library for Python web applications

Project description

Table of Contents generated with DocToc

PyWebGuard

PyPI version Python Versions License All Contributors 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

Here's a basic 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": 3600,  # 1 hour in seconds
        "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": 1800,  # 30 minutes
    },
    {
        "endpoint": "/api/uploads/*",
        "requests_per_minute": 10,
        "burst_size": 5,
        "auto_ban_duration": 1800,
    },
    {
        "endpoint": "/api/admin/**",
        "requests_per_minute": 20,
        "burst_size": 5,
        "auto_ban_threshold": 50,
        "auto_ban_duration": 7200,  # 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

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.

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

pywebguard-1.0.20.tar.gz (49.1 kB view details)

Uploaded Source

Built Distribution

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

pywebguard-1.0.20-py3-none-any.whl (62.9 kB view details)

Uploaded Python 3

File details

Details for the file pywebguard-1.0.20.tar.gz.

File metadata

  • Download URL: pywebguard-1.0.20.tar.gz
  • Upload date:
  • Size: 49.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.18

File hashes

Hashes for pywebguard-1.0.20.tar.gz
Algorithm Hash digest
SHA256 d24a1e29c462fef5d8ae5e32fa39e1e49325b2c39ca45ab0c0f11ffa5d08ab94
MD5 a5e34d1458db824684279cf78b00a01a
BLAKE2b-256 300f2617eadc39342817c0184e0752b0374870d7fd6dc0ed82fbd8fe07c418d6

See more details on using hashes here.

File details

Details for the file pywebguard-1.0.20-py3-none-any.whl.

File metadata

  • Download URL: pywebguard-1.0.20-py3-none-any.whl
  • Upload date:
  • Size: 62.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.18

File hashes

Hashes for pywebguard-1.0.20-py3-none-any.whl
Algorithm Hash digest
SHA256 570cfd73c346cc3fd3a03c62079a3ed2832800a57f4abd12107606ac57200bb3
MD5 6860fdaf0ff80e4e242013e486098316
BLAKE2b-256 302c104c8417c38a54840d96cf0156402fa9b01a98657e695014a5ca5f3a66b1

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