You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. """
  2. Proxy requests to avoid SSRF
  3. """
  4. import logging
  5. import time
  6. import httpx
  7. from configs import dify_config
  8. logger = logging.getLogger(__name__)
  9. SSRF_DEFAULT_MAX_RETRIES = dify_config.SSRF_DEFAULT_MAX_RETRIES
  10. HTTP_REQUEST_NODE_SSL_VERIFY = True # Default value for HTTP_REQUEST_NODE_SSL_VERIFY is True
  11. try:
  12. HTTP_REQUEST_NODE_SSL_VERIFY = dify_config.HTTP_REQUEST_NODE_SSL_VERIFY
  13. http_request_node_ssl_verify_lower = str(HTTP_REQUEST_NODE_SSL_VERIFY).lower()
  14. if http_request_node_ssl_verify_lower == "true":
  15. HTTP_REQUEST_NODE_SSL_VERIFY = True
  16. elif http_request_node_ssl_verify_lower == "false":
  17. HTTP_REQUEST_NODE_SSL_VERIFY = False
  18. else:
  19. raise ValueError("Invalid value. HTTP_REQUEST_NODE_SSL_VERIFY should be 'True' or 'False'")
  20. except NameError:
  21. HTTP_REQUEST_NODE_SSL_VERIFY = True
  22. BACKOFF_FACTOR = 0.5
  23. STATUS_FORCELIST = [429, 500, 502, 503, 504]
  24. class MaxRetriesExceededError(ValueError):
  25. """Raised when the maximum number of retries is exceeded."""
  26. pass
  27. def make_request(method, url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  28. if "allow_redirects" in kwargs:
  29. allow_redirects = kwargs.pop("allow_redirects")
  30. if "follow_redirects" not in kwargs:
  31. kwargs["follow_redirects"] = allow_redirects
  32. if "timeout" not in kwargs:
  33. kwargs["timeout"] = httpx.Timeout(
  34. timeout=dify_config.SSRF_DEFAULT_TIME_OUT,
  35. connect=dify_config.SSRF_DEFAULT_CONNECT_TIME_OUT,
  36. read=dify_config.SSRF_DEFAULT_READ_TIME_OUT,
  37. write=dify_config.SSRF_DEFAULT_WRITE_TIME_OUT,
  38. )
  39. if "ssl_verify" not in kwargs:
  40. kwargs["ssl_verify"] = HTTP_REQUEST_NODE_SSL_VERIFY
  41. ssl_verify = kwargs.pop("ssl_verify")
  42. retries = 0
  43. while retries <= max_retries:
  44. try:
  45. if dify_config.SSRF_PROXY_ALL_URL:
  46. with httpx.Client(proxy=dify_config.SSRF_PROXY_ALL_URL, verify=ssl_verify) as client:
  47. response = client.request(method=method, url=url, **kwargs)
  48. elif dify_config.SSRF_PROXY_HTTP_URL and dify_config.SSRF_PROXY_HTTPS_URL:
  49. proxy_mounts = {
  50. "http://": httpx.HTTPTransport(proxy=dify_config.SSRF_PROXY_HTTP_URL, verify=ssl_verify),
  51. "https://": httpx.HTTPTransport(proxy=dify_config.SSRF_PROXY_HTTPS_URL, verify=ssl_verify),
  52. }
  53. with httpx.Client(mounts=proxy_mounts, verify=ssl_verify) as client:
  54. response = client.request(method=method, url=url, **kwargs)
  55. else:
  56. with httpx.Client(verify=ssl_verify) as client:
  57. response = client.request(method=method, url=url, **kwargs)
  58. if response.status_code not in STATUS_FORCELIST:
  59. return response
  60. else:
  61. logger.warning(
  62. "Received status code %s for URL %s which is in the force list", response.status_code, url
  63. )
  64. except httpx.RequestError as e:
  65. logger.warning("Request to URL %s failed on attempt %s: %s", url, retries + 1, e)
  66. if max_retries == 0:
  67. raise
  68. retries += 1
  69. if retries <= max_retries:
  70. time.sleep(BACKOFF_FACTOR * (2 ** (retries - 1)))
  71. raise MaxRetriesExceededError(f"Reached maximum retries ({max_retries}) for URL {url}")
  72. def get(url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  73. return make_request("GET", url, max_retries=max_retries, **kwargs)
  74. def post(url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  75. return make_request("POST", url, max_retries=max_retries, **kwargs)
  76. def put(url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  77. return make_request("PUT", url, max_retries=max_retries, **kwargs)
  78. def patch(url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  79. return make_request("PATCH", url, max_retries=max_retries, **kwargs)
  80. def delete(url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  81. return make_request("DELETE", url, max_retries=max_retries, **kwargs)
  82. def head(url, max_retries=SSRF_DEFAULT_MAX_RETRIES, **kwargs):
  83. return make_request("HEAD", url, max_retries=max_retries, **kwargs)