Skip to main content

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.

Metadata

Release files for pywebguard 1.0.30

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.30
File Size Uploaded
pywebguard-1.0.30.tar.gz 73.0 kB Details

Built distribution (wheel)

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

Total release size: 136.9 kB

Release files / pywebguard-1.0.30.tar.gz

Download URL pywebguard-1.0.30.tar.gz
Size 73.0 kB
Tags Source
SHA-256 checksum
How to use checksums
d4ea5a461a509d52fd01bc5ccd60ccc47fed98ea37a3eb2bb661ffeea80d3461
BLAKE2b-256 checksum
How to use checksums
93c7ee8abfddbd662b5735c63c99ae5ea0a7f787c8b2b2a03c21ed8e33a5002d
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.30-py3-none-any.whl

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

Release history Release notifications | RSS feed

1.0.42

2 release files

1.0.41

2 release files

1.0.40

2 release files

1.0.39

2 release files

1.0.38

2 release files

1.0.37

2 release files

1.0.36

2 release files

1.0.35

2 release files

1.0.34

2 release files

This release

1.0.30 This release

2 release files

1.0.27

2 release files

1.0.26

2 release files

1.0.25

2 release files

1.0.24

2 release files

1.0.23

2 release files

1.0.21

2 release files

1.0.20

2 release files

1.0.19

2 release files

1.0.18

2 release files

1.0.17

2 release files

1.0.16

2 release files

1.0.15

2 release files

1.0.14

2 release files

1.0.13

2 release files

1.0.12

2 release files

1.0.11

2 release files

1.0.9

2 release files

1.0.8

2 release files

1.0.7

2 release files

1.0.6

2 release files

1.0.5

2 release files

1.0.4

2 release files

1.0.3

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

0.0.1

2 release files

0.0.0

2 release files

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