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