limiter.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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. from pathlib import Path
  29. import flask
  30. import pytomlpp as toml
  31. from searx.tools import config
  32. from searx.botdetection import (
  33. http_accept,
  34. http_accept_encoding,
  35. http_accept_language,
  36. http_connection,
  37. http_user_agent,
  38. ip_limit,
  39. )
  40. LIMITER_CFG_SCHEMA = Path(__file__).parent / "limiter.toml"
  41. """Base configuration (schema) of the botdetection."""
  42. LIMITER_CFG = Path('/etc/searxng/limiter.toml')
  43. """Lokal Limiter configuration."""
  44. CFG_DEPRECATED = {
  45. # "dummy.old.foo": "config 'dummy.old.foo' exists only for tests. Don't use it in your real project config."
  46. }
  47. CFG = config.Config({}, {})
  48. def init_cfg(log):
  49. global CFG # pylint: disable=global-statement
  50. CFG = config.Config(cfg_schema=toml.load(LIMITER_CFG_SCHEMA), deprecated=CFG_DEPRECATED)
  51. if not LIMITER_CFG.exists():
  52. log.warning("missing config file: %s", LIMITER_CFG)
  53. return
  54. log.warning("load config file: %s", LIMITER_CFG)
  55. try:
  56. upd_cfg = toml.load(LIMITER_CFG)
  57. except toml.DecodeError as exc:
  58. msg = str(exc).replace('\t', '').replace('\n', ' ')
  59. log.error("%s: %s", LIMITER_CFG, msg)
  60. raise
  61. is_valid, issue_list = CFG.validate(upd_cfg)
  62. for msg in issue_list:
  63. log.error(str(msg))
  64. if not is_valid:
  65. raise TypeError(f"schema of {LIMITER_CFG} is invalid, can't cutomize limiter configuration from!")
  66. CFG.update(upd_cfg)
  67. def filter_request(request: flask.Request) -> Optional[Tuple[int, str]]:
  68. if request.path == '/healthz':
  69. return None
  70. for func in [
  71. http_user_agent,
  72. ]:
  73. val = func.filter_request(request, CFG)
  74. if val is not None:
  75. return val
  76. if request.path == '/search':
  77. for func in [
  78. http_accept,
  79. http_accept_encoding,
  80. http_accept_language,
  81. http_connection,
  82. http_user_agent,
  83. ip_limit,
  84. ]:
  85. val = func.filter_request(request, CFG)
  86. if val is not None:
  87. return val
  88. return None