{"id":50529427,"url":"https://github.com/rennf93/flaskapi-guard","last_synced_at":"2026-06-03T11:31:06.632Z","repository":{"id":344144965,"uuid":"1179400005","full_name":"rennf93/flaskapi-guard","owner":"rennf93","description":"A security library for Flask that provides an extension to control IPs, log requests, and detect penetration attempts. It integrates seamlessly with Flask to offer robust protection against various security threats.","archived":false,"fork":false,"pushed_at":"2026-05-28T00:21:14.000Z","size":5487,"stargazers_count":12,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"master","last_synced_at":"2026-05-28T02:19:10.040Z","etag":null,"topics":["api","extension","flask","ip","python","rest","security"],"latest_commit_sha":null,"homepage":"https://rennf93.github.io/flaskapi-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,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":"rennf93","tidelift":"pypi/flaskapi-guard","custom":["https://paypal.me/renzof93"]}},"created_at":"2026-03-12T01:47:59.000Z","updated_at":"2026-05-28T00:20:23.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/rennf93/flaskapi-guard","commit_stats":null,"previous_names":["rennf93/flaskapi-guard"],"tags_count":11,"template":false,"template_full_name":null,"purl":"pkg:github/rennf93/flaskapi-guard","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rennf93%2Fflaskapi-guard","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rennf93%2Fflaskapi-guard/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rennf93%2Fflaskapi-guard/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rennf93%2Fflaskapi-guard/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rennf93","download_url":"https://codeload.github.com/rennf93/flaskapi-guard/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rennf93%2Fflaskapi-guard/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33863265,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-03T02:00:06.370Z","response_time":59,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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","extension","flask","ip","python","rest","security"],"created_at":"2026-06-03T11:31:05.583Z","updated_at":"2026-06-03T11:31:06.624Z","avatar_url":"https://github.com/rennf93.png","language":"Python","funding_links":["https://github.com/sponsors/rennf93","https://tidelift.com/funding/github/pypi/flaskapi-guard","https://paypal.me/renzof93"],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://rennf93.github.io/flaskapi-guard/latest/\"\u003e\n        \u003cimg src=\"https://rennf93.github.io/flaskapi-guard/latest/assets/flaskapi_guard_legend.svg\" alt=\"FlaskAPI Guard\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\n---\n\n\u003cp align=\"center\"\u003e\n    \u003cstrong\u003eflaskapi-guard is a security library for Flask that provides an extension to control IPs, log requests, detect penetration attempts and more. It integrates seamlessly with Flask to offer robust protection against various security threats. Powered by \u003ca href=\"https://github.com/rennf93/guard-core\"\u003eguard-core\u003c/a\u003e.\u003c/strong\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://badge.fury.io/py/flaskapi-guard\"\u003e\n        \u003cimg src=\"https://badge.fury.io/py/flaskapi-guard.svg?cache=none\u0026icon=si%3Apython\u0026icon_color=%23008cb4\" alt=\"PyPiVersion\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/rennf93/flaskapi-guard/actions/workflows/release.yml\"\u003e\n        \u003cimg src=\"https://github.com/rennf93/flaskapi-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/flaskapi-guard/actions/workflows/ci.yml\"\u003e\n        \u003cimg src=\"https://github.com/rennf93/flaskapi-guard/actions/workflows/ci.yml/badge.svg\" alt=\"CI\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://github.com/rennf93/flaskapi-guard/actions/workflows/code-ql.yml\"\u003e\n        \u003cimg src=\"https://github.com/rennf93/flaskapi-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/flaskapi-guard/actions/workflows/pages/pages-build-deployment\"\u003e\n        \u003cimg src=\"https://github.com/rennf93/flaskapi-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/flaskapi-guard/actions/workflows/docs.yml\"\u003e\n        \u003cimg src=\"https://github.com/rennf93/flaskapi-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/flaskapi-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/Flask-000000.svg?style=flat\u0026amp;logo=Flask\u0026amp;logoColor=white\" alt=\"Flask\"\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/flaskapi-guard\"\u003e\n        \u003cimg src=\"https://pepy.tech/badge/flaskapi-guard\" alt=\"Downloads\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://guard-core.com\"\u003eWebsite\u003c/a\u003e \u0026middot;\n    \u003ca href=\"https://rennf93.github.io/flaskapi-guard/latest/\"\u003eDocs\u003c/a\u003e \u0026middot;\n    \u003ca href=\"https://playground.guard-core.com\"\u003ePlayground\u003c/a\u003e \u0026middot;\n    \u003ca href=\"https://app.guard-core.com\"\u003eDashboard\u003c/a\u003e \u0026middot;\n    \u003ca href=\"https://discord.gg/ZW7ZJbjMkK\"\u003eDiscord\u003c/a\u003e\n\u003c/p\u003e\n\n---\n\n# Documentation\n\n📚 **[Documentation](https://rennf93.github.io/flaskapi-guard)** - Full technical documentation and deep dive into its inner workings.\n\n___\n\n## Ecosystem\n\nFlaskAPI Guard is the Flask adapter for the Guard security ecosystem. Powered by `guard-core` and compatible with the shared telemetry agent. Parallel implementations exist for TypeScript (on npm) and Rust (on crates.io).\n\n### Python\n\n| Package | Role | PyPI |\n|---|---|---|\n| [guard-core](https://github.com/rennf93/guard-core) | Framework-agnostic security engine | [![PyPI](https://img.shields.io/pypi/v/guard-core)](https://pypi.org/project/guard-core/) |\n| [guard-agent](https://github.com/rennf93/guard-agent) | Telemetry agent | [![PyPI](https://img.shields.io/pypi/v/guard-agent)](https://pypi.org/project/guard-agent/) |\n| [fastapi-guard](https://github.com/rennf93/fastapi-guard) | FastAPI / Starlette adapter | [![PyPI](https://img.shields.io/pypi/v/fastapi-guard)](https://pypi.org/project/fastapi-guard/) |\n| [flaskapi-guard](https://github.com/rennf93/flaskapi-guard) | Flask adapter (this package) | [![PyPI](https://img.shields.io/pypi/v/flaskapi-guard)](https://pypi.org/project/flaskapi-guard/) |\n| [djapi-guard](https://github.com/rennf93/djapi-guard) | Django adapter | [![PyPI](https://img.shields.io/pypi/v/djapi-guard)](https://pypi.org/project/djapi-guard/) |\n| [tornadoapi-guard](https://github.com/rennf93/tornadoapi-guard) | Tornado adapter | [![PyPI](https://img.shields.io/pypi/v/tornadoapi-guard)](https://pypi.org/project/tornadoapi-guard/) |\n\n### TypeScript / JavaScript\n\nPublished under the [`@guardcore`](https://www.npmjs.com/org/guardcore) npm scope. Source in the [guard-core-ts](https://github.com/rennf93/guard-core-ts) monorepo. **Production-ready.**\n\n| Package | Role | npm |\n|---|---|---|\n| [@guardcore/core](https://github.com/rennf93/guard-core-ts/tree/master/packages/core) | Core engine | [![npm](https://img.shields.io/npm/v/%40guardcore%2Fcore)](https://www.npmjs.com/package/@guardcore/core) |\n| [@guardcore/express](https://github.com/rennf93/guard-core-ts/tree/master/packages/express) | Express adapter | [![npm](https://img.shields.io/npm/v/%40guardcore%2Fexpress)](https://www.npmjs.com/package/@guardcore/express) |\n| [@guardcore/nestjs](https://github.com/rennf93/guard-core-ts/tree/master/packages/nestjs) | NestJS adapter | [![npm](https://img.shields.io/npm/v/%40guardcore%2Fnestjs)](https://www.npmjs.com/package/@guardcore/nestjs) |\n| [@guardcore/fastify](https://github.com/rennf93/guard-core-ts/tree/master/packages/fastify) | Fastify adapter | [![npm](https://img.shields.io/npm/v/%40guardcore%2Ffastify)](https://www.npmjs.com/package/@guardcore/fastify) |\n| [@guardcore/hono](https://github.com/rennf93/guard-core-ts/tree/master/packages/hono) | Hono adapter | [![npm](https://img.shields.io/npm/v/%40guardcore%2Fhono)](https://www.npmjs.com/package/@guardcore/hono) |\n\n### Rust\n\nPublished on crates.io. **🚧 Placeholder crates — implementation in progress.**\n\n| Package | Role | crates.io |\n|---|---|---|\n| [guard-core](https://github.com/rennf93/guard-core-rs) | Core engine | [![crates.io](https://img.shields.io/crates/v/guard-core)](https://crates.io/crates/guard-core) |\n| [actix-guard-rs](https://github.com/rennf93/actix-guard-rs) | Actix adapter | [![crates.io](https://img.shields.io/crates/v/actix-guard-rs)](https://crates.io/crates/actix-guard-rs) |\n| [axum-guard-rs](https://github.com/rennf93/axum-guard-rs) | Axum adapter | [![crates.io](https://img.shields.io/crates/v/axum-guard-rs)](https://crates.io/crates/axum-guard-rs) |\n| [rocket-guard-rs](https://github.com/rennf93/rocket-guard-rs) | Rocket adapter | [![crates.io](https://img.shields.io/crates/v/rocket-guard-rs)](https://crates.io/crates/rocket-guard-rs) |\n| [tower-guard-rs](https://github.com/rennf93/tower-guard-rs) | Tower adapter | [![crates.io](https://img.shields.io/crates/v/tower-guard-rs)](https://crates.io/crates/tower-guard-rs) |\n\n___\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- **HTTP Security Headers**: Comprehensive security headers management (CSP, HSTS, X-Frame-Options, etc.)\n- **Custom Logging**: Log security events to a custom file.\n- **CORS Configuration**: Configure CORS settings for your Flask application.\n- **Cloud Provider IP Blocking**: Block requests from cloud provider IPs (AWS, GCP, Azure).\n- **IP Geolocation**: Use a service like 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- **Route-Level Security Decorators**: Fine-grained security controls per route.\n- **Behavioral Analysis**: Endpoint usage tracking and anomaly detection.\n- **Time-Based Access Control**: Restrict endpoint access to specific time windows.\n- **Emergency Mode**: Block all traffic except whitelisted IPs.\n\n___\n\n## Migration to v4.0.0\n\nflaskapi-guard 4.0.0 tracks the `guard-core \u003e= 3.0.0` major bump. There is one\nupstream behavior change plus two additive surfaces.\n\n### Fail-secure by default (upstream)\n\n`SecurityConfig.fail_secure` now defaults to `True`. When any security check\nraises an unhandled exception, the request is now blocked with HTTP 500 instead\nof logging and falling through. Bugs in checks that previously slipped past as\nsilent fail-open responses now surface immediately.\n\nRecommended migration: keep the new default, surface check exceptions in your\nmonitoring, and fix them. To temporarily restore the old behavior on\ndeployments that depend on it:\n\n```python\nfrom flaskapi_guard import FlaskAPIGuard, SecurityConfig\n\nconfig = SecurityConfig(fail_secure=False)\nFlaskAPIGuard(app, config=config)\n```\n\n### Monitoring agent buffer health\n\nWhen `enable_agent=True`, the `FlaskAPIGuard` extension exposes an `agent_stats`\nproperty that returns the current buffer drop counters and transport\ncircuit-breaker state without needing to reach into the agent directly. Wire it\nto a Flask health endpoint:\n\n```python\nfrom flask import Flask, jsonify\nfrom flaskapi_guard import FlaskAPIGuard, SecurityConfig\n\napp = Flask(__name__)\nguard = FlaskAPIGuard(app, config=SecurityConfig(enable_agent=True))\n\n@app.route(\"/health/guard\")\ndef guard_health() -\u003e tuple[dict, int]:\n    return jsonify(guard.agent_stats), 200\n```\n\nWhen the agent is disabled or failed to initialize, the property returns\n`{\"enabled\": False}`. Read it on each scrape — it reflects live counters and is\nnot cached. The same instance is also reachable via\n`app.extensions[\"flaskapi_guard\"][\"guard\"].agent_stats`.\n\n### Reporting the adapter version to the agent\n\n`from flaskapi_guard import __version__` is now exported via\n`importlib.metadata`. Pair it with `guard-core \u003e= 3.0.0`'s\n`SecurityConfig.agent_guard_version` so the agent attributes telemetry to the\nflaskapi-guard release running in production:\n\n```python\nfrom flaskapi_guard import FlaskAPIGuard, SecurityConfig, __version__\n\nconfig = SecurityConfig(\n    enable_agent=True,\n    agent_guard_version=__version__,\n)\nFlaskAPIGuard(app, config=config)\n```\n\n___\n\n## Installation\n\nTo install `flaskapi-guard`, use pip:\n\n```bash\npip install flaskapi-guard\n```\n\n___\n\n## Usage\n\n## Basic Setup\n\nTo use `flaskapi-guard`, you need to configure the extension in your Flask application. Here's a basic example:\n\n```python\nfrom flask import Flask\nfrom flaskapi_guard import FlaskAPIGuard, SecurityConfig\nfrom flaskapi_guard import IPInfoManager\n\napp = Flask(__name__)\n\nconfig = SecurityConfig(\n    geo_ip_handler=IPInfoManager(\"your_ipinfo_token_here\"),\n    whitelist=[\"192.168.1.1\", \"2001:db8::1\"],\n    blacklist=[\"10.0.0.1\", \"2001:db8::2\"],\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 extension\nFlaskAPIGuard(app, config=config)\n\n@app.route(\"/\")\ndef read_root():\n    return {\"message\": \"Hello, World!\"}\n```\n\nYou can also use the **app factory pattern**:\n\n```python\nfrom flask import Flask\nfrom flaskapi_guard import FlaskAPIGuard, SecurityConfig\n\nguard = FlaskAPIGuard()\n\ndef create_app():\n    app = Flask(__name__)\n    config = SecurityConfig(\n        rate_limit=100,\n        enable_cors=True,\n    )\n    guard.init_app(app, config=config)\n    return app\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\", \"2001:db8::1\"],\n    blacklist=[\"10.0.0.1\", \"2001:db8::2\"],\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\nEnable penetration attempt detection using the `enable_penetration_detection` option.\n\n```python\nconfig = SecurityConfig(\n    enable_penetration_detection=True,  # True by default\n)\n```\n\nOptional: Enable `passive mode` to log suspicious activity without blocking requests.\n\n```python\nconfig = SecurityConfig(\n    passive_mode=True,  # False by default\n)\n```\n\n## Custom Penetration Detection\n\nDetect and log potential penetration attempts using the `detect_penetration_attempt` function.\n\n```python\nfrom flask import request, jsonify\nfrom flaskapi_guard.utils import detect_penetration_attempt\n\n@app.route(\"/submit\", methods=[\"POST\"])\ndef submit_data():\n    is_suspicious, trigger_info = detect_penetration_attempt(request)\n    if is_suspicious:\n        return jsonify(\n            {\"error\": f\"Suspicious activity detected: {trigger_info}\"}\n        ), 400\n    return jsonify({\"message\": \"Data submitted successfully\"})\n```\n\n## Custom Logging\n\nLog security events with console output (always enabled) and optional file logging:\n\n```python\nconfig = SecurityConfig(\n    custom_log_file=\"security.log\",  # Optional: adds file logging\n    # custom_log_file=None,  # Default: console output only\n)\n```\n\n**Note:** Console output is always enabled for visibility. File logging is only activated when `custom_log_file` is provided.\n\n## HTTP Security Headers\n\nConfigure comprehensive security headers following OWASP best practices:\n\n```python\nconfig = SecurityConfig(\n    security_headers={\n        \"enabled\": True,\n        \"hsts\": {\n            \"max_age\": 31536000,  # 1 year\n            \"include_subdomains\": True,\n            \"preload\": False\n        },\n        \"csp\": {\n            \"default-src\": [\"'self'\"],\n            \"script-src\": [\"'self'\", \"https://trusted.cdn.com\"],\n            \"style-src\": [\"'self'\", \"'unsafe-inline'\"],\n            \"img-src\": [\"'self'\", \"data:\", \"https:\"],\n            \"connect-src\": [\"'self'\", \"https://api.example.com\"],\n            \"frame-ancestors\": [\"'none'\"],\n            \"base-uri\": [\"'self'\"],\n            \"form-action\": [\"'self'\"]\n        },\n        \"frame_options\": \"DENY\",\n        \"content_type_options\": \"nosniff\",\n        \"xss_protection\": \"1; mode=block\",\n        \"referrer_policy\": \"strict-origin-when-cross-origin\",\n        \"permissions_policy\": \"geolocation=(), microphone=(), camera=()\",\n        \"custom\": {\n            \"X-Custom-Header\": \"CustomValue\"\n        }\n    }\n)\n```\n\nKey security headers supported:\n\n- **Content Security Policy (CSP)**: Prevent XSS attacks by controlling resource loading\n- **HTTP Strict Transport Security (HSTS)**: Force HTTPS connections\n- **X-Frame-Options**: Prevent clickjacking attacks\n- **X-Content-Type-Options**: Prevent MIME type sniffing\n- **X-XSS-Protection**: Enable browser XSS filtering\n- **Referrer-Policy**: Control referrer information\n- **Permissions-Policy**: Restrict browser features\n- **Cross-Origin Policies**: Control cross-origin resource access and embedding\n- **Header Injection Prevention**: Automatic validation against injection attacks\n- **CORS Security**: Secure wildcard and credentials handling\n\n## CORS Configuration\n\nConfigure CORS settings for your Flask 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\nIf you want to use `flaskapi-guard`'s built-in country filtering features, 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\nNote: This is only required if you use country filtering (`blocked_countries`, `whitelist_countries`). You can also provide your own handler that uses any other service.\n\n___\n\n## Route-Level Security with Decorators\n\nFlaskAPI Guard provides powerful decorators that allow you to apply security controls to individual routes, giving you fine-grained control over your API endpoints.\n\n### Basic Decorator Usage\n\n```python\nfrom flask import Flask\nfrom flaskapi_guard import FlaskAPIGuard, SecurityConfig, SecurityDecorator\n\napp = Flask(__name__)\nconfig = SecurityConfig()\n\n# Create decorator instance\nguard_deco = SecurityDecorator(config)\n\n# Initialize extension and connect decorator handler\nguard = FlaskAPIGuard(app, config=config)\nguard.set_decorator_handler(guard_deco)\n\n# Apply decorators to specific routes\n@app.route(\"/api/public\")\ndef public_endpoint():\n    return {\"data\": \"public\"}\n\n@app.route(\"/api/limited\")\n@guard_deco.rate_limit(requests=10, window=300)  # 10 requests per 5 minutes\ndef limited_endpoint():\n    return {\"data\": \"limited\"}\n\n@app.route(\"/api/restricted\")\n@guard_deco.require_ip(whitelist=[\"192.168.1.0/24\"])\n@guard_deco.block_countries([\"CN\", \"RU\"])\ndef restricted_endpoint():\n    return {\"data\": \"restricted\"}\n```\n\n### Available Decorators\n\nAccess Control\n\n- `@guard_deco.require_ip(whitelist=[], blacklist=[])` - IP address filtering\n- `@guard_deco.block_countries([\"CN\", \"RU\"])` - Block specific countries\n- `@guard_deco.allow_countries([\"US\", \"CA\"])` - Allow only specific countries\n- `@guard_deco.block_clouds([\"AWS\", \"GCP\"])` - Block cloud provider IPs\n\nRate Limiting\n\n- `@guard_deco.rate_limit(requests=10, window=60)` - Basic rate limiting\n- `@guard_deco.geo_rate_limit(limits={\"US\": 100, \"default\": 50})` - Geographic rate limiting\n\nAuthentication \u0026 Headers\n\n- `@guard_deco.require_https()` - Force HTTPS\n- `@guard_deco.require_auth(type=\"bearer\")` - Require authentication\n- `@guard_deco.api_key_auth(header_name=\"X-API-Key\")` - API key authentication\n- `@guard_deco.require_headers({\"X-Custom\": \"required\"})` - Require specific headers\n\nContent Filtering\n\n- `@guard_deco.block_user_agents([\"curl\", \"wget\"])` - Block user agent patterns\n- `@guard_deco.content_type_filter([\"application/json\"])` - Filter content types\n- `@guard_deco.max_request_size(1048576)` - Limit request size (1MB)\n- `@guard_deco.require_referrer([\"myapp.com\"])` - Require specific referrers\n\nBehavioral Analysis\n\n- `@guard_deco.usage_monitor(max_calls=50, window=3600, action=\"ban\")` - Monitor endpoint usage\n- `@guard_deco.return_monitor(\"rare_item\", max_occurrences=3, window=86400, action=\"alert\")` - Monitor return patterns\n- `@guard_deco.suspicious_frequency(max_frequency=0.1, window=300, action=\"log\")` - Detect suspicious frequency\n\nAdvanced Controls\n\n- `@guard_deco.time_window(\"09:00\", \"17:00\", \"UTC\")` - Time-based access control\n- `@guard_deco.honeypot_detection(trap_fields=[\"hidden_field\"])` - Detect bots using honeypot fields\n- `@guard_deco.bypass(checks=[\"rate_limit\"])` - Bypass specific security checks\n\n### Complex Route Protection\n\nCombine multiple decorators for comprehensive protection:\n\n```python\n@app.route(\"/api/admin/sensitive\", methods=[\"POST\"])\n@guard_deco.require_https()                        # Security requirement\n@guard_deco.require_auth(type=\"bearer\")            # Authentication\n@guard_deco.require_ip(whitelist=[\"10.0.0.0/8\"])   # Access control\n@guard_deco.rate_limit(requests=5, window=3600)    # Rate limiting\n@guard_deco.suspicious_detection(enabled=True)     # Monitoring\ndef admin_endpoint():\n    return {\"status\": \"admin action\"}\n\n@app.route(\"/api/rewards\")\n@guard_deco.usage_monitor(max_calls=50, window=3600, action=\"ban\")\n@guard_deco.return_monitor(\"rare_item\", max_occurrences=3, window=86400, action=\"ban\")\n@guard_deco.block_countries([\"CN\", \"RU\", \"KP\"])\ndef rewards_endpoint():\n    # This endpoint is protected against:\n    # - Excessive usage (\u003e50 calls/hour results in ban)\n    # - Suspicious return patterns (\u003e3 rare items/day results in ban)\n    # - Geographic restrictions\n    return {\"reward\": \"rare_item\", \"value\": 1000}\n```\n\n### Decorator Configuration Priority\n\nSecurity settings are applied in the following priority order:\n\n1. Decorator Settings (highest priority)\n2. Global Extension Settings\n3. Default Settings (lowest priority)\n\nThis allows routes to override global settings while maintaining sensible defaults.\n\n___\n\n## Advanced Usage\n\n### Secure Proxy Configuration\n\nConfigure trusted proxies to securely handle X-Forwarded-For headers:\n\n```python\nconfig = SecurityConfig(\n    trusted_proxies=[\"10.0.0.1\", \"192.168.1.0/24\"],  # List of trusted proxy IPs or CIDR ranges\n    trusted_proxy_depth=1,                           # How many proxies to expect in chain\n    trust_x_forwarded_proto=True,                    # Whether to trust X-Forwarded-Proto for HTTPS detection (default: True)\n)\n```\n\nWhen `trusted_proxies` is configured, FlaskAPI Guard will:\n\n1. Only trust X-Forwarded-For headers from these IPs\n2. Extract the appropriate client IP based on proxy depth\n3. Prevent IP spoofing attacks through header manipulation\n\n### Custom Geolocation Handler\n\nThe library implements a handler that 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 feature with this handler:\n\n```python\nfrom flaskapi_guard import IPInfoManager\n\nconfig = SecurityConfig(\n    geo_ip_handler=IPInfoManager(\"your_ipinfo_token_here\"),\n    blocked_countries=[\"AR\", \"IT\"],\n    whitelist_countries=[\"US\", \"CA\"],\n)\n```\n\nThe database is automatically downloaded and cached locally when the extension starts, if required, and it's updated daily to ensure accuracy.\n\nYou can also use a service other than IPInfo, as long as you implement the same protocol:\n\n```python\nclass CustomGeoIPHandler:\n    @property\n    def is_initialized(self) -\u003e bool:\n        ...\n\n    def initialize(self) -\u003e None:\n        ...\n\n    def initialize_redis(self, redis_handler: \"RedisManager\") -\u003e None:\n        ...\n\n    def get_country(self, ip: str) -\u003e str | None:\n        ...\n\n\nconfig = SecurityConfig(\n    geo_ip_handler=CustomGeoIPHandler(),\n    blocked_countries=[\"AR\", \"IT\"],\n    whitelist_countries=[\"US\", \"CA\"],\n)\n```\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 flask import Response\nfrom typing import Optional\n\ndef custom_check(req) -\u003e Optional[Response]:\n    if \"X-Custom-Header\" not in req.headers:\n        return Response(\"Missing custom header\", status=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 flask import Response, jsonify\n\ndef custom_modifier(response: Response) -\u003e Response:\n    # Add custom headers\n    response.headers[\"X-Custom-Header\"] = \"CustomValue\"\n\n    # Convert text responses to JSON responses\n    if response.status_code \u003e= 400 and response.content_type != \"application/json\":\n        try:\n            content = response.get_data(as_text=True)\n            json_response = jsonify({\"detail\": content})\n            json_response.status_code = response.status_code\n            return json_response\n        except Exception:\n            pass\n\n    return response\n\nconfig = SecurityConfig(\n    custom_response_modifier=custom_modifier,\n)\n```\n\nThe example above shows how to:\n\n1. Add custom headers to all responses\n2. Convert plain text error responses to JSON format with a \"detail\" field\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\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___\n\n## Emergency Mode\n\nBlock all incoming traffic except from explicitly whitelisted IPs. Useful during active attacks or maintenance windows:\n\n```python\nconfig = SecurityConfig(\n    emergency_mode=True,\n    emergency_whitelist=[\"10.0.0.1\", \"192.168.1.0/24\"],\n)\n```\n\n___\n\n## Behavioral Analysis\n\nFlaskAPI Guard includes a behavioral analysis engine for detecting anomalous usage patterns. This works both at the global level and per-route via decorators:\n\n```python\nfrom flaskapi_guard import SecurityConfig, BehaviorRule\n\nconfig = SecurityConfig(\n    # Global behavioral rules can be defined in config\n)\n\n# Per-route behavioral monitoring via decorators\n@app.route(\"/api/rewards\")\n@guard_deco.usage_monitor(max_calls=50, window=3600, action=\"ban\")\n@guard_deco.return_monitor(\"rare_item\", max_occurrences=3, window=86400, action=\"ban\")\ndef rewards_endpoint():\n    return {\"reward\": \"rare_item\", \"value\": 1000}\n```\n\nBehavioral actions include:\n\n- `\"log\"` - Log the anomaly\n- `\"alert\"` - Generate an alert event\n- `\"ban\"` - Automatically ban the offending IP\n\n___\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- **geo_ip_handler**: ```GeoIPHandler``` - Protocol that allows for IP geolocation functionality.\n- **enable_redis**: ```bool``` - Enable Redis for distributed state (default: True). When disabled, uses in-memory storage.\n- **redis_url**: ```str | None``` - Redis connection URL (default: \"redis://localhost:6379\").\n- **redis_prefix**: ```str``` - Prefix for Redis keys (default: \"flaskapi_guard:\").\n- **trusted_proxies**: ```list[str] | None``` - List of trusted proxy IPs or CIDR ranges.\n- **trusted_proxy_depth**: ```int``` - How many proxies to expect in chain.\n- **trust_x_forwarded_proto**: ```bool``` - Whether to trust X-Forwarded-Proto for HTTPS detection.\n- **whitelist**: ```list[str] | None``` - 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**: ```str | None``` - Optional path to a log file. When provided, enables file logging in addition to console output (which is always enabled). Default: `None` (console only).\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- **rate_limit_window**: ```int``` - The time window in seconds for rate limiting (default: 60).\n- **enforce_https**: ```bool``` - Whether to enforce HTTPS connections. If True, all HTTP requests will be redirected to HTTPS.\n- **custom_request_check**: ```Callable[[Request], Response | None] | None``` - A custom synchronous function to perform additional checks on the request. If it returns a Response, that response will be sent instead of continuing the extension chain.\n- **custom_response_modifier**: ```Callable[[Response], Response] | None``` - A custom synchronous 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**: ```set[str]``` - Case-sensitive cloud provider names to block. Valid values: 'AWS', 'GCP', 'Azure'. Invalid entries are silently ignored.\n- **passive_mode**: ```bool``` - When enabled, logs suspicious activity without blocking requests (default: False).\n- **enable_ip_banning**: ```bool``` - Enable or disable IP banning functionality (default: True).\n- **enable_rate_limiting**: ```bool``` - Enable or disable rate limiting (default: True).\n- **enable_penetration_detection**: ```bool``` - Enable or disable penetration attempt detection (default: True).\n- **emergency_mode**: ```bool``` - Block all traffic except whitelisted IPs (default: False).\n- **emergency_whitelist**: ```list[str]``` - IPs allowed during emergency mode.\n- **exclude_paths**: ```list[str]``` - Paths excluded from security checks (default: [\"/docs\", \"/redoc\", \"/openapi.json\", \"/openapi.yaml\", \"/favicon.ico\", \"/static\"]).\n- **security_headers**: ```dict[str, Any] | None``` - Security headers configuration following OWASP best practices.\n- **endpoint_rate_limits**: ```dict[str, tuple[int, int]]``` - Per-endpoint rate limits as {endpoint: (limit, window)}.\n- **log_suspicious_level**: ```Literal[\"INFO\",\"DEBUG\",\"WARNING\",\"ERROR\",\"CRITICAL\"] | None``` - Log level for suspicious activity (default: \"WARNING\").\n- **log_request_level**: ```Literal[\"INFO\",\"DEBUG\",\"WARNING\",\"ERROR\",\"CRITICAL\"] | None``` - Log level for request logging (default: None).\n\n___\n\n## Detection Engine\n\nFlaskAPI Guard includes a comprehensive detection engine for identifying penetration attempts. It uses pattern matching, semantic analysis, and anomaly detection to catch a wide range of attack vectors.\n\n### Attack Categories Detected\n\n| Category | Examples |\n|----------|----------|\n| **XSS** | Script tags, event handlers, JavaScript protocol, cookie manipulation |\n| **SQL Injection** | UNION queries, logic-based (OR/AND), time-based (SLEEP/BENCHMARK), file ops |\n| **Command Injection** | Shell commands, command substitution/chaining, PHP functions |\n| **Path Traversal** | `../` sequences, `/etc/passwd`, `/proc/self/environ`, Windows system files |\n| **File Inclusion** | `php://`, `data://`, `file://`, `zip://`, `expect://` protocols |\n| **LDAP Injection** | Wildcard patterns, attribute matching, logic ops |\n| **XML Injection** | XXE, CDATA sections, XML declarations |\n| **SSRF** | localhost, `127.0.0.1`, `169.254.*`, private ranges |\n| **Code Injection** | Python `eval`/`exec`/`__import__`, obfuscation, high-entropy payloads |\n\n### Detection Configuration\n\n| Config Field | Default | Range | Purpose |\n|-------------|---------|-------|---------|\n| `detection_compiler_timeout` | `2.0` | 0.1-10.0 | Pattern compilation timeout (seconds) |\n| `detection_max_content_length` | `10000` | 1000-100000 | Max content length to analyze |\n| `detection_preserve_attack_patterns` | `True` | - | Preserve attack signatures during preprocessing |\n| `detection_semantic_threshold` | `0.7` | 0.0-1.0 | Semantic analysis confidence threshold |\n| `detection_anomaly_threshold` | `3.0` | 1.0-10.0 | Anomaly detection threshold (std devs) |\n| `detection_slow_pattern_threshold` | `0.1` | 0.01-1.0 | Slow pattern detection threshold (seconds) |\n| `detection_monitor_history_size` | `1000` | 100-10000 | Performance monitor history size |\n| `detection_max_tracked_patterns` | `1000` | 100-5000 | Max tracked patterns |\n\n___\n\n## Key Differences from FastAPI Guard\n\nFlaskAPI Guard is a direct port of [FastAPI Guard](https://github.com/rennf93/fastapi-guard) to the Flask/WSGI ecosystem. The security logic is identical, but adapted for Flask's synchronous model:\n\n| Aspect | FastAPI Guard | FlaskAPI Guard |\n|--------|--------------|----------------|\n| **Entry point** | `SecurityMiddleware` (ASGI middleware) | `FlaskAPIGuard` (Flask extension) |\n| **Hook mechanism** | ASGI `dispatch(request, call_next)` | `before_request` / `after_request` |\n| **Execution model** | `async`/`await` throughout | Fully synchronous |\n| **Server model** | ASGI (uvicorn) | WSGI (gunicorn, waitress) |\n| **Package name** | `guard` | `flaskapi_guard` |\n| **Request state** | `request.state` | `flask.g` |\n| **Redis client** | `redis.asyncio.Redis` | `redis.Redis` (sync) |\n| **HTTP client** | `httpx.AsyncClient` | `httpx.Client` (sync) |\n| **Request object** | `starlette.requests.Request` | `flask.request` (Werkzeug) |\n| **Response object** | `starlette.responses.Response` | `flask.Response` (Werkzeug) |\n| **IP extraction** | `request.client.host` | `request.remote_addr` / `request.access_route` |\n| **Custom callables** | `async def check(request) -\u003e Response \\| None` | `def check(request) -\u003e Response \\| None` |\n\n___\n\n## Contributing\n\nContributions are welcome! Please open an issue or submit a pull request on GitHub.\n\n___\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.\n\n___\n\n## Author\n\nRenzo Franceschini - [rennf93@users.noreply.github.com](mailto:rennf93@users.noreply.github.com) .\n\n___\n\n## Acknowledgements\n\n- [Flask](https://flask.palletsprojects.com/)\n- [Werkzeug](https://werkzeug.palletsprojects.com/)\n- [FastAPI Guard](https://github.com/rennf93/fastapi-guard)\n- [IPInfo](https://ipinfo.io/)\n- [cachetools](https://cachetools.readthedocs.io/)\n- [Redis](https://redis.io/)\n- [gunicorn](https://gunicorn.org/)\n- [Pydantic](https://docs.pydantic.dev/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frennf93%2Fflaskapi-guard","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frennf93%2Fflaskapi-guard","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frennf93%2Fflaskapi-guard/lists"}