utils.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import asyncio
  2. import logging
  3. import socket
  4. import ssl
  5. import urllib.parse
  6. import urllib.request
  7. from collections import defaultdict
  8. from datetime import datetime, time, timedelta
  9. from typing import (
  10. Any,
  11. AsyncIterator,
  12. Dict,
  13. Iterator,
  14. List,
  15. Optional,
  16. Sequence,
  17. Union
  18. )
  19. import aiohttp
  20. import certifi
  21. import validators
  22. from langchain_community.document_loaders import (
  23. PlaywrightURLLoader,
  24. WebBaseLoader
  25. )
  26. from langchain_core.documents import Document
  27. from open_webui.constants import ERROR_MESSAGES
  28. from open_webui.config import ENABLE_RAG_LOCAL_WEB_FETCH, PLAYWRIGHT_WS_URI, RAG_WEB_LOADER
  29. from open_webui.env import SRC_LOG_LEVELS
  30. log = logging.getLogger(__name__)
  31. log.setLevel(SRC_LOG_LEVELS["RAG"])
  32. def validate_url(url: Union[str, Sequence[str]]):
  33. if isinstance(url, str):
  34. if isinstance(validators.url(url), validators.ValidationError):
  35. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  36. if not ENABLE_RAG_LOCAL_WEB_FETCH:
  37. # Local web fetch is disabled, filter out any URLs that resolve to private IP addresses
  38. parsed_url = urllib.parse.urlparse(url)
  39. # Get IPv4 and IPv6 addresses
  40. ipv4_addresses, ipv6_addresses = resolve_hostname(parsed_url.hostname)
  41. # Check if any of the resolved addresses are private
  42. # This is technically still vulnerable to DNS rebinding attacks, as we don't control WebBaseLoader
  43. for ip in ipv4_addresses:
  44. if validators.ipv4(ip, private=True):
  45. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  46. for ip in ipv6_addresses:
  47. if validators.ipv6(ip, private=True):
  48. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  49. return True
  50. elif isinstance(url, Sequence):
  51. return all(validate_url(u) for u in url)
  52. else:
  53. return False
  54. def safe_validate_urls(url: Sequence[str]) -> Sequence[str]:
  55. valid_urls = []
  56. for u in url:
  57. try:
  58. if validate_url(u):
  59. valid_urls.append(u)
  60. except ValueError:
  61. continue
  62. return valid_urls
  63. def resolve_hostname(hostname):
  64. # Get address information
  65. addr_info = socket.getaddrinfo(hostname, None)
  66. # Extract IP addresses from address information
  67. ipv4_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET]
  68. ipv6_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET6]
  69. return ipv4_addresses, ipv6_addresses
  70. def extract_metadata(soup, url):
  71. metadata = {
  72. "source": url
  73. }
  74. if title := soup.find("title"):
  75. metadata["title"] = title.get_text()
  76. if description := soup.find("meta", attrs={"name": "description"}):
  77. metadata["description"] = description.get(
  78. "content", "No description found."
  79. )
  80. if html := soup.find("html"):
  81. metadata["language"] = html.get("lang", "No language found.")
  82. return metadata
  83. class SafePlaywrightURLLoader(PlaywrightURLLoader):
  84. """Load HTML pages safely with Playwright, supporting SSL verification, rate limiting, and remote browser connection.
  85. Attributes:
  86. web_paths (List[str]): List of URLs to load.
  87. verify_ssl (bool): If True, verify SSL certificates.
  88. requests_per_second (Optional[float]): Number of requests per second to limit to.
  89. continue_on_failure (bool): If True, continue loading other URLs on failure.
  90. headless (bool): If True, the browser will run in headless mode.
  91. playwright_ws_url (Optional[str]): WebSocket endpoint URI for remote browser connection.
  92. trust_env (bool): If True, use proxy settings from environment variables.
  93. """
  94. def __init__(
  95. self,
  96. web_paths: List[str],
  97. verify_ssl: bool = True,
  98. trust_env: bool = False,
  99. requests_per_second: Optional[float] = None,
  100. continue_on_failure: bool = True,
  101. headless: bool = True,
  102. remove_selectors: Optional[List[str]] = None,
  103. proxy: Optional[Dict[str, str]] = None,
  104. playwright_ws_url: Optional[str] = None
  105. ):
  106. """Initialize with additional safety parameters and remote browser support."""
  107. proxy_server = proxy.get('server') if proxy else None
  108. if trust_env and not proxy_server:
  109. env_proxies = urllib.request.getproxies()
  110. env_proxy_server = env_proxies.get('https') or env_proxies.get('http')
  111. if env_proxy_server:
  112. if proxy:
  113. proxy['server'] = env_proxy_server
  114. else:
  115. proxy = { 'server': env_proxy_server }
  116. # We'll set headless to False if using playwright_ws_url since it's handled by the remote browser
  117. super().__init__(
  118. urls=web_paths,
  119. continue_on_failure=continue_on_failure,
  120. headless=headless if playwright_ws_url is None else False,
  121. remove_selectors=remove_selectors,
  122. proxy=proxy
  123. )
  124. self.verify_ssl = verify_ssl
  125. self.requests_per_second = requests_per_second
  126. self.last_request_time = None
  127. self.playwright_ws_url = playwright_ws_url
  128. self.trust_env = trust_env
  129. def lazy_load(self) -> Iterator[Document]:
  130. """Safely load URLs synchronously with support for remote browser."""
  131. from playwright.sync_api import sync_playwright
  132. with sync_playwright() as p:
  133. # Use remote browser if ws_endpoint is provided, otherwise use local browser
  134. if self.playwright_ws_url:
  135. browser = p.chromium.connect(self.playwright_ws_url)
  136. else:
  137. browser = p.chromium.launch(headless=self.headless, proxy=self.proxy)
  138. for url in self.urls:
  139. try:
  140. self._safe_process_url_sync(url)
  141. page = browser.new_page()
  142. response = page.goto(url)
  143. if response is None:
  144. raise ValueError(f"page.goto() returned None for url {url}")
  145. text = self.evaluator.evaluate(page, browser, response)
  146. metadata = {"source": url}
  147. yield Document(page_content=text, metadata=metadata)
  148. except Exception as e:
  149. if self.continue_on_failure:
  150. log.exception(e, "Error loading %s", url)
  151. continue
  152. raise e
  153. browser.close()
  154. async def alazy_load(self) -> AsyncIterator[Document]:
  155. """Safely load URLs asynchronously with support for remote browser."""
  156. from playwright.async_api import async_playwright
  157. async with async_playwright() as p:
  158. # Use remote browser if ws_endpoint is provided, otherwise use local browser
  159. if self.playwright_ws_url:
  160. browser = await p.chromium.connect(self.playwright_ws_url)
  161. else:
  162. browser = await p.chromium.launch(headless=self.headless, proxy=self.proxy)
  163. for url in self.urls:
  164. try:
  165. await self._safe_process_url(url)
  166. page = await browser.new_page()
  167. response = await page.goto(url)
  168. if response is None:
  169. raise ValueError(f"page.goto() returned None for url {url}")
  170. text = await self.evaluator.evaluate_async(page, browser, response)
  171. metadata = {"source": url}
  172. yield Document(page_content=text, metadata=metadata)
  173. except Exception as e:
  174. if self.continue_on_failure:
  175. log.exception(e, "Error loading %s", url)
  176. continue
  177. raise e
  178. await browser.close()
  179. def _verify_ssl_cert(self, url: str) -> bool:
  180. """Verify SSL certificate for the given URL."""
  181. if not url.startswith("https://"):
  182. return True
  183. try:
  184. hostname = url.split("://")[-1].split("/")[0]
  185. context = ssl.create_default_context(cafile=certifi.where())
  186. with context.wrap_socket(ssl.socket(), server_hostname=hostname) as s:
  187. s.connect((hostname, 443))
  188. return True
  189. except ssl.SSLError:
  190. return False
  191. except Exception as e:
  192. log.warning(f"SSL verification failed for {url}: {str(e)}")
  193. return False
  194. async def _wait_for_rate_limit(self):
  195. """Wait to respect the rate limit if specified."""
  196. if self.requests_per_second and self.last_request_time:
  197. min_interval = timedelta(seconds=1.0 / self.requests_per_second)
  198. time_since_last = datetime.now() - self.last_request_time
  199. if time_since_last < min_interval:
  200. await asyncio.sleep((min_interval - time_since_last).total_seconds())
  201. self.last_request_time = datetime.now()
  202. def _sync_wait_for_rate_limit(self):
  203. """Synchronous version of rate limit wait."""
  204. if self.requests_per_second and self.last_request_time:
  205. min_interval = timedelta(seconds=1.0 / self.requests_per_second)
  206. time_since_last = datetime.now() - self.last_request_time
  207. if time_since_last < min_interval:
  208. time.sleep((min_interval - time_since_last).total_seconds())
  209. self.last_request_time = datetime.now()
  210. async def _safe_process_url(self, url: str) -> bool:
  211. """Perform safety checks before processing a URL."""
  212. if self.verify_ssl and not self._verify_ssl_cert(url):
  213. raise ValueError(f"SSL certificate verification failed for {url}")
  214. await self._wait_for_rate_limit()
  215. return True
  216. def _safe_process_url_sync(self, url: str) -> bool:
  217. """Synchronous version of safety checks."""
  218. if self.verify_ssl and not self._verify_ssl_cert(url):
  219. raise ValueError(f"SSL certificate verification failed for {url}")
  220. self._sync_wait_for_rate_limit()
  221. return True
  222. class SafeWebBaseLoader(WebBaseLoader):
  223. """WebBaseLoader with enhanced error handling for URLs."""
  224. def __init__(self, trust_env: bool = False, *args, **kwargs):
  225. """Initialize SafeWebBaseLoader
  226. Args:
  227. trust_env (bool, optional): set to True if using proxy to make web requests, for example
  228. using http(s)_proxy environment variables. Defaults to False.
  229. """
  230. super().__init__(*args, **kwargs)
  231. self.trust_env = trust_env
  232. async def _fetch(
  233. self, url: str, retries: int = 3, cooldown: int = 2, backoff: float = 1.5
  234. ) -> str:
  235. async with aiohttp.ClientSession(trust_env=self.trust_env) as session:
  236. for i in range(retries):
  237. try:
  238. kwargs: Dict = dict(
  239. headers=self.session.headers,
  240. cookies=self.session.cookies.get_dict(),
  241. )
  242. if not self.session.verify:
  243. kwargs["ssl"] = False
  244. async with session.get(
  245. url, **(self.requests_kwargs | kwargs)
  246. ) as response:
  247. if self.raise_for_status:
  248. response.raise_for_status()
  249. return await response.text()
  250. except aiohttp.ClientConnectionError as e:
  251. if i == retries - 1:
  252. raise
  253. else:
  254. log.warning(
  255. f"Error fetching {url} with attempt "
  256. f"{i + 1}/{retries}: {e}. Retrying..."
  257. )
  258. await asyncio.sleep(cooldown * backoff**i)
  259. raise ValueError("retry count exceeded")
  260. def _unpack_fetch_results(
  261. self, results: Any, urls: List[str], parser: Union[str, None] = None
  262. ) -> List[Any]:
  263. """Unpack fetch results into BeautifulSoup objects."""
  264. from bs4 import BeautifulSoup
  265. final_results = []
  266. for i, result in enumerate(results):
  267. url = urls[i]
  268. if parser is None:
  269. if url.endswith(".xml"):
  270. parser = "xml"
  271. else:
  272. parser = self.default_parser
  273. self._check_parser(parser)
  274. final_results.append(BeautifulSoup(result, parser, **self.bs_kwargs))
  275. return final_results
  276. async def ascrape_all(
  277. self, urls: List[str], parser: Union[str, None] = None
  278. ) -> List[Any]:
  279. """Async fetch all urls, then return soups for all results."""
  280. results = await self.fetch_all(urls)
  281. return self._unpack_fetch_results(results, urls, parser=parser)
  282. def lazy_load(self) -> Iterator[Document]:
  283. """Lazy load text from the url(s) in web_path with error handling."""
  284. for path in self.web_paths:
  285. try:
  286. soup = self._scrape(path, bs_kwargs=self.bs_kwargs)
  287. text = soup.get_text(**self.bs_get_text_kwargs)
  288. # Build metadata
  289. metadata = extract_metadata(soup, path)
  290. yield Document(page_content=text, metadata=metadata)
  291. except Exception as e:
  292. # Log the error and continue with the next URL
  293. log.exception(e, "Error loading %s", path)
  294. async def alazy_load(self) -> AsyncIterator[Document]:
  295. """Async lazy load text from the url(s) in web_path."""
  296. results = await self.ascrape_all(self.web_paths)
  297. for path, soup in zip(self.web_paths, results):
  298. text = soup.get_text(**self.bs_get_text_kwargs)
  299. metadata = {"source": path}
  300. if title := soup.find("title"):
  301. metadata["title"] = title.get_text()
  302. if description := soup.find("meta", attrs={"name": "description"}):
  303. metadata["description"] = description.get(
  304. "content", "No description found."
  305. )
  306. if html := soup.find("html"):
  307. metadata["language"] = html.get("lang", "No language found.")
  308. yield Document(page_content=text, metadata=metadata)
  309. async def aload(self) -> list[Document]:
  310. """Load data into Document objects."""
  311. return [document async for document in self.alazy_load()]
  312. RAG_WEB_LOADERS = defaultdict(lambda: SafeWebBaseLoader)
  313. RAG_WEB_LOADERS["playwright"] = SafePlaywrightURLLoader
  314. RAG_WEB_LOADERS["safe_web"] = SafeWebBaseLoader
  315. def get_web_loader(
  316. urls: Union[str, Sequence[str]],
  317. verify_ssl: bool = True,
  318. requests_per_second: int = 2,
  319. trust_env: bool = False,
  320. ):
  321. # Check if the URLs are valid
  322. safe_urls = safe_validate_urls([urls] if isinstance(urls, str) else urls)
  323. web_loader_args = {
  324. "web_paths": safe_urls,
  325. "verify_ssl": verify_ssl,
  326. "requests_per_second": requests_per_second,
  327. "continue_on_failure": True,
  328. "trust_env": trust_env
  329. }
  330. if PLAYWRIGHT_WS_URI.value:
  331. web_loader_args["playwright_ws_url"] = PLAYWRIGHT_WS_URI.value
  332. # Create the appropriate WebLoader based on the configuration
  333. WebLoaderClass = RAG_WEB_LOADERS[RAG_WEB_LOADER.value]
  334. web_loader = WebLoaderClass(**web_loader_args)
  335. log.debug("Using RAG_WEB_LOADER %s for %s URLs", web_loader.__class__.__name__, len(safe_urls))
  336. return web_loader