2021-12-19 10:01:50 +00:00
|
|
|
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
# lint: pylint
|
|
|
|
# pyright: basic
|
2023-05-23 16:16:37 +00:00
|
|
|
"""see :ref:`limiter src`"""
|
2021-12-19 10:01:50 +00:00
|
|
|
|
2023-05-23 16:16:37 +00:00
|
|
|
import flask
|
2021-12-19 10:01:50 +00:00
|
|
|
|
2022-11-11 20:58:32 +00:00
|
|
|
from searx import redisdb
|
2023-02-12 11:14:15 +00:00
|
|
|
from searx.plugins import logger
|
2023-05-23 16:16:37 +00:00
|
|
|
from searx.botdetection import limiter
|
|
|
|
from searx.botdetection import dump_request
|
2021-12-19 10:01:50 +00:00
|
|
|
|
|
|
|
name = "Request limiter"
|
|
|
|
description = "Limit the number of request"
|
|
|
|
default_on = False
|
|
|
|
preference_section = 'service'
|
2023-04-03 17:36:28 +00:00
|
|
|
|
2023-05-23 16:16:37 +00:00
|
|
|
logger = logger.getChild('limiter')
|
2023-02-12 11:14:15 +00:00
|
|
|
|
|
|
|
|
2023-05-23 16:16:37 +00:00
|
|
|
def pre_request():
|
|
|
|
"""See :ref:`flask.Flask.before_request`"""
|
2021-12-19 10:01:50 +00:00
|
|
|
|
2023-05-23 16:16:37 +00:00
|
|
|
val = limiter.filter_request(flask.request)
|
|
|
|
if val is not None:
|
|
|
|
http_status, msg = val
|
|
|
|
client_ip = flask.request.headers.get('X-Forwarded-For', '<unknown>')
|
|
|
|
logger.error("BLOCK (IP %s): %s" % (client_ip, msg))
|
|
|
|
return 'Too Many Requests', http_status
|
2021-12-19 10:01:50 +00:00
|
|
|
|
2023-05-23 16:16:37 +00:00
|
|
|
logger.debug("OK: %s" % dump_request(flask.request))
|
2022-04-06 21:46:11 +00:00
|
|
|
return None
|
2021-12-19 10:01:50 +00:00
|
|
|
|
|
|
|
|
2023-05-23 16:16:37 +00:00
|
|
|
def init(app: flask.Flask, settings) -> bool:
|
2021-12-19 10:01:50 +00:00
|
|
|
if not settings['server']['limiter']:
|
|
|
|
return False
|
2022-07-15 16:38:32 +00:00
|
|
|
if not redisdb.client():
|
2023-05-23 16:16:37 +00:00
|
|
|
logger.error("The limiter requires Redis")
|
2021-12-19 10:01:50 +00:00
|
|
|
return False
|
2023-05-26 15:24:43 +00:00
|
|
|
limiter.init_cfg(logger)
|
2022-04-06 21:46:11 +00:00
|
|
|
app.before_request(pre_request)
|
2021-12-19 10:01:50 +00:00
|
|
|
return True
|