http_user_agent.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """
  4. Method ``http_user_agent``
  5. --------------------------
  6. The ``http_user_agent`` method evaluates a request as the request of a bot if
  7. the User-Agent_ header is unset or matches the regular expression
  8. :py:obj:`USER_AGENT`.
  9. .. _User-Agent:
  10. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
  11. """
  12. from typing import Optional, Tuple
  13. import re
  14. import flask
  15. USER_AGENT = (
  16. r'('
  17. + r'unknown'
  18. + r'|[Cc][Uu][Rr][Ll]|[wW]get|Scrapy|splash|JavaFX|FeedFetcher|python-requests|Go-http-client|Java|Jakarta|okhttp'
  19. + r'|HttpClient|Jersey|Python|libwww-perl|Ruby|SynHttpClient|UniversalFeedParser|Googlebot|GoogleImageProxy'
  20. + r'|bingbot|Baiduspider|yacybot|YandexMobileBot|YandexBot|Yahoo! Slurp|MJ12bot|AhrefsBot|archive.org_bot|msnbot'
  21. + r'|MJ12bot|SeznamBot|linkdexbot|Netvibes|SMTBot|zgrab|James BOT|Sogou|Abonti|Pixray|Spinn3r|SemrushBot|Exabot'
  22. + r'|ZmEu|BLEXBot|bitlybot'
  23. # unmaintained Farside instances
  24. + r'|'
  25. + re.escape(r'Mozilla/5.0 (compatible; Farside/0.1.0; +https://farside.link)')
  26. # other bots and client to block
  27. + '|.*PetalBot.*'
  28. + r')'
  29. )
  30. """Regular expression that matches to User-Agent_ from known *bots*"""
  31. _regexp = None
  32. def regexp_user_agent():
  33. global _regexp # pylint: disable=global-statement
  34. if not _regexp:
  35. _regexp = re.compile(USER_AGENT)
  36. return _regexp
  37. def filter_request(request: flask.Request) -> Optional[Tuple[int, str]]:
  38. user_agent = request.headers.get('User-Agent', 'unknown')
  39. if regexp_user_agent().match(user_agent):
  40. return (
  41. 429,
  42. f"bot detected, HTTP header User-Agent: {user_agent}",
  43. )
  44. return None