pywebguard 1.0.2__tar.gz → 1.0.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. pywebguard-1.0.4/PKG-INFO +105 -0
  2. pywebguard-1.0.4/README.md +66 -0
  3. pywebguard-1.0.4/pywebguard.egg-info/PKG-INFO +105 -0
  4. pywebguard-1.0.2/PKG-INFO +0 -415
  5. pywebguard-1.0.2/README.md +0 -376
  6. pywebguard-1.0.2/pywebguard.egg-info/PKG-INFO +0 -415
  7. {pywebguard-1.0.2 → pywebguard-1.0.4}/LICENSE +0 -0
  8. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/__init__.py +0 -0
  9. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/cli.py +0 -0
  10. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/core/__init__.py +0 -0
  11. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/core/base.py +0 -0
  12. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/core/config.py +0 -0
  13. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/filters/__init__.py +0 -0
  14. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/filters/base.py +0 -0
  15. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/filters/ip_filter.py +0 -0
  16. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/filters/user_agent.py +0 -0
  17. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/frameworks/__init__.py +0 -0
  18. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/frameworks/_fastapi.py +0 -0
  19. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/frameworks/_flask.py +0 -0
  20. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/limiters/__init__.py +0 -0
  21. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/limiters/base.py +0 -0
  22. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/limiters/rate_limit.py +0 -0
  23. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/logging/__init__.py +0 -0
  24. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/logging/backends/__init__.py +0 -0
  25. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/logging/backends/_elasticsearch.py +0 -0
  26. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/logging/backends/_meilisearch.py +0 -0
  27. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/logging/backends/_mongodb.py +0 -0
  28. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/logging/base.py +0 -0
  29. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/logging/logger.py +0 -0
  30. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/security/__init__.py +0 -0
  31. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/security/base.py +0 -0
  32. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/security/cors.py +0 -0
  33. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/security/penetration.py +0 -0
  34. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/storage/__init__.py +0 -0
  35. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/storage/_mongodb.py +0 -0
  36. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/storage/_postgresql.py +0 -0
  37. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/storage/_redis.py +0 -0
  38. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/storage/_sqlite.py +0 -0
  39. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/storage/_tinydb.py +0 -0
  40. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/storage/base.py +0 -0
  41. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/storage/memory.py +0 -0
  42. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/utils/__init__.py +0 -0
  43. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/utils/ip.py +0 -0
  44. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard/utils/request.py +0 -0
  45. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard.egg-info/SOURCES.txt +0 -0
  46. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard.egg-info/dependency_links.txt +0 -0
  47. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard.egg-info/entry_points.txt +0 -0
  48. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard.egg-info/requires.txt +0 -0
  49. {pywebguard-1.0.2 → pywebguard-1.0.4}/pywebguard.egg-info/top_level.txt +0 -0
  50. {pywebguard-1.0.2 → pywebguard-1.0.4}/setup.cfg +0 -0
  51. {pywebguard-1.0.2 → pywebguard-1.0.4}/setup.py +0 -0
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.1
2
+ Name: pywebguard
3
+ Version: 1.0.4
4
+ Summary: A comprehensive security library for Python web applications
5
+ Home-page: https://github.com/py-daily/pywebguard
6
+ Author: py-daily
7
+ Author-email: mm@ktechhub.com
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Topic :: Security
21
+ Classifier: Topic :: Internet :: WWW/HTTP
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Requires-Python: >=3.8
24
+ Description-Content-Type: text/markdown
25
+ Provides-Extra: fastapi
26
+ Provides-Extra: flask
27
+ Provides-Extra: redis
28
+ Provides-Extra: sqlite
29
+ Provides-Extra: tinydb
30
+ Provides-Extra: mongodb
31
+ Provides-Extra: postgresql
32
+ Provides-Extra: elasticsearch
33
+ Provides-Extra: all-storage
34
+ Provides-Extra: all-frameworks
35
+ Provides-Extra: all
36
+ Provides-Extra: dev
37
+ License-File: LICENSE
38
+
39
+
40
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
41
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
42
+ **Table of Contents** *generated with [DocToc](https://github.com/ktechhub/doctoc)*
43
+
44
+ <!---toc start-->
45
+
46
+ * [PyWebGuard](#pywebguard)
47
+ * [Key Features](#key-features)
48
+ * [Quick Start](#quick-start)
49
+ * [Documentation](#documentation)
50
+ * [Contributors](#contributors)
51
+ * [License](#license)
52
+
53
+ <!---toc end-->
54
+
55
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
56
+ # PyWebGuard
57
+ [![PyPI version](https://badge.fury.io/py/pywebguard.svg)](https://badge.fury.io/py/pywebguard)
58
+ [![Python Versions](https://img.shields.io/pypi/pyversions/pywebguard.svg)](https://pypi.org/project/pywebguard/)
59
+ [![License](https://img.shields.io/github/license/py-daily/pywebguard.svg)](https://github.com/py-daily/pywebguard/blob/main/LICENSE)
60
+
61
+ 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.
62
+
63
+ For detailed installation instructions and configuration options, see [Installation Guide](docs/installation.md).
64
+
65
+ ## Key Features
66
+
67
+ - **IP Whitelisting and Blacklisting**: Control access based on IP addresses
68
+ - **User Agent Filtering**: Block requests from specific user agents
69
+ - **Rate Limiting**: Limit the number of requests from a single IP
70
+ - **Per-Route Rate Limiting**: Set different rate limits for different endpoints
71
+ - **Bulk Configuration**: Configure rate limits for multiple routes at once
72
+ - **Pattern Matching**: Use wildcards to apply rate limits to groups of routes
73
+ - **Automatic IP Banning**: Automatically ban IPs after a certain number of suspicious requests
74
+ - **Penetration Attempt Detection**: Detect and log potential penetration attempts
75
+ - **Custom Logging**: Log security events to a custom file
76
+ - **CORS Configuration**: Configure CORS settings for your web application
77
+ - **IP Geolocation**: Determine the country of an IP address
78
+ - **Flexible Storage**: Redis-enabled distributed storage, nosql, sql or in-memory storage
79
+ - **Async/Sync Support**: Works with both synchronous (Flask) and asynchronous (FastAPI) frameworks
80
+ - **Logging Backends**: Configurable logging backends with current support for Meilisearch
81
+
82
+
83
+
84
+ ## Quick Start
85
+ Check the `examples` folder.
86
+
87
+
88
+ ## Documentation
89
+ - [Installation Guide](docs/installation.md)
90
+ - [CLI Usage](docs/cli.md)
91
+ - [Core Features](docs/core/)
92
+ - [Framework Integration](docs/frameworks/)
93
+ - [Storage Backends](docs/storage/)
94
+
95
+ ## Contributors
96
+
97
+ <a href="https://github.com/py-daily/pywebguard/graphs/contributors">
98
+ <img src="https://contrib.rocks/image?repo=py-daily/pywebguard" width="80" />
99
+ </a>
100
+
101
+
102
+ ## License
103
+
104
+ This project is licensed under the [MIT License](LICENSE).
105
+
@@ -0,0 +1,66 @@
1
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
2
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
3
+ **Table of Contents** *generated with [DocToc](https://github.com/ktechhub/doctoc)*
4
+
5
+ <!---toc start-->
6
+
7
+ * [PyWebGuard](#pywebguard)
8
+ * [Key Features](#key-features)
9
+ * [Quick Start](#quick-start)
10
+ * [Documentation](#documentation)
11
+ * [Contributors](#contributors)
12
+ * [License](#license)
13
+
14
+ <!---toc end-->
15
+
16
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
17
+ # PyWebGuard
18
+ [![PyPI version](https://badge.fury.io/py/pywebguard.svg)](https://badge.fury.io/py/pywebguard)
19
+ [![Python Versions](https://img.shields.io/pypi/pyversions/pywebguard.svg)](https://pypi.org/project/pywebguard/)
20
+ [![License](https://img.shields.io/github/license/py-daily/pywebguard.svg)](https://github.com/py-daily/pywebguard/blob/main/LICENSE)
21
+
22
+ 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.
23
+
24
+ For detailed installation instructions and configuration options, see [Installation Guide](docs/installation.md).
25
+
26
+ ## Key Features
27
+
28
+ - **IP Whitelisting and Blacklisting**: Control access based on IP addresses
29
+ - **User Agent Filtering**: Block requests from specific user agents
30
+ - **Rate Limiting**: Limit the number of requests from a single IP
31
+ - **Per-Route Rate Limiting**: Set different rate limits for different endpoints
32
+ - **Bulk Configuration**: Configure rate limits for multiple routes at once
33
+ - **Pattern Matching**: Use wildcards to apply rate limits to groups of routes
34
+ - **Automatic IP Banning**: Automatically ban IPs after a certain number of suspicious requests
35
+ - **Penetration Attempt Detection**: Detect and log potential penetration attempts
36
+ - **Custom Logging**: Log security events to a custom file
37
+ - **CORS Configuration**: Configure CORS settings for your web application
38
+ - **IP Geolocation**: Determine the country of an IP address
39
+ - **Flexible Storage**: Redis-enabled distributed storage, nosql, sql or in-memory storage
40
+ - **Async/Sync Support**: Works with both synchronous (Flask) and asynchronous (FastAPI) frameworks
41
+ - **Logging Backends**: Configurable logging backends with current support for Meilisearch
42
+
43
+
44
+
45
+ ## Quick Start
46
+ Check the `examples` folder.
47
+
48
+
49
+ ## Documentation
50
+ - [Installation Guide](docs/installation.md)
51
+ - [CLI Usage](docs/cli.md)
52
+ - [Core Features](docs/core/)
53
+ - [Framework Integration](docs/frameworks/)
54
+ - [Storage Backends](docs/storage/)
55
+
56
+ ## Contributors
57
+
58
+ <a href="https://github.com/py-daily/pywebguard/graphs/contributors">
59
+ <img src="https://contrib.rocks/image?repo=py-daily/pywebguard" width="80" />
60
+ </a>
61
+
62
+
63
+ ## License
64
+
65
+ This project is licensed under the [MIT License](LICENSE).
66
+
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.1
2
+ Name: pywebguard
3
+ Version: 1.0.4
4
+ Summary: A comprehensive security library for Python web applications
5
+ Home-page: https://github.com/py-daily/pywebguard
6
+ Author: py-daily
7
+ Author-email: mm@ktechhub.com
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Topic :: Security
21
+ Classifier: Topic :: Internet :: WWW/HTTP
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Requires-Python: >=3.8
24
+ Description-Content-Type: text/markdown
25
+ Provides-Extra: fastapi
26
+ Provides-Extra: flask
27
+ Provides-Extra: redis
28
+ Provides-Extra: sqlite
29
+ Provides-Extra: tinydb
30
+ Provides-Extra: mongodb
31
+ Provides-Extra: postgresql
32
+ Provides-Extra: elasticsearch
33
+ Provides-Extra: all-storage
34
+ Provides-Extra: all-frameworks
35
+ Provides-Extra: all
36
+ Provides-Extra: dev
37
+ License-File: LICENSE
38
+
39
+
40
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
41
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
42
+ **Table of Contents** *generated with [DocToc](https://github.com/ktechhub/doctoc)*
43
+
44
+ <!---toc start-->
45
+
46
+ * [PyWebGuard](#pywebguard)
47
+ * [Key Features](#key-features)
48
+ * [Quick Start](#quick-start)
49
+ * [Documentation](#documentation)
50
+ * [Contributors](#contributors)
51
+ * [License](#license)
52
+
53
+ <!---toc end-->
54
+
55
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
56
+ # PyWebGuard
57
+ [![PyPI version](https://badge.fury.io/py/pywebguard.svg)](https://badge.fury.io/py/pywebguard)
58
+ [![Python Versions](https://img.shields.io/pypi/pyversions/pywebguard.svg)](https://pypi.org/project/pywebguard/)
59
+ [![License](https://img.shields.io/github/license/py-daily/pywebguard.svg)](https://github.com/py-daily/pywebguard/blob/main/LICENSE)
60
+
61
+ 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.
62
+
63
+ For detailed installation instructions and configuration options, see [Installation Guide](docs/installation.md).
64
+
65
+ ## Key Features
66
+
67
+ - **IP Whitelisting and Blacklisting**: Control access based on IP addresses
68
+ - **User Agent Filtering**: Block requests from specific user agents
69
+ - **Rate Limiting**: Limit the number of requests from a single IP
70
+ - **Per-Route Rate Limiting**: Set different rate limits for different endpoints
71
+ - **Bulk Configuration**: Configure rate limits for multiple routes at once
72
+ - **Pattern Matching**: Use wildcards to apply rate limits to groups of routes
73
+ - **Automatic IP Banning**: Automatically ban IPs after a certain number of suspicious requests
74
+ - **Penetration Attempt Detection**: Detect and log potential penetration attempts
75
+ - **Custom Logging**: Log security events to a custom file
76
+ - **CORS Configuration**: Configure CORS settings for your web application
77
+ - **IP Geolocation**: Determine the country of an IP address
78
+ - **Flexible Storage**: Redis-enabled distributed storage, nosql, sql or in-memory storage
79
+ - **Async/Sync Support**: Works with both synchronous (Flask) and asynchronous (FastAPI) frameworks
80
+ - **Logging Backends**: Configurable logging backends with current support for Meilisearch
81
+
82
+
83
+
84
+ ## Quick Start
85
+ Check the `examples` folder.
86
+
87
+
88
+ ## Documentation
89
+ - [Installation Guide](docs/installation.md)
90
+ - [CLI Usage](docs/cli.md)
91
+ - [Core Features](docs/core/)
92
+ - [Framework Integration](docs/frameworks/)
93
+ - [Storage Backends](docs/storage/)
94
+
95
+ ## Contributors
96
+
97
+ <a href="https://github.com/py-daily/pywebguard/graphs/contributors">
98
+ <img src="https://contrib.rocks/image?repo=py-daily/pywebguard" width="80" />
99
+ </a>
100
+
101
+
102
+ ## License
103
+
104
+ This project is licensed under the [MIT License](LICENSE).
105
+
pywebguard-1.0.2/PKG-INFO DELETED
@@ -1,415 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: pywebguard
3
- Version: 1.0.2
4
- Summary: A comprehensive security library for Python web applications
5
- Home-page: https://github.com/py-daily/pywebguard
6
- Author: py-daily
7
- Author-email: mm@ktechhub.com
8
- Classifier: Development Status :: 3 - Alpha
9
- Classifier: Intended Audience :: Developers
10
- Classifier: License :: OSI Approved :: MIT License
11
- Classifier: Operating System :: OS Independent
12
- Classifier: Programming Language :: Python :: 3.14
13
- Classifier: Programming Language :: Python :: 3.13
14
- Classifier: Programming Language :: Python :: 3.12
15
- Classifier: Programming Language :: Python :: 3.11
16
- Classifier: Programming Language :: Python :: 3.10
17
- Classifier: Programming Language :: Python :: 3.9
18
- Classifier: Programming Language :: Python :: 3.8
19
- Classifier: Programming Language :: Python :: 3
20
- Classifier: Topic :: Security
21
- Classifier: Topic :: Internet :: WWW/HTTP
22
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
- Requires-Python: >=3.8
24
- Description-Content-Type: text/markdown
25
- Provides-Extra: fastapi
26
- Provides-Extra: flask
27
- Provides-Extra: redis
28
- Provides-Extra: sqlite
29
- Provides-Extra: tinydb
30
- Provides-Extra: mongodb
31
- Provides-Extra: postgresql
32
- Provides-Extra: elasticsearch
33
- Provides-Extra: all-storage
34
- Provides-Extra: all-frameworks
35
- Provides-Extra: all
36
- Provides-Extra: dev
37
- License-File: LICENSE
38
-
39
-
40
- <!-- START doctoc generated TOC please keep comment here to allow auto update -->
41
- <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
42
- **Table of Contents** *generated with [DocToc](https://github.com/ktechhub/doctoc)*
43
-
44
- <!---toc start-->
45
-
46
- * [PyWebGuard](#pywebguard)
47
- * [Key Features](#key-features)
48
- * [Quick Start](#quick-start)
49
- * [Define route-specific rate limits](#define-route-specific-rate-limits)
50
- * [Initialize storage (async in-memory for this example)](#initialize-storage-async-in-memory-for-this-example)
51
- * [Uncomment to use Redis storage instead or import any of the storage supports](#uncomment-to-use-redis-storage-instead-or-import-any-of-the-storage-supports)
52
- * [storage = AsyncRedisStorage(url="redis://localhost:6379")](#storage--asyncredisstorageurlredislocalhost6379)
53
- * [Add PyWebGuard middleware](#add-pywebguard-middleware)
54
- * [Example of a path that might trigger penetration detection](#example-of-a-path-that-might-trigger-penetration-detection)
55
- * [Helper endpoint to check remaining rate limits](#helper-endpoint-to-check-remaining-rate-limits)
56
- * [Endpoint to check if an IP is banned](#endpoint-to-check-if-an-ip-is-banned)
57
- * [Admin endpoint to get metrics](#admin-endpoint-to-get-metrics)
58
- * [Admin endpoint to ban an IP](#admin-endpoint-to-ban-an-ip)
59
- * [Admin endpoint to unban an IP](#admin-endpoint-to-unban-an-ip)
60
- * [Documentation](#documentation)
61
- * [Contributors](#contributors)
62
- * [License](#license)
63
-
64
- <!---toc end-->
65
-
66
- <!-- END doctoc generated TOC please keep comment here to allow auto update -->
67
- # PyWebGuard
68
- [![PyPI version](https://badge.fury.io/py/pywebguard.svg)](https://badge.fury.io/py/pywebguard)
69
- [![Python Versions](https://img.shields.io/pypi/pyversions/pywebguard.svg)](https://pypi.org/project/pywebguard/)
70
- [![License](https://img.shields.io/github/license/py-daily/pywebguard.svg)](https://github.com/py-daily/pywebguard/blob/main/LICENSE)
71
-
72
- 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.
73
-
74
- For detailed installation instructions and configuration options, see [Installation Guide](docs/installation.md).
75
-
76
- ## Key Features
77
-
78
- - **IP Whitelisting and Blacklisting**: Control access based on IP addresses
79
- - **User Agent Filtering**: Block requests from specific user agents
80
- - **Rate Limiting**: Limit the number of requests from a single IP
81
- - **Per-Route Rate Limiting**: Set different rate limits for different endpoints
82
- - **Bulk Configuration**: Configure rate limits for multiple routes at once
83
- - **Pattern Matching**: Use wildcards to apply rate limits to groups of routes
84
- - **Automatic IP Banning**: Automatically ban IPs after a certain number of suspicious requests
85
- - **Penetration Attempt Detection**: Detect and log potential penetration attempts
86
- - **Custom Logging**: Log security events to a custom file
87
- - **CORS Configuration**: Configure CORS settings for your web application
88
- - **IP Geolocation**: Determine the country of an IP address
89
- - **Flexible Storage**: Redis-enabled distributed storage, nosql, sql or in-memory storage
90
- - **Async/Sync Support**: Works with both synchronous (Flask) and asynchronous (FastAPI) frameworks
91
- - **Logging Backends**: Configurable logging backends with current support for Meilisearch
92
-
93
-
94
-
95
- ## Quick Start
96
-
97
- ```python
98
- from fastapi import FastAPI
99
- from pywebguard import FastAPIGuard, GuardConfig, RateLimitConfig
100
- from pywebguard.storage.memory import AsyncMemoryStorage
101
- from pywebguard.core.config import LoggingConfig
102
-
103
- config = GuardConfig(
104
- # IP filtering configuration
105
- ip_filter={
106
- "enabled": True,
107
- "whitelist": ["127.0.0.1", "::1", "192.168.1.0/24"],
108
- "blacklist": ["10.0.0.1", "172.16.0.0/16"],
109
- },
110
- # Global rate limiting configuration
111
- rate_limit={
112
- "enabled": True,
113
- "requests_per_minute": 100,
114
- "burst_size": 20,
115
- "auto_ban_threshold": 200,
116
- "auto_ban_duration": 3600, # 1 hour in seconds
117
- },
118
- # User agent filtering
119
- user_agent={
120
- "enabled": True,
121
- "blocked_agents": ["curl", "wget", "Scrapy", "bot", "Bot"],
122
- },
123
- # CORS configuration
124
- cors={
125
- "enabled": True,
126
- "allow_origins": ["http://localhost:3000", "https://example.com"],
127
- "allow_methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
128
- "allow_headers": ["Content-Type", "Authorization"],
129
- "allow_credentials": True,
130
- "max_age": 3600,
131
- },
132
- # Penetration detection
133
- penetration={
134
- "enabled": True,
135
- "detect_sql_injection": True,
136
- "detect_xss": True,
137
- "detect_path_traversal": True,
138
- "block_suspicious_requests": True,
139
- },
140
- # Logging configuration
141
- logging={
142
- "enabled": True,
143
- "level": "DEBUG", # Change to DEBUG to see all messages
144
- "log_blocked_requests": True,
145
- "stream": True,
146
- "stream_levels": ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
147
- "meilisearch": {
148
- "url": "https://meilisearch.dev.pydaily.com",
149
- "api_key": os.getenv("MEILISEARCH_API_KEY"),
150
- "index_name": "pywebguard",
151
- },
152
- },
153
- )
154
- # Define route-specific rate limits
155
- route_rate_limits = [
156
- {
157
- "endpoint": "/api/limited",
158
- "requests_per_minute": 5,
159
- "burst_size": 2,
160
- "auto_ban_threshold": 10,
161
- "auto_ban_duration": 1800, # 30 minutes
162
- },
163
- {
164
- "endpoint": "/api/uploads/*",
165
- "requests_per_minute": 10,
166
- "burst_size": 5,
167
- "auto_ban_duration": 1800,
168
- },
169
- {
170
- "endpoint": "/api/admin/**",
171
- "requests_per_minute": 20,
172
- "burst_size": 5,
173
- "auto_ban_threshold": 50,
174
- "auto_ban_duration": 7200, # 2 hours
175
- },
176
- ]
177
-
178
-
179
- # Initialize storage (async in-memory for this example)
180
- storage = AsyncMemoryStorage()
181
-
182
- # Uncomment to use Redis storage instead or import any of the storage supports
183
- # storage = AsyncRedisStorage(url="redis://localhost:6379")
184
-
185
-
186
- # Add PyWebGuard middleware
187
- app.add_middleware(
188
- FastAPIGuard,
189
- config=config,
190
- storage=storage,
191
- route_rate_limits=route_rate_limits,
192
- )
193
-
194
- Basic routes
195
- @app.get("/", tags=["main"])
196
- async def root():
197
- """Root endpoint with default rate limit (100 req/min)"""
198
- return {"message": "Hello World - Default rate limit (100 req/min)"}
199
-
200
-
201
- @app.get("/api/limited", tags=["main"])
202
- async def limited_endpoint():
203
- """Strictly rate limited endpoint (5 req/min)"""
204
- return {"message": "This endpoint is strictly rate limited (5 req/min)"}
205
-
206
-
207
- @app.get("/api/uploads/files", tags=["main"])
208
- async def upload_files():
209
- """File upload endpoint with custom rate limit (10 req/min)"""
210
- return {"message": "File upload endpoint with custom rate limit (10 req/min)"}
211
-
212
-
213
- @app.get("/api/admin/dashboard", tags=["main"])
214
- async def admin_dashboard():
215
- """Admin dashboard with custom rate limit (20 req/min)"""
216
- return {"message": "Admin dashboard with custom rate limit (20 req/min)"}
217
-
218
-
219
- @app.get("/api/admin/users/list", tags=["main"])
220
- async def admin_users():
221
- """Admin users list with custom rate limit (20 req/min)"""
222
- return {"message": "Admin users list with custom rate limit (20 req/min)"}
223
-
224
-
225
- @app.get("/protected", tags=["main"])
226
- async def protected(request: Request):
227
- """Protected endpoint with default rate limit"""
228
- return {
229
- "message": "This is a protected endpoint with default rate limit",
230
- "client_ip": request.client.host,
231
- "user_agent": request.headers.get("user-agent", "Unknown"),
232
- }
233
-
234
-
235
- # Example of a path that might trigger penetration detection
236
- @app.get("/search", tags=["main"])
237
- async def search(q: str):
238
- """
239
- Search endpoint that might trigger penetration detection if malicious queries are used
240
-
241
- Args:
242
- q: Search query
243
-
244
- Returns:
245
- Search results
246
- """
247
- # PyWebGuard will check for SQL injection, XSS, etc. in the query parameter
248
- return {"results": f"Search results for: {q}"}
249
-
250
-
251
- # Helper endpoint to check remaining rate limits
252
- @app.get("/rate-limit-status", tags=["helper"])
253
- async def rate_limit_status(request: Request, path: str = "/"):
254
- """
255
- Check rate limit status for a specific path
256
-
257
- Args:
258
- request: The FastAPI request object
259
- path: The path to check rate limits for (default: /)
260
-
261
- Returns:
262
- Rate limit information for the specified path
263
- """
264
- client_ip = request.client.host
265
-
266
- # Get rate limit info for the specified path
267
- guard = request.app.state.guard
268
- rate_info = await guard.guard.rate_limiter.check_limit(client_ip, path)
269
-
270
- return {
271
- "path": path,
272
- "allowed": rate_info["allowed"],
273
- "remaining": rate_info["remaining"],
274
- "reset": rate_info["reset"],
275
- "client_ip": client_ip,
276
- }
277
-
278
-
279
- # Endpoint to check if an IP is banned
280
- @app.get("/check-ban-status", tags=["helper"])
281
- async def check_ban_status(request: Request, ip: Optional[str] = None):
282
- """
283
- Check if an IP is banned
284
-
285
- Args:
286
- request: The FastAPI request object
287
- ip: The IP to check (default: client IP)
288
-
289
- Returns:
290
- Ban status information
291
- """
292
- check_ip = ip or request.client.host
293
- guard = request.app.state.guard
294
- is_banned = await guard.guard.is_ip_banned(check_ip)
295
-
296
- return {
297
- "ip": check_ip,
298
- "is_banned": is_banned,
299
- "timestamp": time.time(),
300
- }
301
-
302
-
303
- # Admin endpoint to get metrics
304
- @app.get("/admin/metrics", tags=["admin"])
305
- async def get_metrics(request: Request):
306
- """
307
- Get PyWebGuard metrics
308
-
309
- Args:
310
- request: The FastAPI request object
311
-
312
- Returns:
313
- Current metrics from PyWebGuard
314
- """
315
- # This would typically be protected by authentication
316
- guard = request.app.state.guard
317
- # Get rate limit info for all paths
318
- rate_limits = {}
319
- for path in ["/", "/api/limited", "/api/uploads/*", "/api/admin/**"]:
320
- rate_info = await guard.guard.rate_limiter.check_limit(
321
- request.client.host, path
322
- )
323
- rate_limits[path] = {
324
- "allowed": rate_info["allowed"],
325
- "remaining": rate_info["remaining"],
326
- "reset": rate_info["reset"],
327
- }
328
-
329
- return {
330
- "timestamp": time.time(),
331
- "metrics": {
332
- "rate_limits": rate_limits,
333
- "client_ip": request.client.host,
334
- "user_agent": request.headers.get("user-agent", "Unknown"),
335
- },
336
- }
337
-
338
-
339
- # Admin endpoint to ban an IP
340
- @app.post("/admin/ban-ip", tags=["admin"])
341
- async def ban_ip(request: Request, ip: str, duration: int = 60):
342
- """
343
- Ban an IP address
344
-
345
- Args:
346
- request: The FastAPI request object
347
- ip: The IP to ban
348
- duration: Ban duration in seconds (default: 1 hour)
349
-
350
- Returns:
351
- Ban confirmation
352
- """
353
- # This would typically be protected by authentication
354
- guard = request.app.state.guard
355
- ban_key = f"banned_ip:{ip}"
356
- await guard.guard.storage.set(
357
- ban_key,
358
- {"reason": "Manually banned via API", "timestamp": time.time()},
359
- duration,
360
- )
361
-
362
- return {
363
- "message": f"IP {ip} banned for {duration} seconds",
364
- "timestamp": time.time(),
365
- }
366
-
367
-
368
- # Admin endpoint to unban an IP
369
- @app.post("/admin/unban-ip", tags=["admin"])
370
- async def unban_ip(request: Request, ip: str):
371
- """
372
- Unban an IP address
373
-
374
- Args:
375
- request: The FastAPI request object
376
- ip: The IP to unban
377
-
378
- Returns:
379
- Unban confirmation
380
- """
381
- # This would typically be protected by authentication
382
- guard = request.app.state.guard
383
- ban_key = f"banned_ip:{ip}"
384
- await guard.guard.storage.delete(ban_key)
385
-
386
- return {
387
- "message": f"IP {ip} unbanned",
388
- "timestamp": time.time(),
389
- }
390
-
391
-
392
- if __name__ == "__main__":
393
- logger.info("Starting PyWebGuard FastAPI example server...")
394
- uvicorn.run(app, host="0.0.0.0", port=8000)
395
- ```
396
-
397
-
398
- ## Documentation
399
- - [Installation Guide](docs/installation.md)
400
- - [CLI Usage](docs/cli.md)
401
- - [Core Features](docs/core/)
402
- - [Framework Integration](docs/frameworks/)
403
- - [Storage Backends](docs/storage/)
404
-
405
- ## Contributors
406
-
407
- <a href="https://github.com/py-daily/pywebguard/graphs/contributors">
408
- <img src="https://contrib.rocks/image?repo=py-daily/pywebguard" width="80" />
409
- </a>
410
-
411
-
412
- ## License
413
-
414
- This project is licensed under the [MIT License](LICENSE).
415
-