pywebguard 0.0.0__py3-none-any.whl

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 (43) hide show
  1. pywebguard/__init__.py +87 -0
  2. pywebguard/cli.py +1022 -0
  3. pywebguard/core/__init__.py +0 -0
  4. pywebguard/core/base.py +792 -0
  5. pywebguard/core/config.py +455 -0
  6. pywebguard/filters/__init__.py +0 -0
  7. pywebguard/filters/base.py +44 -0
  8. pywebguard/filters/ip_filter.py +233 -0
  9. pywebguard/filters/user_agent.py +102 -0
  10. pywebguard/frameworks/__init__.py +0 -0
  11. pywebguard/frameworks/_fastapi.py +191 -0
  12. pywebguard/frameworks/_flask.py +182 -0
  13. pywebguard/limiters/__init__.py +0 -0
  14. pywebguard/limiters/base.py +46 -0
  15. pywebguard/limiters/rate_limit.py +415 -0
  16. pywebguard/logging/__init__.py +0 -0
  17. pywebguard/logging/backends/__init__.py +17 -0
  18. pywebguard/logging/backends/_elasticsearch.py +307 -0
  19. pywebguard/logging/backends/_meilisearch.py +310 -0
  20. pywebguard/logging/backends/_mongodb.py +303 -0
  21. pywebguard/logging/base.py +117 -0
  22. pywebguard/logging/logger.py +408 -0
  23. pywebguard/security/__init__.py +0 -0
  24. pywebguard/security/base.py +44 -0
  25. pywebguard/security/cors.py +204 -0
  26. pywebguard/security/penetration.py +265 -0
  27. pywebguard/storage/__init__.py +0 -0
  28. pywebguard/storage/_mongodb.py +396 -0
  29. pywebguard/storage/_postgresql.py +539 -0
  30. pywebguard/storage/_redis.py +314 -0
  31. pywebguard/storage/_sqlite.py +374 -0
  32. pywebguard/storage/_tinydb.py +271 -0
  33. pywebguard/storage/base.py +327 -0
  34. pywebguard/storage/memory.py +245 -0
  35. pywebguard/utils/__init__.py +0 -0
  36. pywebguard/utils/ip.py +84 -0
  37. pywebguard/utils/request.py +65 -0
  38. pywebguard-0.0.0.dist-info/LICENSE +21 -0
  39. pywebguard-0.0.0.dist-info/METADATA +368 -0
  40. pywebguard-0.0.0.dist-info/RECORD +43 -0
  41. pywebguard-0.0.0.dist-info/WHEEL +5 -0
  42. pywebguard-0.0.0.dist-info/entry_points.txt +2 -0
  43. pywebguard-0.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,303 @@
1
+ # """
2
+ # MongoDB logging backend for PyWebGuard.
3
+ # """
4
+
5
+ # import time
6
+ # import logging
7
+ # from typing import Dict, Any, Optional, TYPE_CHECKING
8
+
9
+ # # Try to import pymongo
10
+ # try:
11
+ # from pymongo import MongoClient, AsyncMongoClient
12
+
13
+ # PYMONGO_AVAILABLE = True
14
+ # except ImportError:
15
+ # PYMONGO_AVAILABLE = False
16
+ # if TYPE_CHECKING:
17
+ # from pymongo import MongoClient, AsyncMongoClient
18
+
19
+ # from ..base import LoggingBackend, AsyncLoggingBackend
20
+
21
+
22
+ # class MongoDBBackend(LoggingBackend):
23
+ # """
24
+ # Synchronous MongoDB logging backend implementation.
25
+ # """
26
+
27
+ # def __init__(self, config: Dict[str, Any]):
28
+ # """
29
+ # Initialize the MongoDB backend.
30
+
31
+ # Args:
32
+ # config: Configuration dictionary containing:
33
+ # - uri: MongoDB connection URI
34
+ # - database: Database name
35
+ # - collection: Collection name
36
+ # - username: Optional username for authentication
37
+ # - password: Optional password for authentication
38
+
39
+ # Raises:
40
+ # ImportError: If pymongo is not installed
41
+ # """
42
+ # if not PYMONGO_AVAILABLE:
43
+ # raise ImportError(
44
+ # "MongoDB backend requires pymongo. Install it with 'pip install pymongo'"
45
+ # )
46
+
47
+ # self.config = config
48
+ # self.client = None
49
+ # self.collection = None
50
+ # self.setup(config)
51
+
52
+ # def setup(self, config: Dict[str, Any]) -> None:
53
+ # """
54
+ # Set up the MongoDB client and collection.
55
+
56
+ # Args:
57
+ # config: Configuration dictionary
58
+ # """
59
+ # # Build connection URI if not provided
60
+ # if "uri" not in config:
61
+ # auth_str = ""
62
+ # if "username" in config and "password" in config:
63
+ # auth_str = f"{config['username']}:{config['password']}@"
64
+ # config["uri"] = f"mongodb://{auth_str}{config['host']}:{config['port']}"
65
+
66
+ # self.client = MongoClient(config["uri"])
67
+ # db = self.client[config["database"]]
68
+ # self.collection = db[config["collection"]]
69
+
70
+ # # Create indexes for efficient querying
71
+ # self.collection.create_index("timestamp")
72
+ # self.collection.create_index("level")
73
+ # self.collection.create_index("ip")
74
+ # self.collection.create_index("event_type")
75
+ # self.collection.create_index([("timestamp", -1)])
76
+
77
+ # def _create_log_entry(self, **kwargs) -> Dict[str, Any]:
78
+ # """
79
+ # Create a standardized log entry.
80
+
81
+ # Returns:
82
+ # Dict containing the log entry
83
+ # """
84
+ # return {"timestamp": int(time.time() * 1000), **kwargs} # milliseconds
85
+
86
+ # def log_request(self, request_info: Dict[str, Any], response: Any) -> None:
87
+ # """
88
+ # Log a request to MongoDB.
89
+
90
+ # Args:
91
+ # request_info: Dict with request information
92
+ # response: The framework-specific response object
93
+ # """
94
+ # log_entry = self._create_log_entry(
95
+ # level="INFO",
96
+ # ip=request_info.get("ip", "unknown"),
97
+ # method=request_info.get("method", "unknown"),
98
+ # path=request_info.get("path", "unknown"),
99
+ # status_code=self._extract_status_code(response),
100
+ # user_agent=request_info.get("user_agent", "unknown"),
101
+ # event_type="request",
102
+ # )
103
+ # self.collection.insert_one(log_entry)
104
+
105
+ # def log_blocked_request(
106
+ # self, request_info: Dict[str, Any], block_type: str, reason: str
107
+ # ) -> None:
108
+ # """
109
+ # Log a blocked request to MongoDB.
110
+
111
+ # Args:
112
+ # request_info: Dict with request information
113
+ # block_type: Type of block (IP filter, rate limit, etc.)
114
+ # reason: Reason for blocking
115
+ # """
116
+ # log_entry = self._create_log_entry(
117
+ # level="WARNING",
118
+ # ip=request_info.get("ip", "unknown"),
119
+ # method=request_info.get("method", "unknown"),
120
+ # path=request_info.get("path", "unknown"),
121
+ # block_type=block_type,
122
+ # reason=reason,
123
+ # user_agent=request_info.get("user_agent", "unknown"),
124
+ # event_type="blocked_request",
125
+ # )
126
+ # self.collection.insert_one(log_entry)
127
+
128
+ # def log_security_event(
129
+ # self, level: str, message: str, extra: Optional[Dict[str, Any]] = None
130
+ # ) -> None:
131
+ # """
132
+ # Log a security event to MongoDB.
133
+
134
+ # Args:
135
+ # level: Log level (INFO, WARNING, ERROR, etc.)
136
+ # message: The log message
137
+ # extra: Additional information to log
138
+ # """
139
+ # log_entry = self._create_log_entry(
140
+ # level=level, message=message, event_type="security_event", **(extra or {})
141
+ # )
142
+ # self.collection.insert_one(log_entry)
143
+
144
+ # def _extract_status_code(self, response: Any) -> int:
145
+ # """
146
+ # Extract status code from a response object.
147
+
148
+ # Args:
149
+ # response: The framework-specific response object
150
+
151
+ # Returns:
152
+ # The status code or 0 if not found
153
+ # """
154
+ # try:
155
+ # if hasattr(response, "status_code"):
156
+ # return response.status_code
157
+ # if isinstance(response, dict) and "status_code" in response:
158
+ # return response["status_code"]
159
+ # except:
160
+ # pass
161
+ # return 0
162
+
163
+
164
+ # class AsyncMongoDBBackend(AsyncLoggingBackend):
165
+ # """
166
+ # Asynchronous MongoDB logging backend implementation.
167
+ # """
168
+
169
+ # def __init__(self, config: Dict[str, Any]):
170
+ # """
171
+ # Initialize the async MongoDB backend.
172
+
173
+ # Args:
174
+ # config: Configuration dictionary containing:
175
+ # - uri: MongoDB connection URI
176
+ # - database: Database name
177
+ # - collection: Collection name
178
+ # - username: Optional username for authentication
179
+ # - password: Optional password for authentication
180
+
181
+ # Raises:
182
+ # ImportError: If pymongo is not installed
183
+ # """
184
+ # if not PYMONGO_AVAILABLE:
185
+ # raise ImportError(
186
+ # "MongoDB backend requires pymongo. Install it with 'pip install pymongo'"
187
+ # )
188
+
189
+ # self.config = config
190
+ # self.client = None
191
+ # self.collection = None
192
+ # self.setup(config)
193
+
194
+ # def setup(self, config: Dict[str, Any]) -> None:
195
+ # """
196
+ # Set up the async MongoDB client and collection.
197
+
198
+ # Args:
199
+ # config: Configuration dictionary
200
+ # """
201
+ # # Build connection URI if not provided
202
+ # if "uri" not in config:
203
+ # auth_str = ""
204
+ # if "username" in config and "password" in config:
205
+ # auth_str = f"{config['username']}:{config['password']}@"
206
+ # config["uri"] = f"mongodb://{auth_str}{config['host']}:{config['port']}"
207
+
208
+ # self.client = AsyncMongoClient(config["uri"])
209
+ # db = self.client[config["database"]]
210
+ # self.collection = db[config["collection"]]
211
+
212
+ # # Create indexes for efficient querying
213
+ # self.collection.create_index("timestamp")
214
+ # self.collection.create_index("level")
215
+ # self.collection.create_index("ip")
216
+ # self.collection.create_index("event_type")
217
+ # self.collection.create_index([("timestamp", -1)])
218
+
219
+ # def _create_log_entry(self, **kwargs) -> Dict[str, Any]:
220
+ # """
221
+ # Create a standardized log entry.
222
+
223
+ # Returns:
224
+ # Dict containing the log entry
225
+ # """
226
+ # return {"timestamp": int(time.time() * 1000), **kwargs} # milliseconds
227
+
228
+ # async def log_request(self, request_info: Dict[str, Any], response: Any) -> None:
229
+ # """
230
+ # Log a request to MongoDB asynchronously.
231
+
232
+ # Args:
233
+ # request_info: Dict with request information
234
+ # response: The framework-specific response object
235
+ # """
236
+ # log_entry = self._create_log_entry(
237
+ # level="INFO",
238
+ # ip=request_info.get("ip", "unknown"),
239
+ # method=request_info.get("method", "unknown"),
240
+ # path=request_info.get("path", "unknown"),
241
+ # status_code=self._extract_status_code(response),
242
+ # user_agent=request_info.get("user_agent", "unknown"),
243
+ # event_type="request",
244
+ # )
245
+ # await self.collection.insert_one(log_entry)
246
+
247
+ # async def log_blocked_request(
248
+ # self, request_info: Dict[str, Any], block_type: str, reason: str
249
+ # ) -> None:
250
+ # """
251
+ # Log a blocked request to MongoDB asynchronously.
252
+
253
+ # Args:
254
+ # request_info: Dict with request information
255
+ # block_type: Type of block (IP filter, rate limit, etc.)
256
+ # reason: Reason for blocking
257
+ # """
258
+ # log_entry = self._create_log_entry(
259
+ # level="WARNING",
260
+ # ip=request_info.get("ip", "unknown"),
261
+ # method=request_info.get("method", "unknown"),
262
+ # path=request_info.get("path", "unknown"),
263
+ # block_type=block_type,
264
+ # reason=reason,
265
+ # user_agent=request_info.get("user_agent", "unknown"),
266
+ # event_type="blocked_request",
267
+ # )
268
+ # await self.collection.insert_one(log_entry)
269
+
270
+ # async def log_security_event(
271
+ # self, level: str, message: str, extra: Optional[Dict[str, Any]] = None
272
+ # ) -> None:
273
+ # """
274
+ # Log a security event to MongoDB asynchronously.
275
+
276
+ # Args:
277
+ # level: Log level (INFO, WARNING, ERROR, etc.)
278
+ # message: The log message
279
+ # extra: Additional information to log
280
+ # """
281
+ # log_entry = self._create_log_entry(
282
+ # level=level, message=message, event_type="security_event", **(extra or {})
283
+ # )
284
+ # await self.collection.insert_one(log_entry)
285
+
286
+ # def _extract_status_code(self, response: Any) -> int:
287
+ # """
288
+ # Extract status code from a response object.
289
+
290
+ # Args:
291
+ # response: The framework-specific response object
292
+
293
+ # Returns:
294
+ # The status code or 0 if not found
295
+ # """
296
+ # try:
297
+ # if hasattr(response, "status_code"):
298
+ # return response.status_code
299
+ # if isinstance(response, dict) and "status_code" in response:
300
+ # return response["status_code"]
301
+ # except:
302
+ # pass
303
+ # return 0
@@ -0,0 +1,117 @@
1
+ """
2
+ Base logging interface for PyWebGuard.
3
+ """
4
+
5
+ from abc import ABC, abstractmethod
6
+ from typing import Dict, Any, Optional
7
+ import logging
8
+
9
+
10
+ class LoggingBackend(ABC):
11
+ """
12
+ Abstract base class for synchronous logging backends.
13
+ """
14
+
15
+ @abstractmethod
16
+ def setup(self, config: Any) -> None:
17
+ """
18
+ Set up the logging backend with the given configuration.
19
+
20
+ Args:
21
+ config: Configuration specific to the backend
22
+ """
23
+ pass
24
+
25
+ @abstractmethod
26
+ def log_request(self, request_info: Dict[str, Any], response: Any) -> None:
27
+ """
28
+ Log a request.
29
+
30
+ Args:
31
+ request_info: Dict with request information
32
+ response: The framework-specific response object
33
+ """
34
+ pass
35
+
36
+ @abstractmethod
37
+ def log_blocked_request(
38
+ self, request_info: Dict[str, Any], block_type: str, reason: str
39
+ ) -> None:
40
+ """
41
+ Log a blocked request.
42
+
43
+ Args:
44
+ request_info: Dict with request information
45
+ block_type: Type of block (IP filter, rate limit, etc.)
46
+ reason: Reason for blocking
47
+ """
48
+ pass
49
+
50
+ @abstractmethod
51
+ def log_security_event(
52
+ self, level: str, message: str, extra: Optional[Dict[str, Any]] = None
53
+ ) -> None:
54
+ """
55
+ Log a security event.
56
+
57
+ Args:
58
+ level: Log level (INFO, WARNING, ERROR, etc.)
59
+ message: The log message
60
+ extra: Additional information to log
61
+ """
62
+ pass
63
+
64
+
65
+ class AsyncLoggingBackend(ABC):
66
+ """
67
+ Abstract base class for asynchronous logging backends.
68
+ """
69
+
70
+ @abstractmethod
71
+ def setup(self, config: Any) -> None:
72
+ """
73
+ Set up the logging backend with the given configuration.
74
+
75
+ Args:
76
+ config: Configuration specific to the backend
77
+ """
78
+ pass
79
+
80
+ @abstractmethod
81
+ async def log_request(self, request_info: Dict[str, Any], response: Any) -> None:
82
+ """
83
+ Log a request asynchronously.
84
+
85
+ Args:
86
+ request_info: Dict with request information
87
+ response: The framework-specific response object
88
+ """
89
+ pass
90
+
91
+ @abstractmethod
92
+ async def log_blocked_request(
93
+ self, request_info: Dict[str, Any], block_type: str, reason: str
94
+ ) -> None:
95
+ """
96
+ Log a blocked request asynchronously.
97
+
98
+ Args:
99
+ request_info: Dict with request information
100
+ block_type: Type of block (IP filter, rate limit, etc.)
101
+ reason: Reason for blocking
102
+ """
103
+ pass
104
+
105
+ @abstractmethod
106
+ async def log_security_event(
107
+ self, level: str, message: str, extra: Optional[Dict[str, Any]] = None
108
+ ) -> None:
109
+ """
110
+ Log a security event asynchronously.
111
+
112
+ Args:
113
+ level: Log level (INFO, WARNING, ERROR, etc.)
114
+ message: The log message
115
+ extra: Additional information to log
116
+ """
117
+ pass