utils.py 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import socket
  2. import urllib.parse
  3. import validators
  4. from typing import Union, Sequence, Iterator
  5. from langchain_community.document_loaders import (
  6. WebBaseLoader,
  7. )
  8. from langchain_core.documents import Document
  9. from open_webui.constants import ERROR_MESSAGES
  10. from open_webui.config import ENABLE_RAG_LOCAL_WEB_FETCH
  11. from open_webui.env import SRC_LOG_LEVELS
  12. import logging
  13. log = logging.getLogger(__name__)
  14. log.setLevel(SRC_LOG_LEVELS["RAG"])
  15. def validate_url(url: Union[str, Sequence[str]]):
  16. if isinstance(url, str):
  17. if isinstance(validators.url(url), validators.ValidationError):
  18. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  19. if not ENABLE_RAG_LOCAL_WEB_FETCH:
  20. # Local web fetch is disabled, filter out any URLs that resolve to private IP addresses
  21. parsed_url = urllib.parse.urlparse(url)
  22. # Get IPv4 and IPv6 addresses
  23. ipv4_addresses, ipv6_addresses = resolve_hostname(parsed_url.hostname)
  24. # Check if any of the resolved addresses are private
  25. # This is technically still vulnerable to DNS rebinding attacks, as we don't control WebBaseLoader
  26. for ip in ipv4_addresses:
  27. if validators.ipv4(ip, private=True):
  28. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  29. for ip in ipv6_addresses:
  30. if validators.ipv6(ip, private=True):
  31. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  32. return True
  33. elif isinstance(url, Sequence):
  34. return all(validate_url(u) for u in url)
  35. else:
  36. return False
  37. def resolve_hostname(hostname):
  38. # Get address information
  39. addr_info = socket.getaddrinfo(hostname, None)
  40. # Extract IP addresses from address information
  41. ipv4_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET]
  42. ipv6_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET6]
  43. return ipv4_addresses, ipv6_addresses
  44. class SafeWebBaseLoader(WebBaseLoader):
  45. """WebBaseLoader with enhanced error handling for URLs."""
  46. def lazy_load(self) -> Iterator[Document]:
  47. """Lazy load text from the url(s) in web_path with error handling."""
  48. for path in self.web_paths:
  49. try:
  50. soup = self._scrape(path, bs_kwargs=self.bs_kwargs)
  51. text = soup.get_text(**self.bs_get_text_kwargs)
  52. # Build metadata
  53. metadata = {"source": path}
  54. if title := soup.find("title"):
  55. metadata["title"] = title.get_text()
  56. if description := soup.find("meta", attrs={"name": "description"}):
  57. metadata["description"] = description.get(
  58. "content", "No description found."
  59. )
  60. if html := soup.find("html"):
  61. metadata["language"] = html.get("lang", "No language found.")
  62. yield Document(page_content=text, metadata=metadata)
  63. except Exception as e:
  64. # Log the error and continue with the next URL
  65. log.error(f"Error loading {path}: {e}")
  66. def get_web_loader(
  67. url: Union[str, Sequence[str]],
  68. verify_ssl: bool = True,
  69. requests_per_second: int = 2,
  70. ):
  71. # Check if the URL is valid
  72. if not validate_url(url):
  73. raise ValueError(ERROR_MESSAGES.INVALID_URL)
  74. return SafeWebBaseLoader(
  75. url,
  76. verify_ssl=verify_ssl,
  77. requests_per_second=requests_per_second,
  78. continue_on_failure=True,
  79. )