{"id":20458992,"url":"https://github.com/rennf93/fastapi-guard","last_synced_at":"2025-05-16T12:12:53.147Z","repository":{"id":251890168,"uuid":"838357935","full_name":"rennf93/fastapi-guard","owner":"rennf93","description":"A security library for FastAPI that provides middleware to control IPs, log requests, and detect penetration attempts. It integrates seamlessly with FastAPI to offer robust protection against various security threats.","archived":false,"fork":false,"pushed_at":"2025-05-07T20:07:46.000Z","size":42898,"stargazers_count":208,"open_issues_count":2,"forks_count":4,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-05-07T21:24:30.236Z","etag":null,"topics":["api","fastapi","ip","middleware","python","rest","security"],"latest_commit_sha":null,"homepage":"https://rennf93.github.io/fastapi-guard/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rennf93.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"rennf93","tidelift":"pypi/fastapi-guard","custom":["https://paypal.me/renzof93"]}},"created_at":"2024-08-05T13:29:12.000Z","updated_at":"2025-05-06T19:50:25.000Z","dependencies_parsed_at":"2024-12-14T02:24:24.799Z","dependency_job_id":"adb618c2-bd58-4144-9655-46188000326a","html_url":"https://github.com/rennf93/fastapi-guard","commit_stats":null,"previous_names":["rennf93/fastapi-guard"],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rennf93%2Ffastapi-guard","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rennf93%2Ffastapi-guard/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rennf93%2Ffastapi-guard/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rennf93%2Ffastapi-guard/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rennf93","download_url":"https://codeload.github.com/rennf93/fastapi-guard/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254527099,"owners_count":22085919,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","fastapi","ip","middleware","python","rest","security"],"created_at":"2024-11-15T12:14:39.600Z","updated_at":"2025-05-16T12:12:48.137Z","avatar_url":"https://github.com/rennf93.png","language":"Python","readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://rennf93.github.io/fastapi-guard/latest/\"\u003e\n        \u003cimg src=\"https://rennf93.github.io/fastapi-guard/latest/assets/big_logo.svg\" alt=\"FastAPI Guard\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\n---\n\n\u003cp align=\"center\"\u003e\n    \u003cstrong\u003efastapi-guard is a security library for FastAPI that provides middleware to control IPs, log requests, detect penetration attempts and more. It integrates seamlessly with FastAPI to offer robust protection against various security threats.\u003c/strong\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://badge.fury.io/py/fastapi-guard\"\u003e\n        \u003cimg src=\"https://badge.fury.io/py/fastapi-guard.svg?cache=none\u0026icon=si%3Apython\u0026icon_color=%23008cb4\" alt=\"PyPiVersion\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/rennf93/fastapi-guard/actions/workflows/release.yml\"\u003e\n        \u003cimg src=\"https://github.com/rennf93/fastapi-guard/actions/workflows/release.yml/badge.svg\" alt=\"Release\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://opensource.org/licenses/MIT\"\u003e\n        \u003cimg src=\"https://img.shields.io/badge/License-MIT-yellow.svg\" alt=\"License\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/rennf93/fastapi-guard/actions/workflows/ci.yml\"\u003e\n        \u003cimg src=\"https://github.com/rennf93/fastapi-guard/actions/workflows/ci.yml/badge.svg\" alt=\"CI\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/rennf93/fastapi-guard/actions/workflows/code-ql.yml\"\u003e\n        \u003cimg src=\"https://github.com/rennf93/fastapi-guard/actions/workflows/code-ql.yml/badge.svg\" alt=\"CodeQL\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://github.com/rennf93/fastapi-guard/actions/workflows/pages/pages-build-deployment\"\u003e\n        \u003cimg src=\"https://github.com/rennf93/fastapi-guard/actions/workflows/pages/pages-build-deployment/badge.svg?branch=gh-pages\" alt=\"PagesBuildDeployment\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/rennf93/fastapi-guard/actions/workflows/docs.yml\"\u003e\n        \u003cimg src=\"https://github.com/rennf93/fastapi-guard/actions/workflows/docs.yml/badge.svg\" alt=\"DocsUpdate\"\u003e\n    \u003c/a\u003e\n    \u003cimg src=\"https://img.shields.io/github/last-commit/rennf93/fastapi-guard?style=flat\u0026amp;logo=git\u0026amp;logoColor=white\u0026amp;color=0080ff\" alt=\"last-commit\"\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003cimg src=\"https://img.shields.io/badge/Python-3776AB.svg?style=flat\u0026amp;logo=Python\u0026amp;logoColor=white\" alt=\"Python\"\u003e\n    \u003cimg src=\"https://img.shields.io/badge/FastAPI-009688.svg?style=flat\u0026amp;logo=FastAPI\u0026amp;logoColor=white\" alt=\"FastAPI\"\u003e\n    \u003cimg src=\"https://img.shields.io/badge/Redis-FF4438.svg?style=flat\u0026amp;logo=Redis\u0026amp;logoColor=white\" alt=\"Redis\"\u003e\n    \u003ca href=\"https://pepy.tech/project/fastapi-guard\"\u003e\n        \u003cimg src=\"https://pepy.tech/badge/fastapi-guard\" alt=\"Downloads\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\n---\n\n## Documentation\n\n📚 **[Documentation](https://rennf93.github.io/fastapi-guard)** - Full technical documentation and deep dive into its inner workings.\n\n## Prerequisites\n\nBefore using `fastapi-guard`, you'll need to obtain an IPInfo token:\n\n1. Visit [IPInfo's website](https://ipinfo.io/signup) to create a free account\n2. After signing up, you'll receive an API token\n3. The free tier includes:\n   - Up to 50,000 requests per month\n   - Access to IP to Country database\n   - Daily database updates\n   - IPv4 \u0026 IPv6 support\n\n## Features\n\n- **IP Whitelisting and Blacklisting**: Control access based on IP addresses.\n- **User Agent Filtering**: Block requests from specific user agents.\n- **Rate Limiting**: Limit the number of requests from a single IP.\n- **Automatic IP Banning**: Automatically ban IPs after a certain number of suspicious requests.\n- **Penetration Attempt Detection**: Detect and log potential penetration attempts.\n- **Custom Logging**: Log security events to a custom file.\n- **CORS Configuration**: Configure CORS settings for your FastAPI application.\n- **Cloud Provider IP Blocking**: Block requests from cloud provider IPs (AWS, GCP, Azure).\n- **IP Geolocation**: Use IPInfo.io API to determine the country of an IP address.\n- **Distributed State Management**: (Optional) Redis integration for shared security state across instances\n- **Flexible Storage**: Redis-enabled distributed storage or in-memory storage for single instance deployments\n\n## Installation\n\nTo install `fastapi-guard`, use pip:\n\n```\npip install fastapi-guard\n```\n\n## Usage\n\n### Basic Setup\n\nTo use `fastapi-guard`, you need to configure the middleware in your FastAPI application. Here's a basic example:\n\n```python\nfrom fastapi import FastAPI\nfrom guard.middleware import SecurityMiddleware\nfrom guard.models import SecurityConfig\n\napp = FastAPI()\n\n# Define your security configuration\nconfig = SecurityConfig(\n    ipinfo_token=\"your_ipinfo_token_here\",  # Required for IP geolocation\n    db_path=\"custom/ipinfo.db\",  # Optional custom database path\n    whitelist=[\"192.168.1.1\"],\n    blacklist=[\"10.0.0.1\"],\n    blocked_countries=[\"AR\", \"IT\"],\n    blocked_user_agents=[\"curl\", \"wget\"],\n    auto_ban_threshold=5,\n    auto_ban_duration=86400,\n    custom_log_file=\"security.log\",\n    rate_limit=100,\n    enforce_https=True,\n    enable_cors=True,\n    cors_allow_origins=[\"*\"],\n    cors_allow_methods=[\"GET\", \"POST\"],\n    cors_allow_headers=[\"*\"],\n    cors_allow_credentials=True,\n    cors_expose_headers=[\"X-Custom-Header\"],\n    cors_max_age=600,\n    block_cloud_providers={\"AWS\", \"GCP\", \"Azure\"},\n)\n\n# Add the security middleware\napp.add_middleware(SecurityMiddleware, config=config)\n\n@app.get(\"/\")\nasync def read_root():\n    return {\"message\": \"Hello, World!\"}\n```\n\n### IP Whitelisting and Blacklisting\n\nYou can control access based on IP addresses using the `whitelist` and `blacklist` options in the `SecurityConfig`.\n\n```python\nconfig = SecurityConfig(\n    whitelist=[\"192.168.1.1\"],\n    blacklist=[\"10.0.0.1\"],\n)\n```\n\n### User Agent Filtering\n\nBlock requests from specific user agents by adding patterns to the `blocked_user_agents` list.\n\n```python\nconfig = SecurityConfig(\n    blocked_user_agents=[\"curl\", \"wget\"],\n)\n```\n\n### Rate Limiting\n\nLimit the number of requests from a single IP using the `rate_limit` option.\n\n```python\nconfig = SecurityConfig(\n    rate_limit=100,  # Maximum 100 requests per minute\n)\n```\n\n### Automatic IP Banning\n\nAutomatically ban IPs after a certain number of suspicious requests using the `auto_ban_threshold` and `auto_ban_duration` options.\n\n```python\nconfig = SecurityConfig(\n    auto_ban_threshold=5,  # Ban IP after 5 suspicious requests\n    auto_ban_duration=86400,  # Ban duration in seconds (1 day)\n)\n```\n\n### Penetration Attempt Detection\n\nDetect and log potential penetration attempts using the `detect_penetration_attempt` function.\n\n```python\nfrom fastapi import Request\nfrom guard.utils import detect_penetration_attempt\n\n@app.post(\"/submit\")\nasync def submit_data(request: Request):\n    if await detect_penetration_attempt(request):\n        return {\"error\": \"Potential attack detected\"}\n    return {\"message\": \"Data submitted successfully\"}\n```\n\n### Custom Logging\n\nLog security events to a custom file using the `custom_log_file` option.\n\n```python\nconfig = SecurityConfig(\n    custom_log_file=\"security.log\",\n)\n```\n\n### CORS Configuration\n\nConfigure CORS settings for your FastAPI application using the `enable_cors` and related options.\n\n```python\nconfig = SecurityConfig(\n    enable_cors=True,\n    cors_allow_origins=[\"*\"],\n    cors_allow_methods=[\"GET\", \"POST\"],\n    cors_allow_headers=[\"*\"],\n    cors_allow_credentials=True,\n    cors_expose_headers=[\"X-Custom-Header\"],\n    cors_max_age=600,\n)\n```\n\n### Cloud Provider IP Blocking\n\nBlock requests from cloud provider IPs (AWS, GCP, Azure) using the `block_cloud_providers` option.\n\n```python\nconfig = SecurityConfig(\n    block_cloud_providers={\"AWS\", \"GCP\", \"Azure\"},\n)\n```\n\n### IP Geolocation and Country Blocking\n\nThe library uses IPInfo's [IP to Country database](https://ipinfo.io/products/free-ip-database) which provides:\n\n- Full accuracy IP to country mapping\n- Daily updates\n- Support for both IPv4 and IPv6\n- Country and continent information\n- ASN details\n\nTo use the geolocation features:\n\n```python\nconfig = SecurityConfig(\n    ipinfo_token=\"your_ipinfo_token_here\",\n    db_path=\"custom/ipinfo.db\",  # Optional custom database path\n    blocked_countries=[\"AR\", \"IT\"],  # Block specific countries using ISO 3166-1 alpha-2 codes\n    whitelist_countries=[\"US\", \"CA\"]  # Optional: Only allow specific countries\n)\n```\n\nThe database is automatically downloaded and cached locally when the middleware starts, and it's updated daily to ensure accuracy.\n\n## Advanced Usage\n\n### Custom Request Check\n\nYou can define a custom function to perform additional checks on the request using the `custom_request_check` option.\n\n```python\nfrom fastapi import Request, Response\n\nasync def custom_check(request: Request) -\u003e Optional[Response]:\n    if \"X-Custom-Header\" not in request.headers:\n        return Response(\"Missing custom header\", status_code=400)\n    return None\n\nconfig = SecurityConfig(\n    custom_request_check=custom_check,\n)\n```\n\n### Custom Response Modifier\n\nYou can define a custom function to modify the response before it's sent using the `custom_response_modifier` option.\n\n```python\nfrom fastapi import Response\n\nasync def custom_modifier(response: Response) -\u003e Response:\n    response.headers[\"X-Custom-Header\"] = \"CustomValue\"\n    return response\n\nconfig = SecurityConfig(\n    custom_response_modifier=custom_modifier,\n)\n```\n\n### Redis Configuration\n\nEnable distributed state management across multiple instances:\n\n```python\nconfig = SecurityConfig(\n    enable_redis=True,\n    redis_url=\"redis://prod-redis:6379/1\",\n    redis_prefix=\"myapp:security:\",\n)\n```\n\nThe Redis integration provides:\n- Atomic increment operations for rate limiting\n- Distributed IP ban tracking\n- Cloud provider IP range caching\n- Pattern storage for penetration detection\n\n## Detailed Configuration Options\n\n### SecurityConfig\n\nThe `SecurityConfig` class defines the structure for security configuration, including IP whitelists and blacklists, blocked countries, blocked user agents, rate limiting, automatic IP banning, HTTPS enforcement, custom hooks, CORS settings, and blocking of cloud provider IPs.\n\n#### Attributes\n\n- `ipinfo_token`: str - The IPInfo API token required for IP geolocation functionality.\n- `db_path`: Optional[str] - Custom path for IPInfo database storage (default: ./data/ipinfo/country_asn.mmdb)\n- `enable_redis`: bool - Enable Redis for distributed state (default: True). When disabled, uses in-memory storage\n- `redis_url`: Optional[str] - Redis connection URL (default: \"redis://localhost:6379\")\n- `redis_prefix`: str - Prefix for Redis keys (default: \"fastapi_guard:\")\n- `whitelist`: Optional[List[str]] - A list of IP addresses or ranges that are always allowed. If set to None, no whitelist is applied.\n- `blacklist`: List[str] - A list of IP addresses or ranges that are always blocked.\n- `blocked_countries`: List[str] - A list of country codes whose IP addresses should be blocked.\n- `blocked_user_agents`: List[str] - A list of user agent strings or patterns that should be blocked.\n- `auto_ban_threshold`: int - The threshold for auto-banning an IP address after a certain number of requests.\n- `auto_ban_duration`: int - The duration in seconds for which an IP address should be banned after reaching the auto-ban threshold.\n- `custom_log_file`: Optional[str] - The path to a custom log file for logging security events.\n- `custom_error_responses`: Dict[int, str] - A dictionary of custom error responses for specific HTTP status codes.\n- `rate_limit`: int - The maximum number of requests allowed per minute from a single IP.\n- `enforce_https`: bool - Whether to enforce HTTPS connections. If True, all HTTP requests will be redirected to HTTPS.\n- `custom_request_check`: Optional[Callable[[Request], Awaitable[Optional[Response]]]] - A custom function to perform additional checks on the request. If it returns a Response, that response will be sent instead of continuing the middleware chain.\n- `custom_response_modifier`: Optional[Callable[[Response], Awaitable[Response]]] - A custom function to modify the response before it's sent.\n- `enable_cors`: bool - Whether to enable CORS.\n- `cors_allow_origins`: List[str] - A list of origins that are allowed to access the API.\n- `cors_allow_methods`: List[str] - A list of methods that are allowed to access the API.\n- `cors_allow_headers`: List[str] - A list of headers that are allowed in CORS requests.\n- `cors_allow_credentials`: bool - Whether to allow credentials in CORS requests.\n- `cors_expose_headers`: List[str] - A list of headers that are exposed in CORS responses.\n- `cors_max_age`: int - The maximum age in seconds that the results of a preflight request can be cached.\n- `block_cloud_providers`: Optional[Set[str]] - Case-sensitive cloud provider names to block. Valid values: 'AWS', 'GCP', 'Azure'. Invalid entries are silently ignored.\n\n## Contributing\n\nContributions are welcome! Please open an issue or submit a pull request on GitHub.\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.\n\n## Author\n\nRenzo Franceschini - [rennf93@gmail.com](mailto:rennf93@gmail.com)\n\n## Acknowledgements\n\n- [FastAPI](https://fastapi.tiangolo.com/)\n- [IPInfo](https://ipinfo.io/)\n- [aiohttp](https://docs.aiohttp.org/)\n- [cachetools](https://cachetools.readthedocs.io/)\n- [requests](https://docs.python-requests.org/)\n- [Redis](https://redis.io/)\n- [uvicorn](https://www.uvicorn.org/)\n","funding_links":["https://github.com/sponsors/rennf93","https://tidelift.com/funding/github/pypi/fastapi-guard","https://paypal.me/renzof93"],"categories":["Python","Third-Party Extensions"],"sub_categories":["CyberSecurity"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frennf93%2Ffastapi-guard","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frennf93%2Ffastapi-guard","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frennf93%2Ffastapi-guard/lists"}