limiter.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """.. _limiter src:
  4. Limiter
  5. =======
  6. .. sidebar:: info
  7. The limiter requires a :ref:`Redis <settings redis>` database.
  8. Bot protection / IP rate limitation. The intention of rate limitation is to
  9. limit suspicious requests from an IP. The motivation behind this is the fact
  10. that SearXNG passes through requests from bots and is thus classified as a bot
  11. itself. As a result, the SearXNG engine then receives a CAPTCHA or is blocked
  12. by the search engine (the origin) in some other way.
  13. To avoid blocking, the requests from bots to SearXNG must also be blocked, this
  14. is the task of the limiter. To perform this task, the limiter uses the methods
  15. from the :py:obj:`searx.botdetection`.
  16. To enable the limiter activate:
  17. .. code:: yaml
  18. server:
  19. ...
  20. limiter: true # rate limit the number of request on the instance, block some bots
  21. and set the redis-url connection. Check the value, it depends on your redis DB
  22. (see :ref:`settings redis`), by example:
  23. .. code:: yaml
  24. redis:
  25. url: unix:///usr/local/searxng-redis/run/redis.sock?db=0
  26. """
  27. from typing import Optional, Tuple
  28. import flask
  29. from searx.botdetection import (
  30. http_accept,
  31. http_accept_encoding,
  32. http_accept_language,
  33. http_connection,
  34. http_user_agent,
  35. ip_limit,
  36. )
  37. def filter_request(request: flask.Request) -> Optional[Tuple[int, str]]:
  38. if request.path == '/healthz':
  39. return None
  40. for func in [
  41. http_user_agent,
  42. ]:
  43. val = func.filter_request(request)
  44. if val is not None:
  45. return val
  46. if request.path == '/search':
  47. for func in [
  48. http_accept,
  49. http_accept_encoding,
  50. http_accept_language,
  51. http_connection,
  52. http_user_agent,
  53. ip_limit,
  54. ]:
  55. val = func.filter_request(request)
  56. if val is not None:
  57. return val
  58. return None