WhakerPy 2.4__py3-none-any.whl → 3.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.
whakerpy/__init__.py CHANGED
@@ -25,6 +25,6 @@ from .httpd import *
25
25
  from .messages import error
26
26
  from .webapp import *
27
27
 
28
- __version__ = "2.4"
28
+ __version__ = "3.0"
29
29
  ___author__ = "Brigitte Bigi"
30
30
  __copyright__ = "Copyright (C) 2023-2026 Brigitte Bigi, CNRS, Laboratoire Parole et Langage, Aix-en-Provence, France"
@@ -40,7 +40,10 @@ from .hutils import HTTPDHandlerUtils
40
40
  from .handler import HTTPDHandler
41
41
  from .hserver import BaseHTTPDServer
42
42
  from .hresponse import BaseResponseRecipe
43
+ from .hbanlist import BanList
43
44
  from .hblacklist import Blacklist
45
+ from .hblacklist import BlackListAgent
46
+ from .hblacklist import BlackListPath
44
47
  from .hsignedurl import SignedURL
45
48
  from .hpolicy import HTTPDPolicy
46
49
 
@@ -54,6 +57,9 @@ __all__ = (
54
57
  "HTTPDHandlerUtils",
55
58
  "BaseHTTPDServer",
56
59
  "Blacklist",
60
+ "BlackListAgent",
61
+ "BlackListPath",
62
+ "BanList",
57
63
  "SignedURL",
58
64
  "HTTPDPolicy"
59
65
  )
whakerpy/httpd/handler.py CHANGED
@@ -72,7 +72,6 @@ class HTTPDHandler(http.server.BaseHTTPRequestHandler):
72
72
  - 403: Forbidden
73
73
  - 404: Not Found -- also used for "expired"
74
74
  - 410: Gone
75
- - 418: I'm a teapot
76
75
 
77
76
  """
78
77
 
@@ -140,6 +139,28 @@ class HTTPDHandler(http.server.BaseHTTPRequestHandler):
140
139
 
141
140
  # -----------------------------------------------------------------------
142
141
 
142
+ def _static_content(self, handler_utils: HTTPDHandlerUtils) -> tuple:
143
+ """Return the content of the requested static file and its status.
144
+
145
+ The server policy is asked before the file is read, so that a file
146
+ out of the served paths is refused.
147
+
148
+ :param handler_utils: (HTTPDhandlerUtils)
149
+ :return: (tuple) (content, status, mime_type)
150
+
151
+ """
152
+ filepath = self.path[1:]
153
+
154
+ if hasattr(self.server, 'policy_check_file') is True:
155
+ allowed, content, status, mime = self.server.policy_check_file(filepath)
156
+ if allowed is False:
157
+ return content, status, mime
158
+
159
+ content, status = handler_utils.static_content(filepath)
160
+ return content, status, HTTPDHandlerUtils.get_mime_type(self.path)
161
+
162
+ # -----------------------------------------------------------------------
163
+
143
164
  def _bakery(self, handler_utils: HTTPDHandlerUtils, events: dict, mime_type: str) -> tuple:
144
165
  """Process the events and return the html page content or json data and status.
145
166
 
@@ -206,13 +227,13 @@ class HTTPDHandler(http.server.BaseHTTPRequestHandler):
206
227
  allowed = True
207
228
  if hasattr(self.server, 'policy_check') is True:
208
229
  allowed, content, status, mime = self.server.policy_check(
209
- self.path, query_string, self.headers)
230
+ self.path, query_string, self.headers, self.client_address[0])
210
231
 
211
232
  if allowed is True:
212
233
  # 3) Serve content
213
234
  # Static file first (even if HTML) when the file exists.
214
235
  if os.path.exists(handler_utils.get_path()) or os.path.exists(handler_utils.get_path()[1:]):
215
- content, status = handler_utils.static_content(self.path[1:])
236
+ content, status, mime_type = self._static_content(handler_utils)
216
237
 
217
238
  # Dynamic HTML page generated by the server.
218
239
  elif mime_type == "text/html":
@@ -229,7 +250,7 @@ class HTTPDHandler(http.server.BaseHTTPRequestHandler):
229
250
 
230
251
  # Unknown mime type: try to get a static file anyway.
231
252
  else:
232
- content, status = handler_utils.static_content(self.path[1:])
253
+ content, status, mime_type = self._static_content(handler_utils)
233
254
  else:
234
255
  mime_type = mime
235
256
 
@@ -264,16 +285,19 @@ class HTTPDHandler(http.server.BaseHTTPRequestHandler):
264
285
 
265
286
  # 2) Check policy compliance
266
287
  allowed = True
288
+ mime_type = "text/html"
267
289
  if hasattr(self.server, 'policy_check') is True:
268
290
  allowed, content, status, mime = self.server.policy_check(
269
- self.path, query_string, self.headers)
291
+ self.path, query_string, self.headers, self.client_address[0])
270
292
 
271
293
  if allowed is True:
272
294
  # 3) Process POST body and build the dynamic page.
273
295
  events, accept = handler_utils.process_post(self.rfile)
274
296
  content, status = self._bakery(handler_utils, events, accept)
297
+ else:
298
+ mime_type = mime
275
299
 
276
- self._response(content, status.code, "text/html")
300
+ self._response(content, status.code, mime_type)
277
301
 
278
302
  # -----------------------------------------------------------------------
279
303
 
@@ -0,0 +1,219 @@
1
+ # -*- coding: UTF-8 -*-
2
+ """
3
+ :filename: whakerpy.httpd.hbanlist.py
4
+ :author: Brigitte Bigi
5
+ :contact: contact@sppas.org
6
+ :summary: Manager of a temporary list of client addresses to be rejected.
7
+
8
+ .. _This file is part of WhakerPy: https://whakerpy.sourceforge.io
9
+ ..
10
+ -------------------------------------------------------------------------
11
+
12
+ Copyright (C) 2023-2026 Brigitte Bigi, CNRS
13
+ Laboratoire Parole et Langage, Aix-en-Provence, France
14
+
15
+ This program is free software: you can redistribute it and/or modify
16
+ it under the terms of the GNU Affero General Public License as published by
17
+ the Free Software Foundation, either version 3 of the License, or
18
+ (at your option) any later version.
19
+
20
+ This program is distributed in the hope that it will be useful,
21
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
22
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23
+ GNU Affero General Public License for more details.
24
+
25
+ You should have received a copy of the GNU Affero General Public License
26
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
27
+
28
+ This banner notice must not be removed.
29
+
30
+ -------------------------------------------------------------------------
31
+
32
+ """
33
+
34
+ from __future__ import annotations
35
+ import os
36
+ import time
37
+ import logging
38
+ import tempfile
39
+
40
+ # ---------------------------------------------------------------------------
41
+
42
+
43
+ class BanList:
44
+ """Manager of a temporary list of client addresses to be rejected.
45
+
46
+ An address is recorded when a request met a forbidden URL path, and it
47
+ is rejected during the duration given by the configuration.
48
+
49
+ The list is stored in a file, so that the processes of a server share
50
+ it and it survives a reload. A line of the file is an address and the
51
+ time it was recorded:
52
+
53
+ 192.0.2.4 1761220000.0
54
+
55
+ An address matches when it is written in the file and its line is not
56
+ older than the duration. The comparison is exact: an address is never a
57
+ part of another one.
58
+
59
+ """
60
+
61
+ def __init__(self):
62
+ """Create a ban list with no file and no duration.
63
+
64
+ """
65
+ self.__filename = ""
66
+ self.__duration = 0
67
+
68
+ # -----------------------------------------------------------------------
69
+
70
+ def configure(self, config: dict, json_key: str = "banlist") -> dict:
71
+ """Configure the ban list.
72
+
73
+ The section of the given key is a dict with two required values:
74
+ "file" is the path of the file where the addresses are stored, and
75
+ "duration" is the number of seconds an address is rejected.
76
+
77
+ If the key is missing, the ban list is disabled.
78
+
79
+ :param config: (dict) Configuration dictionary.
80
+ :param json_key: (str) Key of the ban list dict in dict.
81
+ :raises: TypeError: the section is not a dict.
82
+ :raises: ValueError: a required value is missing or invalid.
83
+ :return: (dict) Loaded settings: {"file": str, "duration": int}.
84
+
85
+ """
86
+ _cfg = config.get(json_key, None)
87
+
88
+ # If missing: ban list disabled => reset and return empty config.
89
+ if _cfg is None:
90
+ self.__filename = ""
91
+ self.__duration = 0
92
+ return {"file": "", "duration": 0}
93
+
94
+ if isinstance(_cfg, dict) is False:
95
+ raise TypeError(f"JSON key '{json_key}' must be a dict.")
96
+
97
+ _filename = _cfg.get("file", "")
98
+ if type(_filename) is not str or len(_filename) == 0:
99
+ raise ValueError(f"{json_key}.file must be a non-empty string.")
100
+
101
+ _duration = _cfg.get("duration", 0)
102
+ if isinstance(_duration, int) is False or _duration <= 0:
103
+ raise ValueError(f"{json_key}.duration must be a number of seconds.")
104
+
105
+ self.__filename = _filename
106
+ self.__duration = _duration
107
+
108
+ return {"file": _filename, "duration": _duration}
109
+
110
+ # -----------------------------------------------------------------------
111
+
112
+ def match(self, address: str) -> bool:
113
+ """Return True if the given address is banned.
114
+
115
+ The addresses that expired are dropped from the file by this
116
+ reading, so none of them is kept longer than the duration.
117
+
118
+ :param address: (str) The address of a client.
119
+ :raises: TypeError: address is not a string.
120
+ :return: (bool) True if the address was recorded and did not expire.
121
+
122
+ """
123
+ if type(address) is not str:
124
+ raise TypeError("Address must be a string.")
125
+ if len(self.__filename) == 0 or len(address) == 0:
126
+ return False
127
+
128
+ return address in self.__read()
129
+
130
+ # -----------------------------------------------------------------------
131
+
132
+ def add(self, address: str) -> None:
133
+ """Record the given address for the configured duration.
134
+
135
+ The addresses that expired are dropped from the file.
136
+
137
+ :param address: (str) The address of a client.
138
+ :raises: TypeError: address is not a string.
139
+
140
+ """
141
+ if type(address) is not str:
142
+ raise TypeError("Address must be a string.")
143
+ if len(self.__filename) == 0 or len(address) == 0:
144
+ return
145
+
146
+ entries = self.__read()
147
+ entries[address] = time.time()
148
+ self.__write(entries)
149
+ logging.info("Banned address '" + address + "' for "
150
+ + str(self.__duration) + " seconds")
151
+
152
+ # -----------------------------------------------------------------------
153
+ # Private
154
+ # -----------------------------------------------------------------------
155
+
156
+ def __read(self) -> dict:
157
+ """Return the addresses of the file that did not expire.
158
+
159
+ The file is written back as soon as a reading finds a line it does
160
+ not keep, so an expired address does not survive that reading. A
161
+ file with nothing to drop is left untouched.
162
+
163
+ :return: (dict) key=address, value=time it was recorded.
164
+
165
+ """
166
+ if os.path.exists(self.__filename) is False:
167
+ return dict()
168
+
169
+ oldest = time.time() - self.__duration
170
+ entries = dict()
171
+ nb_lines = 0
172
+ try:
173
+ with open(self.__filename, "r", encoding="utf-8") as fp:
174
+ for line in fp:
175
+ nb_lines += 1
176
+ items = line.split()
177
+ if len(items) != 2:
178
+ continue
179
+ try:
180
+ recorded = float(items[1])
181
+ except ValueError:
182
+ continue
183
+ if recorded > oldest:
184
+ entries[items[0]] = recorded
185
+ except OSError as e:
186
+ logging.error("Ban list file can't be read: " + str(e))
187
+ return entries
188
+
189
+ if len(entries) < nb_lines:
190
+ self.__write(entries)
191
+
192
+ return entries
193
+
194
+ # -----------------------------------------------------------------------
195
+
196
+ def __write(self, entries: dict) -> None:
197
+ """Write the given addresses in the file.
198
+
199
+ The file is written aside and moved into place, so that a reader
200
+ never gets an incomplete content.
201
+
202
+ :param entries: (dict) key=address, value=time it was recorded.
203
+
204
+ """
205
+ folder = os.path.dirname(self.__filename)
206
+ if len(folder) == 0:
207
+ folder = "."
208
+
209
+ temporary = ""
210
+ try:
211
+ fd, temporary = tempfile.mkstemp(dir=folder)
212
+ with os.fdopen(fd, "w", encoding="utf-8") as fp:
213
+ for address in entries:
214
+ fp.write(address + " " + str(entries[address]) + "\n")
215
+ os.replace(temporary, self.__filename)
216
+ except OSError as e:
217
+ logging.error("Ban list file can't be written: " + str(e))
218
+ if len(temporary) > 0 and os.path.exists(temporary) is True:
219
+ os.remove(temporary)
@@ -2,7 +2,7 @@
2
2
  :filename: whakerpy.httpd.hblacklist.py
3
3
  :author: Brigitte Bigi
4
4
  :contact: contact@sppas.org
5
- :summary: Manager of a list of websites to be blacklisted.
5
+ :summary: Managers of the lists of user agents and URL paths to be rejected.
6
6
 
7
7
  ..
8
8
  -------------------------------------------------------------------------
@@ -38,29 +38,21 @@ import logging
38
38
 
39
39
 
40
40
  class Blacklist:
41
- """Manager of a list of blacklisted websites.
41
+ """Manager of a list of entries to be rejected.
42
42
 
43
- A blacklist is a set of URL paths that can be blacklisted by a website,
44
- managed as a persistent set of URL paths to be rejected.
43
+ A blacklist is a set of entries, each one a plain string, configured
44
+ from a dictionary or loaded from a file. This class is the base of the
45
+ blacklists of the package: what an entry is tested against, and with
46
+ which rule, is the matter of each subclass.
45
47
 
46
- The blacklist stores URL paths as strings, for example:
47
- - /bot.html
48
- - /admin/
49
- - /foo/bar
50
-
51
- A match can be:
52
- - exact match
53
- - parent-path match
54
-
55
- Example:
56
- If '/admin' is in the blacklist, then '/admin', '/admin/', and
57
- '/admin/page.html' are considered blacklisted.
48
+ BlackListAgent tests an entry against a User-Agent header.
49
+ BlackListPath tests an entry against a URL path.
58
50
 
59
51
  """
60
52
 
61
53
  def __init__(self) -> None:
62
54
  """Create an empty blacklist."""
63
- self.__blacklist = set()
55
+ self._blacklist = set()
64
56
 
65
57
  # -----------------------------------------------------------------------
66
58
 
@@ -82,7 +74,7 @@ class Blacklist:
82
74
  out.add(it)
83
75
  logging.info("Blacklisted entry '" + it + "'")
84
76
 
85
- self.__blacklist = out
77
+ self._blacklist = out
86
78
  return len(out)
87
79
 
88
80
  # -----------------------------------------------------------------------
@@ -101,7 +93,7 @@ class Blacklist:
101
93
  if type(value) is not str:
102
94
  raise TypeError("Value must be a string.")
103
95
 
104
- for entry in self.__blacklist:
96
+ for entry in self._blacklist:
105
97
  if entry in value:
106
98
  return True
107
99
 
@@ -139,13 +131,13 @@ class Blacklist:
139
131
 
140
132
  def __contains__(self, item):
141
133
  """Return True if the given URL path exists in the blacklist."""
142
- return item in self.__blacklist
134
+ return item in self._blacklist
143
135
 
144
136
  def __str__(self):
145
- return str(self.__blacklist)
137
+ return str(self._blacklist)
146
138
 
147
139
  def __repr__(self):
148
- return "Blacklist: " + str(self.__blacklist)
140
+ return self.__class__.__name__ + ": " + str(self._blacklist)
149
141
 
150
142
  # -----------------------------------------------------------------------
151
143
  # Private
@@ -159,7 +151,7 @@ class Blacklist:
159
151
  if len(s) == 0 or s.startswith("#"):
160
152
  continue
161
153
  items.add(s)
162
- self.__blacklist = items
154
+ self._blacklist = items
163
155
  return len(items)
164
156
 
165
157
  # -----------------------------------------------------------------------
@@ -182,3 +174,60 @@ class Blacklist:
182
174
  raise TypeError("JSON key 'WhakerPy' must be a dict.")
183
175
 
184
176
  return self.configure(_section)
177
+
178
+ # ---------------------------------------------------------------------------
179
+
180
+
181
+ class BlackListAgent(Blacklist):
182
+ """Manager of a list of user agents to be rejected.
183
+
184
+ An entry is a plain string token, for example 'SemrushBot'. The rule is
185
+ the one of the base class, a substring search, because the name of an
186
+ agent is written inside a longer header value.
187
+
188
+ """
189
+
190
+ # ---------------------------------------------------------------------------
191
+
192
+
193
+ class BlackListPath(Blacklist):
194
+ """Manager of a list of URL paths to be rejected.
195
+
196
+ An entry is a folder name, a file name or an extension, written the way
197
+ it appears in the path, for example:
198
+ - /wp-login.php
199
+ - /.git/
200
+ - .php
201
+
202
+ A match can be:
203
+ - exact match
204
+ - parent-path match
205
+ - extension match
206
+
207
+ Example:
208
+ If '/admin' is in the blacklist, then '/admin', '/admin/' and
209
+ '/admin/page.html' are considered blacklisted. If '.php' is in the
210
+ blacklist, then '/index.php' and '/wp/admin.php' are too.
211
+
212
+ """
213
+
214
+ def match(self, value: str) -> bool:
215
+ """Override. Return True if an entry starts or ends the given path.
216
+
217
+ The middle of a path is never tested: an entry rejects the path it
218
+ names, and nothing else.
219
+
220
+ :param value: (str) A URL path to test, without its query string.
221
+ :return: (bool) True if blacklisted, False otherwise.
222
+
223
+ """
224
+ if type(value) is not str:
225
+ raise TypeError("Value must be a string.")
226
+
227
+ for entry in self._blacklist:
228
+ if value.startswith(entry) is True:
229
+ return True
230
+ if value.endswith(entry) is True:
231
+ return True
232
+
233
+ return False