fastapi-guard 0.1.0__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.
- fastapi_guard-0.1.0/LICENSE +21 -0
- fastapi_guard-0.1.0/PKG-INFO +296 -0
- fastapi_guard-0.1.0/README.md +270 -0
- fastapi_guard-0.1.0/config/__init__.py +0 -0
- fastapi_guard-0.1.0/config/ip2/__init__.py +0 -0
- fastapi_guard-0.1.0/config/ip2/ip2location_config.py +162 -0
- fastapi_guard-0.1.0/config/sus_patterns.py +261 -0
- fastapi_guard-0.1.0/fastapi_guard.egg-info/PKG-INFO +296 -0
- fastapi_guard-0.1.0/fastapi_guard.egg-info/SOURCES.txt +19 -0
- fastapi_guard-0.1.0/fastapi_guard.egg-info/dependency_links.txt +1 -0
- fastapi_guard-0.1.0/fastapi_guard.egg-info/requires.txt +13 -0
- fastapi_guard-0.1.0/fastapi_guard.egg-info/top_level.txt +3 -0
- fastapi_guard-0.1.0/guard/__init__.py +5 -0
- fastapi_guard-0.1.0/guard/cloud_ips.py +110 -0
- fastapi_guard-0.1.0/guard/middleware.py +331 -0
- fastapi_guard-0.1.0/guard/models.py +234 -0
- fastapi_guard-0.1.0/guard/utils.py +321 -0
- fastapi_guard-0.1.0/setup.cfg +4 -0
- fastapi_guard-0.1.0/setup.py +43 -0
- fastapi_guard-0.1.0/tests/__init__.py +0 -0
- fastapi_guard-0.1.0/tests/conftest.py +53 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Renzo F
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: fastapi_guard
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A security library for FastAPI to control IPs, log requests, and detect penetration attempts.
|
|
5
|
+
Home-page: https://github.com/rennf93/fastapi_guard
|
|
6
|
+
Author: Renzo Franceschini
|
|
7
|
+
Author-email: rennf93@gmail.com
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Requires-Dist: aiohttp
|
|
15
|
+
Requires-Dist: cachetools
|
|
16
|
+
Requires-Dist: fastapi
|
|
17
|
+
Requires-Dist: ipaddress
|
|
18
|
+
Requires-Dist: IP2Location
|
|
19
|
+
Requires-Dist: requests
|
|
20
|
+
Requires-Dist: uvicorn
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: httpx; extra == "dev"
|
|
23
|
+
Requires-Dist: pytest; extra == "dev"
|
|
24
|
+
Requires-Dist: pytest-asyncio; extra == "dev"
|
|
25
|
+
Requires-Dist: pytest-mock; extra == "dev"
|
|
26
|
+
|
|
27
|
+
# FastAPI Guard
|
|
28
|
+
|
|
29
|
+
`fastapi-guard` is 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.
|
|
30
|
+
|
|
31
|
+
## Features
|
|
32
|
+
|
|
33
|
+
- **IP Whitelisting and Blacklisting**: Control access based on IP addresses.
|
|
34
|
+
- **User Agent Filtering**: Block requests from specific user agents.
|
|
35
|
+
- **Rate Limiting**: Limit the number of requests from a single IP.
|
|
36
|
+
- **Automatic IP Banning**: Automatically ban IPs after a certain number of suspicious requests.
|
|
37
|
+
- **Penetration Attempt Detection**: Detect and log potential penetration attempts.
|
|
38
|
+
- **Custom Logging**: Log security events to a custom file.
|
|
39
|
+
- **CORS Configuration**: Configure CORS settings for your FastAPI application.
|
|
40
|
+
- **Cloud Provider IP Blocking**: Block requests from cloud provider IPs (AWS, GCP, Azure).
|
|
41
|
+
- **IP Geolocation**: Use IP2Location or ipinfo.io to determine the country of an IP address.
|
|
42
|
+
|
|
43
|
+
## Installation
|
|
44
|
+
|
|
45
|
+
To install `fastapi-guard`, use pip:
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
pip install fastapi-guard
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Usage
|
|
52
|
+
|
|
53
|
+
### Basic Setup
|
|
54
|
+
|
|
55
|
+
To use `fastapi-guard`, you need to configure the middleware in your FastAPI application. Here's a basic example:
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from fastapi import FastAPI
|
|
59
|
+
from guard.middleware import SecurityMiddleware
|
|
60
|
+
from guard.models import SecurityConfig
|
|
61
|
+
|
|
62
|
+
app = FastAPI()
|
|
63
|
+
|
|
64
|
+
# Define your security configuration
|
|
65
|
+
config = SecurityConfig(
|
|
66
|
+
whitelist=["192.168.1.1"],
|
|
67
|
+
blacklist=["10.0.0.1"],
|
|
68
|
+
blocked_countries=["AR", "IT"],
|
|
69
|
+
blocked_user_agents=["curl", "wget"],
|
|
70
|
+
auto_ban_threshold=5,
|
|
71
|
+
auto_ban_duration=86400,
|
|
72
|
+
custom_log_file="security.log",
|
|
73
|
+
rate_limit=100,
|
|
74
|
+
use_ip2location=True,
|
|
75
|
+
ip2location_db_path="./IP2LOCATION-LITE-DB1.IPV6.BIN",
|
|
76
|
+
ip2location_auto_download=True,
|
|
77
|
+
ip2location_auto_update=True,
|
|
78
|
+
ip2location_update_interval=24,
|
|
79
|
+
use_ipinfo_fallback=True,
|
|
80
|
+
enforce_https=True,
|
|
81
|
+
enable_cors=True,
|
|
82
|
+
cors_allow_origins=["*"],
|
|
83
|
+
cors_allow_methods=["GET", "POST"],
|
|
84
|
+
cors_allow_headers=["*"],
|
|
85
|
+
cors_allow_credentials=True,
|
|
86
|
+
cors_expose_headers=["X-Custom-Header"],
|
|
87
|
+
cors_max_age=600,
|
|
88
|
+
block_cloud_providers={"AWS", "GCP", "Azure"},
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
# Add the security middleware
|
|
92
|
+
app.add_middleware(SecurityMiddleware, config=config)
|
|
93
|
+
|
|
94
|
+
@app.get("/")
|
|
95
|
+
async def read_root():
|
|
96
|
+
return {"message": "Hello, World!"}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### IP Whitelisting and Blacklisting
|
|
100
|
+
|
|
101
|
+
You can control access based on IP addresses using the `whitelist` and `blacklist` options in the `SecurityConfig`.
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
config = SecurityConfig(
|
|
105
|
+
whitelist=["192.168.1.1"],
|
|
106
|
+
blacklist=["10.0.0.1"],
|
|
107
|
+
)
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### User Agent Filtering
|
|
111
|
+
|
|
112
|
+
Block requests from specific user agents by adding patterns to the `blocked_user_agents` list.
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
config = SecurityConfig(
|
|
116
|
+
blocked_user_agents=["curl", "wget"],
|
|
117
|
+
)
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Rate Limiting
|
|
121
|
+
|
|
122
|
+
Limit the number of requests from a single IP using the `rate_limit` option.
|
|
123
|
+
|
|
124
|
+
```python
|
|
125
|
+
config = SecurityConfig(
|
|
126
|
+
rate_limit=100, # Maximum 100 requests per minute
|
|
127
|
+
)
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### Automatic IP Banning
|
|
131
|
+
|
|
132
|
+
Automatically ban IPs after a certain number of suspicious requests using the `auto_ban_threshold` and `auto_ban_duration` options.
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
config = SecurityConfig(
|
|
136
|
+
auto_ban_threshold=5, # Ban IP after 5 suspicious requests
|
|
137
|
+
auto_ban_duration=86400, # Ban duration in seconds (1 day)
|
|
138
|
+
)
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Penetration Attempt Detection
|
|
142
|
+
|
|
143
|
+
Detect and log potential penetration attempts using the `detect_penetration_attempt` function.
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
from fastapi import Request
|
|
147
|
+
from guard.utils import detect_penetration_attempt
|
|
148
|
+
|
|
149
|
+
@app.post("/submit")
|
|
150
|
+
async def submit_data(request: Request):
|
|
151
|
+
if await detect_penetration_attempt(request):
|
|
152
|
+
return {"error": "Potential attack detected"}
|
|
153
|
+
return {"message": "Data submitted successfully"}
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Custom Logging
|
|
157
|
+
|
|
158
|
+
Log security events to a custom file using the `custom_log_file` option.
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
config = SecurityConfig(
|
|
162
|
+
custom_log_file="security.log",
|
|
163
|
+
)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### CORS Configuration
|
|
167
|
+
|
|
168
|
+
Configure CORS settings for your FastAPI application using the `enable_cors` and related options.
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
config = SecurityConfig(
|
|
172
|
+
enable_cors=True,
|
|
173
|
+
cors_allow_origins=["*"],
|
|
174
|
+
cors_allow_methods=["GET", "POST"],
|
|
175
|
+
cors_allow_headers=["*"],
|
|
176
|
+
cors_allow_credentials=True,
|
|
177
|
+
cors_expose_headers=["X-Custom-Header"],
|
|
178
|
+
cors_max_age=600,
|
|
179
|
+
)
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
### Cloud Provider IP Blocking
|
|
183
|
+
|
|
184
|
+
Block requests from cloud provider IPs (AWS, GCP, Azure) using the `block_cloud_providers` option.
|
|
185
|
+
|
|
186
|
+
```python
|
|
187
|
+
config = SecurityConfig(
|
|
188
|
+
block_cloud_providers={"AWS", "GCP", "Azure"},
|
|
189
|
+
)
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
### IP Geolocation
|
|
193
|
+
|
|
194
|
+
Use IP2Location or ipinfo.io to determine the country of an IP address using the `use_ip2location` and `use_ipinfo_fallback` options.
|
|
195
|
+
|
|
196
|
+
```python
|
|
197
|
+
config = SecurityConfig(
|
|
198
|
+
use_ip2location=True,
|
|
199
|
+
ip2location_db_path="./IP2LOCATION-LITE-DB1.IPV6.BIN",
|
|
200
|
+
ip2location_auto_download=True,
|
|
201
|
+
ip2location_auto_update=True,
|
|
202
|
+
ip2location_update_interval=24,
|
|
203
|
+
use_ipinfo_fallback=True,
|
|
204
|
+
)
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
## Advanced Usage
|
|
208
|
+
|
|
209
|
+
### Custom Request Check
|
|
210
|
+
|
|
211
|
+
You can define a custom function to perform additional checks on the request using the `custom_request_check` option.
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
from fastapi import Request, Response
|
|
215
|
+
|
|
216
|
+
async def custom_check(request: Request) -> Optional[Response]:
|
|
217
|
+
if "X-Custom-Header" not in request.headers:
|
|
218
|
+
return Response("Missing custom header", status_code=400)
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
config = SecurityConfig(
|
|
222
|
+
custom_request_check=custom_check,
|
|
223
|
+
)
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
### Custom Response Modifier
|
|
227
|
+
|
|
228
|
+
You can define a custom function to modify the response before it's sent using the `custom_response_modifier` option.
|
|
229
|
+
|
|
230
|
+
```python
|
|
231
|
+
from fastapi import Response
|
|
232
|
+
|
|
233
|
+
async def custom_modifier(response: Response) -> Response:
|
|
234
|
+
response.headers["X-Custom-Header"] = "CustomValue"
|
|
235
|
+
return response
|
|
236
|
+
|
|
237
|
+
config = SecurityConfig(
|
|
238
|
+
custom_response_modifier=custom_modifier,
|
|
239
|
+
)
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
## Detailed Configuration Options
|
|
243
|
+
|
|
244
|
+
### SecurityConfig
|
|
245
|
+
|
|
246
|
+
The `SecurityConfig` class defines the structure for security configuration, including IP whitelists and blacklists, blocked countries, blocked user agents, rate limiting, automatic IP banning, IP2Location settings, HTTPS enforcement, custom hooks, CORS settings, and blocking of cloud provider IPs.
|
|
247
|
+
|
|
248
|
+
#### Attributes
|
|
249
|
+
|
|
250
|
+
- `whitelist`: Optional[List[str]] - A list of IP addresses or ranges that are always allowed. If set to None, no whitelist is applied.
|
|
251
|
+
- `blacklist`: List[str] - A list of IP addresses or ranges that are always blocked.
|
|
252
|
+
- `blocked_countries`: List[str] - A list of country codes whose IP addresses should be blocked.
|
|
253
|
+
- `blocked_user_agents`: List[str] - A list of user agent strings or patterns that should be blocked.
|
|
254
|
+
- `auto_ban_threshold`: int - The threshold for auto-banning an IP address after a certain number of requests.
|
|
255
|
+
- `auto_ban_duration`: int - The duration in seconds for which an IP address should be banned after reaching the auto-ban threshold.
|
|
256
|
+
- `custom_log_file`: Optional[str] - The path to a custom log file for logging security events.
|
|
257
|
+
- `custom_error_responses`: Dict[int, str] - A dictionary of custom error responses for specific HTTP status codes.
|
|
258
|
+
- `rate_limit`: int - The maximum number of requests allowed per minute from a single IP.
|
|
259
|
+
- `use_ip2location`: bool - Whether to use the IP2Location database for IP geolocation.
|
|
260
|
+
- `ip2location_db_path`: Optional[str] - The path to the IP2Location database file.
|
|
261
|
+
- `ip2location_auto_download`: bool - Whether to automatically download the IP2Location database if it's not found.
|
|
262
|
+
- `ip2location_auto_update`: bool - Whether to automatically update the IP2Location database periodically.
|
|
263
|
+
- `ip2location_update_interval`: int - The interval in hours for automatic IP2Location database updates.
|
|
264
|
+
- `use_ipinfo_fallback`: bool - Whether to use ipinfo.io as a fallback for IP geolocation when IP2Location fails.
|
|
265
|
+
- `enforce_https`: bool - Whether to enforce HTTPS connections. If True, all HTTP requests will be redirected to HTTPS.
|
|
266
|
+
- `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.
|
|
267
|
+
- `custom_response_modifier`: Optional[Callable[[Response], Awaitable[Response]]] - A custom function to modify the response before it's sent.
|
|
268
|
+
- `enable_cors`: bool - Whether to enable CORS.
|
|
269
|
+
- `cors_allow_origins`: List[str] - A list of origins that are allowed to access the API.
|
|
270
|
+
- `cors_allow_methods`: List[str] - A list of methods that are allowed to access the API.
|
|
271
|
+
- `cors_allow_headers`: List[str] - A list of headers that are allowed in CORS requests.
|
|
272
|
+
- `cors_allow_credentials`: bool - Whether to allow credentials in CORS requests.
|
|
273
|
+
- `cors_expose_headers`: List[str] - A list of headers that are exposed in CORS responses.
|
|
274
|
+
- `cors_max_age`: int - The maximum age in seconds that the results of a preflight request can be cached.
|
|
275
|
+
- `block_cloud_providers`: Optional[Set[str]] - A set of cloud provider names to block. Supported values: 'AWS', 'GCP', 'Azure'.
|
|
276
|
+
|
|
277
|
+
## Contributing
|
|
278
|
+
|
|
279
|
+
Contributions are welcome! Please open an issue or submit a pull request on GitHub.
|
|
280
|
+
|
|
281
|
+
## License
|
|
282
|
+
|
|
283
|
+
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
|
|
284
|
+
|
|
285
|
+
## Author
|
|
286
|
+
|
|
287
|
+
Renzo Franceschini - [rennf93@gmail.com](mailto:rennf93@gmail.com)
|
|
288
|
+
|
|
289
|
+
## Acknowledgements
|
|
290
|
+
|
|
291
|
+
- [FastAPI](https://fastapi.tiangolo.com/)
|
|
292
|
+
- [IP2Location](https://www.ip2location.com/)
|
|
293
|
+
- [aiohttp](https://docs.aiohttp.org/)
|
|
294
|
+
- [cachetools](https://cachetools.readthedocs.io/)
|
|
295
|
+
- [requests](https://docs.python-requests.org/)
|
|
296
|
+
- [uvicorn](https://www.uvicorn.org/)
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
# FastAPI Guard
|
|
2
|
+
|
|
3
|
+
`fastapi-guard` is 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.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **IP Whitelisting and Blacklisting**: Control access based on IP addresses.
|
|
8
|
+
- **User Agent Filtering**: Block requests from specific user agents.
|
|
9
|
+
- **Rate Limiting**: Limit the number of requests from a single IP.
|
|
10
|
+
- **Automatic IP Banning**: Automatically ban IPs after a certain number of suspicious requests.
|
|
11
|
+
- **Penetration Attempt Detection**: Detect and log potential penetration attempts.
|
|
12
|
+
- **Custom Logging**: Log security events to a custom file.
|
|
13
|
+
- **CORS Configuration**: Configure CORS settings for your FastAPI application.
|
|
14
|
+
- **Cloud Provider IP Blocking**: Block requests from cloud provider IPs (AWS, GCP, Azure).
|
|
15
|
+
- **IP Geolocation**: Use IP2Location or ipinfo.io to determine the country of an IP address.
|
|
16
|
+
|
|
17
|
+
## Installation
|
|
18
|
+
|
|
19
|
+
To install `fastapi-guard`, use pip:
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
pip install fastapi-guard
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Usage
|
|
26
|
+
|
|
27
|
+
### Basic Setup
|
|
28
|
+
|
|
29
|
+
To use `fastapi-guard`, you need to configure the middleware in your FastAPI application. Here's a basic example:
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
from fastapi import FastAPI
|
|
33
|
+
from guard.middleware import SecurityMiddleware
|
|
34
|
+
from guard.models import SecurityConfig
|
|
35
|
+
|
|
36
|
+
app = FastAPI()
|
|
37
|
+
|
|
38
|
+
# Define your security configuration
|
|
39
|
+
config = SecurityConfig(
|
|
40
|
+
whitelist=["192.168.1.1"],
|
|
41
|
+
blacklist=["10.0.0.1"],
|
|
42
|
+
blocked_countries=["AR", "IT"],
|
|
43
|
+
blocked_user_agents=["curl", "wget"],
|
|
44
|
+
auto_ban_threshold=5,
|
|
45
|
+
auto_ban_duration=86400,
|
|
46
|
+
custom_log_file="security.log",
|
|
47
|
+
rate_limit=100,
|
|
48
|
+
use_ip2location=True,
|
|
49
|
+
ip2location_db_path="./IP2LOCATION-LITE-DB1.IPV6.BIN",
|
|
50
|
+
ip2location_auto_download=True,
|
|
51
|
+
ip2location_auto_update=True,
|
|
52
|
+
ip2location_update_interval=24,
|
|
53
|
+
use_ipinfo_fallback=True,
|
|
54
|
+
enforce_https=True,
|
|
55
|
+
enable_cors=True,
|
|
56
|
+
cors_allow_origins=["*"],
|
|
57
|
+
cors_allow_methods=["GET", "POST"],
|
|
58
|
+
cors_allow_headers=["*"],
|
|
59
|
+
cors_allow_credentials=True,
|
|
60
|
+
cors_expose_headers=["X-Custom-Header"],
|
|
61
|
+
cors_max_age=600,
|
|
62
|
+
block_cloud_providers={"AWS", "GCP", "Azure"},
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# Add the security middleware
|
|
66
|
+
app.add_middleware(SecurityMiddleware, config=config)
|
|
67
|
+
|
|
68
|
+
@app.get("/")
|
|
69
|
+
async def read_root():
|
|
70
|
+
return {"message": "Hello, World!"}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### IP Whitelisting and Blacklisting
|
|
74
|
+
|
|
75
|
+
You can control access based on IP addresses using the `whitelist` and `blacklist` options in the `SecurityConfig`.
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
config = SecurityConfig(
|
|
79
|
+
whitelist=["192.168.1.1"],
|
|
80
|
+
blacklist=["10.0.0.1"],
|
|
81
|
+
)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### User Agent Filtering
|
|
85
|
+
|
|
86
|
+
Block requests from specific user agents by adding patterns to the `blocked_user_agents` list.
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
config = SecurityConfig(
|
|
90
|
+
blocked_user_agents=["curl", "wget"],
|
|
91
|
+
)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Rate Limiting
|
|
95
|
+
|
|
96
|
+
Limit the number of requests from a single IP using the `rate_limit` option.
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
config = SecurityConfig(
|
|
100
|
+
rate_limit=100, # Maximum 100 requests per minute
|
|
101
|
+
)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Automatic IP Banning
|
|
105
|
+
|
|
106
|
+
Automatically ban IPs after a certain number of suspicious requests using the `auto_ban_threshold` and `auto_ban_duration` options.
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
config = SecurityConfig(
|
|
110
|
+
auto_ban_threshold=5, # Ban IP after 5 suspicious requests
|
|
111
|
+
auto_ban_duration=86400, # Ban duration in seconds (1 day)
|
|
112
|
+
)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Penetration Attempt Detection
|
|
116
|
+
|
|
117
|
+
Detect and log potential penetration attempts using the `detect_penetration_attempt` function.
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
from fastapi import Request
|
|
121
|
+
from guard.utils import detect_penetration_attempt
|
|
122
|
+
|
|
123
|
+
@app.post("/submit")
|
|
124
|
+
async def submit_data(request: Request):
|
|
125
|
+
if await detect_penetration_attempt(request):
|
|
126
|
+
return {"error": "Potential attack detected"}
|
|
127
|
+
return {"message": "Data submitted successfully"}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### Custom Logging
|
|
131
|
+
|
|
132
|
+
Log security events to a custom file using the `custom_log_file` option.
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
config = SecurityConfig(
|
|
136
|
+
custom_log_file="security.log",
|
|
137
|
+
)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### CORS Configuration
|
|
141
|
+
|
|
142
|
+
Configure CORS settings for your FastAPI application using the `enable_cors` and related options.
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
config = SecurityConfig(
|
|
146
|
+
enable_cors=True,
|
|
147
|
+
cors_allow_origins=["*"],
|
|
148
|
+
cors_allow_methods=["GET", "POST"],
|
|
149
|
+
cors_allow_headers=["*"],
|
|
150
|
+
cors_allow_credentials=True,
|
|
151
|
+
cors_expose_headers=["X-Custom-Header"],
|
|
152
|
+
cors_max_age=600,
|
|
153
|
+
)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Cloud Provider IP Blocking
|
|
157
|
+
|
|
158
|
+
Block requests from cloud provider IPs (AWS, GCP, Azure) using the `block_cloud_providers` option.
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
config = SecurityConfig(
|
|
162
|
+
block_cloud_providers={"AWS", "GCP", "Azure"},
|
|
163
|
+
)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### IP Geolocation
|
|
167
|
+
|
|
168
|
+
Use IP2Location or ipinfo.io to determine the country of an IP address using the `use_ip2location` and `use_ipinfo_fallback` options.
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
config = SecurityConfig(
|
|
172
|
+
use_ip2location=True,
|
|
173
|
+
ip2location_db_path="./IP2LOCATION-LITE-DB1.IPV6.BIN",
|
|
174
|
+
ip2location_auto_download=True,
|
|
175
|
+
ip2location_auto_update=True,
|
|
176
|
+
ip2location_update_interval=24,
|
|
177
|
+
use_ipinfo_fallback=True,
|
|
178
|
+
)
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
## Advanced Usage
|
|
182
|
+
|
|
183
|
+
### Custom Request Check
|
|
184
|
+
|
|
185
|
+
You can define a custom function to perform additional checks on the request using the `custom_request_check` option.
|
|
186
|
+
|
|
187
|
+
```python
|
|
188
|
+
from fastapi import Request, Response
|
|
189
|
+
|
|
190
|
+
async def custom_check(request: Request) -> Optional[Response]:
|
|
191
|
+
if "X-Custom-Header" not in request.headers:
|
|
192
|
+
return Response("Missing custom header", status_code=400)
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
config = SecurityConfig(
|
|
196
|
+
custom_request_check=custom_check,
|
|
197
|
+
)
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### Custom Response Modifier
|
|
201
|
+
|
|
202
|
+
You can define a custom function to modify the response before it's sent using the `custom_response_modifier` option.
|
|
203
|
+
|
|
204
|
+
```python
|
|
205
|
+
from fastapi import Response
|
|
206
|
+
|
|
207
|
+
async def custom_modifier(response: Response) -> Response:
|
|
208
|
+
response.headers["X-Custom-Header"] = "CustomValue"
|
|
209
|
+
return response
|
|
210
|
+
|
|
211
|
+
config = SecurityConfig(
|
|
212
|
+
custom_response_modifier=custom_modifier,
|
|
213
|
+
)
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
## Detailed Configuration Options
|
|
217
|
+
|
|
218
|
+
### SecurityConfig
|
|
219
|
+
|
|
220
|
+
The `SecurityConfig` class defines the structure for security configuration, including IP whitelists and blacklists, blocked countries, blocked user agents, rate limiting, automatic IP banning, IP2Location settings, HTTPS enforcement, custom hooks, CORS settings, and blocking of cloud provider IPs.
|
|
221
|
+
|
|
222
|
+
#### Attributes
|
|
223
|
+
|
|
224
|
+
- `whitelist`: Optional[List[str]] - A list of IP addresses or ranges that are always allowed. If set to None, no whitelist is applied.
|
|
225
|
+
- `blacklist`: List[str] - A list of IP addresses or ranges that are always blocked.
|
|
226
|
+
- `blocked_countries`: List[str] - A list of country codes whose IP addresses should be blocked.
|
|
227
|
+
- `blocked_user_agents`: List[str] - A list of user agent strings or patterns that should be blocked.
|
|
228
|
+
- `auto_ban_threshold`: int - The threshold for auto-banning an IP address after a certain number of requests.
|
|
229
|
+
- `auto_ban_duration`: int - The duration in seconds for which an IP address should be banned after reaching the auto-ban threshold.
|
|
230
|
+
- `custom_log_file`: Optional[str] - The path to a custom log file for logging security events.
|
|
231
|
+
- `custom_error_responses`: Dict[int, str] - A dictionary of custom error responses for specific HTTP status codes.
|
|
232
|
+
- `rate_limit`: int - The maximum number of requests allowed per minute from a single IP.
|
|
233
|
+
- `use_ip2location`: bool - Whether to use the IP2Location database for IP geolocation.
|
|
234
|
+
- `ip2location_db_path`: Optional[str] - The path to the IP2Location database file.
|
|
235
|
+
- `ip2location_auto_download`: bool - Whether to automatically download the IP2Location database if it's not found.
|
|
236
|
+
- `ip2location_auto_update`: bool - Whether to automatically update the IP2Location database periodically.
|
|
237
|
+
- `ip2location_update_interval`: int - The interval in hours for automatic IP2Location database updates.
|
|
238
|
+
- `use_ipinfo_fallback`: bool - Whether to use ipinfo.io as a fallback for IP geolocation when IP2Location fails.
|
|
239
|
+
- `enforce_https`: bool - Whether to enforce HTTPS connections. If True, all HTTP requests will be redirected to HTTPS.
|
|
240
|
+
- `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.
|
|
241
|
+
- `custom_response_modifier`: Optional[Callable[[Response], Awaitable[Response]]] - A custom function to modify the response before it's sent.
|
|
242
|
+
- `enable_cors`: bool - Whether to enable CORS.
|
|
243
|
+
- `cors_allow_origins`: List[str] - A list of origins that are allowed to access the API.
|
|
244
|
+
- `cors_allow_methods`: List[str] - A list of methods that are allowed to access the API.
|
|
245
|
+
- `cors_allow_headers`: List[str] - A list of headers that are allowed in CORS requests.
|
|
246
|
+
- `cors_allow_credentials`: bool - Whether to allow credentials in CORS requests.
|
|
247
|
+
- `cors_expose_headers`: List[str] - A list of headers that are exposed in CORS responses.
|
|
248
|
+
- `cors_max_age`: int - The maximum age in seconds that the results of a preflight request can be cached.
|
|
249
|
+
- `block_cloud_providers`: Optional[Set[str]] - A set of cloud provider names to block. Supported values: 'AWS', 'GCP', 'Azure'.
|
|
250
|
+
|
|
251
|
+
## Contributing
|
|
252
|
+
|
|
253
|
+
Contributions are welcome! Please open an issue or submit a pull request on GitHub.
|
|
254
|
+
|
|
255
|
+
## License
|
|
256
|
+
|
|
257
|
+
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
|
|
258
|
+
|
|
259
|
+
## Author
|
|
260
|
+
|
|
261
|
+
Renzo Franceschini - [rennf93@gmail.com](mailto:rennf93@gmail.com)
|
|
262
|
+
|
|
263
|
+
## Acknowledgements
|
|
264
|
+
|
|
265
|
+
- [FastAPI](https://fastapi.tiangolo.com/)
|
|
266
|
+
- [IP2Location](https://www.ip2location.com/)
|
|
267
|
+
- [aiohttp](https://docs.aiohttp.org/)
|
|
268
|
+
- [cachetools](https://cachetools.readthedocs.io/)
|
|
269
|
+
- [requests](https://docs.python-requests.org/)
|
|
270
|
+
- [uvicorn](https://www.uvicorn.org/)
|
|
File without changes
|
|
File without changes
|