impl.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. import gc
  3. import typing
  4. import types
  5. import functools
  6. import itertools
  7. from time import time
  8. from timeit import default_timer
  9. from urllib.parse import urlparse
  10. import re
  11. import httpx
  12. from searx import network, logger
  13. from searx.utils import gen_useragent, detect_language
  14. from searx.results import ResultContainer
  15. from searx.search.models import SearchQuery, EngineRef
  16. from searx.search.processors import EngineProcessor
  17. from searx.metrics import counter_inc
  18. logger = logger.getChild('searx.search.checker')
  19. HTML_TAGS = [
  20. # fmt: off
  21. 'embed', 'iframe', 'object', 'param', 'picture', 'source', 'svg', 'math', 'canvas', 'noscript', 'script',
  22. 'del', 'ins', 'area', 'audio', 'img', 'map', 'track', 'video', 'a', 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite',
  23. 'code', 'data', 'dfn', 'em', 'i', 'kdb', 'mark', 'q', 'rb', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'small',
  24. 'span', 'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr', 'style', 'blockquote', 'dd', 'div', 'dl', 'dt',
  25. 'figcaption', 'figure', 'hr', 'li', 'ol', 'p', 'pre', 'ul', 'button', 'datalist', 'fieldset', 'form', 'input',
  26. 'label', 'legend', 'meter', 'optgroup', 'option', 'output', 'progress', 'select', 'textarea', 'applet',
  27. 'frame', 'frameset'
  28. # fmt: on
  29. ]
  30. def get_check_no_html():
  31. rep = ['<' + tag + '[^\>]*>' for tag in HTML_TAGS]
  32. rep += ['</' + tag + '>' for tag in HTML_TAGS]
  33. pattern = re.compile('|'.join(rep))
  34. def f(text):
  35. return pattern.search(text.lower()) is None
  36. return f
  37. _check_no_html = get_check_no_html()
  38. def _is_url(url):
  39. try:
  40. result = urlparse(url)
  41. except ValueError:
  42. return False
  43. if result.scheme not in ('http', 'https'):
  44. return False
  45. return True
  46. @functools.lru_cache(maxsize=8192)
  47. def _download_and_check_if_image(image_url: str) -> bool:
  48. """Download an URL and check if the Content-Type starts with "image/"
  49. This function should not be called directly: use _is_url_image
  50. otherwise the cache of functools.lru_cache contains data: URL which might be huge.
  51. """
  52. retry = 2
  53. while retry > 0:
  54. a = time()
  55. try:
  56. # use "image_proxy" (avoid HTTP/2)
  57. network.set_context_network_name('image_proxy')
  58. r, stream = network.stream(
  59. 'GET',
  60. image_url,
  61. timeout=10.0,
  62. allow_redirects=True,
  63. headers={
  64. 'User-Agent': gen_useragent(),
  65. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
  66. 'Accept-Language': 'en-US;q=0.5,en;q=0.3',
  67. 'Accept-Encoding': 'gzip, deflate, br',
  68. 'DNT': '1',
  69. 'Connection': 'keep-alive',
  70. 'Upgrade-Insecure-Requests': '1',
  71. 'Sec-GPC': '1',
  72. 'Cache-Control': 'max-age=0',
  73. },
  74. )
  75. r.close()
  76. if r.status_code == 200:
  77. is_image = r.headers.get('content-type', '').startswith('image/')
  78. else:
  79. is_image = False
  80. del r
  81. del stream
  82. return is_image
  83. except httpx.TimeoutException:
  84. logger.error('Timeout for %s: %i', image_url, int(time() - a))
  85. retry -= 1
  86. except httpx.HTTPError:
  87. logger.exception('Exception for %s', image_url)
  88. return False
  89. return False
  90. def _is_url_image(image_url) -> bool:
  91. """Normalize image_url"""
  92. if not isinstance(image_url, str):
  93. return False
  94. if image_url.startswith('//'):
  95. image_url = 'https:' + image_url
  96. if image_url.startswith('data:'):
  97. return image_url.startswith('data:image/')
  98. if not _is_url(image_url):
  99. return False
  100. return _download_and_check_if_image(image_url)
  101. def _search_query_to_dict(search_query: SearchQuery) -> typing.Dict[str, typing.Any]:
  102. return {
  103. 'query': search_query.query,
  104. 'lang': search_query.lang,
  105. 'pageno': search_query.pageno,
  106. 'safesearch': search_query.safesearch,
  107. 'time_range': search_query.time_range,
  108. }
  109. def _search_query_diff(
  110. sq1: SearchQuery, sq2: SearchQuery
  111. ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.Dict[str, typing.Any]]:
  112. param1 = _search_query_to_dict(sq1)
  113. param2 = _search_query_to_dict(sq2)
  114. common = {}
  115. diff = {}
  116. for k, value1 in param1.items():
  117. value2 = param2[k]
  118. if value1 == value2:
  119. common[k] = value1
  120. else:
  121. diff[k] = (value1, value2)
  122. return (common, diff)
  123. class TestResults:
  124. __slots__ = 'errors', 'logs', 'languages'
  125. def __init__(self):
  126. self.errors: typing.Dict[str, typing.List[str]] = {}
  127. self.logs: typing.Dict[str, typing.List[typing.Any]] = {}
  128. self.languages: typing.Set[str] = set()
  129. def add_error(self, test, message, *args):
  130. # message to self.errors
  131. errors_for_test = self.errors.setdefault(test, [])
  132. if message not in errors_for_test:
  133. errors_for_test.append(message)
  134. # (message, *args) to self.logs
  135. logs_for_test = self.logs.setdefault(test, [])
  136. if (message, *args) not in logs_for_test:
  137. logs_for_test.append((message, *args))
  138. def add_language(self, language):
  139. self.languages.add(language)
  140. @property
  141. def successful(self):
  142. return len(self.errors) == 0
  143. def __iter__(self):
  144. for test_name, errors in self.errors.items():
  145. for error in sorted(errors):
  146. yield (test_name, error)
  147. class ResultContainerTests:
  148. __slots__ = 'test_name', 'search_query', 'result_container', 'languages', 'stop_test', 'test_results'
  149. def __init__(
  150. self, test_results: TestResults, test_name: str, search_query: SearchQuery, result_container: ResultContainer
  151. ):
  152. self.test_name = test_name
  153. self.search_query = search_query
  154. self.result_container = result_container
  155. self.languages: typing.Set[str] = set()
  156. self.test_results = test_results
  157. self.stop_test = False
  158. @property
  159. def result_urls(self):
  160. results = self.result_container.get_ordered_results()
  161. return [result['url'] for result in results if 'url' in result]
  162. def _record_error(self, message: str, *args) -> None:
  163. sq = _search_query_to_dict(self.search_query)
  164. sqstr = ' '.join(['{}={!r}'.format(k, v) for k, v in sq.items()])
  165. self.test_results.add_error(self.test_name, message, *args, '(' + sqstr + ')')
  166. def _add_language(self, text: str) -> typing.Optional[str]:
  167. langStr = detect_language(text)
  168. if langStr:
  169. self.languages.add(langStr)
  170. self.test_results.add_language(langStr)
  171. return None
  172. def _check_result(self, result):
  173. if not _check_no_html(result.get('title', '')):
  174. self._record_error('HTML in title', repr(result.get('title', '')))
  175. if not _check_no_html(result.get('content', '')):
  176. self._record_error('HTML in content', repr(result.get('content', '')))
  177. if result.get('url') is None:
  178. self._record_error('url is None')
  179. self._add_language(result.get('title', ''))
  180. self._add_language(result.get('content', ''))
  181. template = result.get('template', 'default.html')
  182. if template == 'default.html':
  183. return
  184. if template == 'code.html':
  185. return
  186. if template == 'torrent.html':
  187. return
  188. if template == 'map.html':
  189. return
  190. if template == 'images.html':
  191. thumbnail_src = result.get('thumbnail_src')
  192. if thumbnail_src is not None:
  193. if not _is_url_image(thumbnail_src):
  194. self._record_error('thumbnail_src URL is invalid', thumbnail_src)
  195. elif not _is_url_image(result.get('img_src')):
  196. self._record_error('img_src URL is invalid', result.get('img_src'))
  197. if template == 'videos.html' and not _is_url_image(result.get('thumbnail')):
  198. self._record_error('thumbnail URL is invalid', result.get('img_src'))
  199. def _check_results(self, results: list):
  200. for result in results:
  201. self._check_result(result)
  202. def _check_answers(self, answers):
  203. for answer in answers:
  204. if not _check_no_html(answer):
  205. self._record_error('HTML in answer', answer)
  206. def _check_infoboxes(self, infoboxes):
  207. for infobox in infoboxes:
  208. if not _check_no_html(infobox.get('content', '')):
  209. self._record_error('HTML in infobox content', infobox.get('content', ''))
  210. self._add_language(infobox.get('content', ''))
  211. for attribute in infobox.get('attributes', {}):
  212. if not _check_no_html(attribute.get('value', '')):
  213. self._record_error('HTML in infobox attribute value', attribute.get('value', ''))
  214. def check_basic(self):
  215. if len(self.result_container.unresponsive_engines) > 0:
  216. for message in self.result_container.unresponsive_engines:
  217. self._record_error(message[1] + ' ' + (message[2] or ''))
  218. self.stop_test = True
  219. return
  220. results = self.result_container.get_ordered_results()
  221. if len(results) > 0:
  222. self._check_results(results)
  223. if len(self.result_container.answers) > 0:
  224. self._check_answers(self.result_container.answers)
  225. if len(self.result_container.infoboxes) > 0:
  226. self._check_infoboxes(self.result_container.infoboxes)
  227. def has_infobox(self):
  228. """Check the ResultContainer has at least one infobox"""
  229. if len(self.result_container.infoboxes) == 0:
  230. self._record_error('No infobox')
  231. def has_answer(self):
  232. """Check the ResultContainer has at least one answer"""
  233. if len(self.result_container.answers) == 0:
  234. self._record_error('No answer')
  235. def has_language(self, lang):
  236. """Check at least one title or content of the results is written in the `lang`.
  237. Detected using pycld3, may be not accurate"""
  238. if lang not in self.languages:
  239. self._record_error(lang + ' not found')
  240. def not_empty(self):
  241. """Check the ResultContainer has at least one answer or infobox or result"""
  242. result_types = set()
  243. results = self.result_container.get_ordered_results()
  244. if len(results) > 0:
  245. result_types.add('results')
  246. if len(self.result_container.answers) > 0:
  247. result_types.add('answers')
  248. if len(self.result_container.infoboxes) > 0:
  249. result_types.add('infoboxes')
  250. if len(result_types) == 0:
  251. self._record_error('No result')
  252. def one_title_contains(self, title: str):
  253. """Check one of the title contains `title` (case insensitive comparison)"""
  254. title = title.lower()
  255. for result in self.result_container.get_ordered_results():
  256. if title in result['title'].lower():
  257. return
  258. self._record_error(('{!r} not found in the title'.format(title)))
  259. class CheckerTests:
  260. __slots__ = 'test_results', 'test_name', 'result_container_tests_list'
  261. def __init__(
  262. self, test_results: TestResults, test_name: str, result_container_tests_list: typing.List[ResultContainerTests]
  263. ):
  264. self.test_results = test_results
  265. self.test_name = test_name
  266. self.result_container_tests_list = result_container_tests_list
  267. def unique_results(self):
  268. """Check the results of each ResultContainer is unique"""
  269. urls_list = [rct.result_urls for rct in self.result_container_tests_list]
  270. if len(urls_list[0]) > 0:
  271. # results on the first page
  272. for i, urls_i in enumerate(urls_list):
  273. for j, urls_j in enumerate(urls_list):
  274. if i < j and urls_i == urls_j:
  275. common, diff = _search_query_diff(
  276. self.result_container_tests_list[i].search_query,
  277. self.result_container_tests_list[j].search_query,
  278. )
  279. common_str = ' '.join(['{}={!r}'.format(k, v) for k, v in common.items()])
  280. diff1_str = ', '.join(['{}={!r}'.format(k, v1) for (k, (v1, v2)) in diff.items()])
  281. diff2_str = ', '.join(['{}={!r}'.format(k, v2) for (k, (v1, v2)) in diff.items()])
  282. self.test_results.add_error(
  283. self.test_name,
  284. 'results are identitical for {} and {} ({})'.format(diff1_str, diff2_str, common_str),
  285. )
  286. class Checker:
  287. __slots__ = 'processor', 'tests', 'test_results'
  288. def __init__(self, processor: EngineProcessor):
  289. self.processor = processor
  290. self.tests = self.processor.get_tests()
  291. self.test_results = TestResults()
  292. @property
  293. def engineref_list(self):
  294. engine_name = self.processor.engine_name
  295. engine_category = self.processor.engine.categories[0]
  296. return [EngineRef(engine_name, engine_category)]
  297. @staticmethod
  298. def search_query_matrix_iterator(engineref_list, matrix):
  299. p = []
  300. for name, values in matrix.items():
  301. if isinstance(values, (tuple, list)):
  302. l = [(name, value) for value in values]
  303. else:
  304. l = [(name, values)]
  305. p.append(l)
  306. for kwargs in itertools.product(*p):
  307. kwargs = {k: v for k, v in kwargs}
  308. query = kwargs['query']
  309. params = dict(kwargs)
  310. del params['query']
  311. yield SearchQuery(query, engineref_list, **params)
  312. def call_test(self, obj, test_description):
  313. if isinstance(test_description, (tuple, list)):
  314. method, args = test_description[0], test_description[1:]
  315. else:
  316. method = test_description
  317. args = ()
  318. if isinstance(method, str) and hasattr(obj, method):
  319. getattr(obj, method)(*args)
  320. elif isinstance(method, types.FunctionType):
  321. method(*args)
  322. else:
  323. self.test_results.add_error(
  324. obj.test_name,
  325. 'method {!r} ({}) not found for {}'.format(method, method.__class__.__name__, obj.__class__.__name__),
  326. )
  327. def call_tests(self, obj, test_descriptions):
  328. for test_description in test_descriptions:
  329. self.call_test(obj, test_description)
  330. def search(self, search_query: SearchQuery) -> ResultContainer:
  331. result_container = ResultContainer()
  332. engineref_category = search_query.engineref_list[0].category
  333. params = self.processor.get_params(search_query, engineref_category)
  334. if params is not None:
  335. counter_inc('engine', search_query.engineref_list[0].name, 'search', 'count', 'sent')
  336. self.processor.search(search_query.query, params, result_container, default_timer(), 5)
  337. return result_container
  338. def get_result_container_tests(self, test_name: str, search_query: SearchQuery) -> ResultContainerTests:
  339. result_container = self.search(search_query)
  340. result_container_check = ResultContainerTests(self.test_results, test_name, search_query, result_container)
  341. result_container_check.check_basic()
  342. return result_container_check
  343. def run_test(self, test_name):
  344. test_parameters = self.tests[test_name]
  345. search_query_list = list(Checker.search_query_matrix_iterator(self.engineref_list, test_parameters['matrix']))
  346. rct_list = [self.get_result_container_tests(test_name, search_query) for search_query in search_query_list]
  347. stop_test = False
  348. if 'result_container' in test_parameters:
  349. for rct in rct_list:
  350. stop_test = stop_test or rct.stop_test
  351. if not rct.stop_test:
  352. self.call_tests(rct, test_parameters['result_container'])
  353. if not stop_test:
  354. if 'test' in test_parameters:
  355. checker_tests = CheckerTests(self.test_results, test_name, rct_list)
  356. self.call_tests(checker_tests, test_parameters['test'])
  357. def run(self):
  358. for test_name in self.tests:
  359. self.run_test(test_name)
  360. # clear cache
  361. _download_and_check_if_image.cache_clear()
  362. # force a garbage collector
  363. gc.collect()