helper.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. import json
  2. import logging
  3. import random
  4. import re
  5. import string
  6. import subprocess
  7. import time
  8. import uuid
  9. from collections.abc import Generator, Mapping
  10. from datetime import datetime
  11. from hashlib import sha256
  12. from typing import TYPE_CHECKING, Any, Optional, Union, cast
  13. from zoneinfo import available_timezones
  14. from flask import Response, stream_with_context
  15. from flask_restful import fields
  16. from configs import dify_config
  17. from core.app.features.rate_limiting.rate_limit import RateLimitGenerator
  18. from core.file import helpers as file_helpers
  19. from extensions.ext_redis import redis_client
  20. if TYPE_CHECKING:
  21. from models.account import Account
  22. def run(script):
  23. return subprocess.getstatusoutput("source /root/.bashrc && " + script)
  24. class AppIconUrlField(fields.Raw):
  25. def output(self, key, obj):
  26. if obj is None:
  27. return None
  28. from models.model import App, IconType, Site
  29. if isinstance(obj, dict) and "app" in obj:
  30. obj = obj["app"]
  31. if isinstance(obj, App | Site) and obj.icon_type == IconType.IMAGE.value:
  32. return file_helpers.get_signed_file_url(obj.icon)
  33. return None
  34. class TimestampField(fields.Raw):
  35. def format(self, value) -> int:
  36. return int(value.timestamp())
  37. def email(email):
  38. # Define a regex pattern for email addresses
  39. pattern = r"^[\w\.!#$%&'*+\-/=?^_`{|}~]+@([\w-]+\.)+[\w-]{2,}$"
  40. # Check if the email matches the pattern
  41. if re.match(pattern, email) is not None:
  42. return email
  43. error = "{email} is not a valid email.".format(email=email)
  44. raise ValueError(error)
  45. def uuid_value(value):
  46. if value == "":
  47. return str(value)
  48. try:
  49. uuid_obj = uuid.UUID(value)
  50. return str(uuid_obj)
  51. except ValueError:
  52. error = "{value} is not a valid uuid.".format(value=value)
  53. raise ValueError(error)
  54. def alphanumeric(value: str):
  55. # check if the value is alphanumeric and underlined
  56. if re.match(r"^[a-zA-Z0-9_]+$", value):
  57. return value
  58. raise ValueError(f"{value} is not a valid alphanumeric value")
  59. def timestamp_value(timestamp):
  60. try:
  61. int_timestamp = int(timestamp)
  62. if int_timestamp < 0:
  63. raise ValueError
  64. return int_timestamp
  65. except ValueError:
  66. error = "{timestamp} is not a valid timestamp.".format(timestamp=timestamp)
  67. raise ValueError(error)
  68. class StrLen:
  69. """Restrict input to an integer in a range (inclusive)"""
  70. def __init__(self, max_length, argument="argument"):
  71. self.max_length = max_length
  72. self.argument = argument
  73. def __call__(self, value):
  74. length = len(value)
  75. if length > self.max_length:
  76. error = "Invalid {arg}: {val}. {arg} cannot exceed length {length}".format(
  77. arg=self.argument, val=value, length=self.max_length
  78. )
  79. raise ValueError(error)
  80. return value
  81. class FloatRange:
  82. """Restrict input to an float in a range (inclusive)"""
  83. def __init__(self, low, high, argument="argument"):
  84. self.low = low
  85. self.high = high
  86. self.argument = argument
  87. def __call__(self, value):
  88. value = _get_float(value)
  89. if value < self.low or value > self.high:
  90. error = "Invalid {arg}: {val}. {arg} must be within the range {lo} - {hi}".format(
  91. arg=self.argument, val=value, lo=self.low, hi=self.high
  92. )
  93. raise ValueError(error)
  94. return value
  95. class DatetimeString:
  96. def __init__(self, format, argument="argument"):
  97. self.format = format
  98. self.argument = argument
  99. def __call__(self, value):
  100. try:
  101. datetime.strptime(value, self.format)
  102. except ValueError:
  103. error = "Invalid {arg}: {val}. {arg} must be conform to the format {format}".format(
  104. arg=self.argument, val=value, format=self.format
  105. )
  106. raise ValueError(error)
  107. return value
  108. def _get_float(value):
  109. try:
  110. return float(value)
  111. except (TypeError, ValueError):
  112. raise ValueError("{} is not a valid float".format(value))
  113. def timezone(timezone_string):
  114. if timezone_string and timezone_string in available_timezones():
  115. return timezone_string
  116. error = "{timezone_string} is not a valid timezone.".format(timezone_string=timezone_string)
  117. raise ValueError(error)
  118. def generate_string(n):
  119. letters_digits = string.ascii_letters + string.digits
  120. result = ""
  121. for i in range(n):
  122. result += random.choice(letters_digits)
  123. return result
  124. def extract_remote_ip(request) -> str:
  125. if request.headers.get("CF-Connecting-IP"):
  126. return cast(str, request.headers.get("Cf-Connecting-Ip"))
  127. elif request.headers.getlist("X-Forwarded-For"):
  128. return cast(str, request.headers.getlist("X-Forwarded-For")[0])
  129. else:
  130. return cast(str, request.remote_addr)
  131. def generate_text_hash(text: str) -> str:
  132. hash_text = str(text) + "None"
  133. return sha256(hash_text.encode()).hexdigest()
  134. def compact_generate_response(response: Union[Mapping, Generator, RateLimitGenerator]) -> Response:
  135. if isinstance(response, dict):
  136. return Response(response=json.dumps(response), status=200, mimetype="application/json")
  137. else:
  138. def generate() -> Generator:
  139. yield from response
  140. return Response(stream_with_context(generate()), status=200, mimetype="text/event-stream")
  141. class TokenManager:
  142. @classmethod
  143. def generate_token(
  144. cls,
  145. token_type: str,
  146. account: Optional["Account"] = None,
  147. email: Optional[str] = None,
  148. additional_data: Optional[dict] = None,
  149. ) -> str:
  150. if account is None and email is None:
  151. raise ValueError("Account or email must be provided")
  152. account_id = account.id if account else None
  153. account_email = account.email if account else email
  154. if account_id:
  155. old_token = cls._get_current_token_for_account(account_id, token_type)
  156. if old_token:
  157. if isinstance(old_token, bytes):
  158. old_token = old_token.decode("utf-8")
  159. cls.revoke_token(old_token, token_type)
  160. token = str(uuid.uuid4())
  161. token_data = {"account_id": account_id, "email": account_email, "token_type": token_type}
  162. if additional_data:
  163. token_data.update(additional_data)
  164. expiry_minutes = dify_config.model_dump().get(f"{token_type.upper()}_TOKEN_EXPIRY_MINUTES")
  165. if expiry_minutes is None:
  166. raise ValueError(f"Expiry minutes for {token_type} token is not set")
  167. token_key = cls._get_token_key(token, token_type)
  168. expiry_time = int(expiry_minutes * 60)
  169. redis_client.setex(token_key, expiry_time, json.dumps(token_data))
  170. if account_id:
  171. cls._set_current_token_for_account(account_id, token, token_type, expiry_minutes)
  172. return token
  173. @classmethod
  174. def _get_token_key(cls, token: str, token_type: str) -> str:
  175. return f"{token_type}:token:{token}"
  176. @classmethod
  177. def revoke_token(cls, token: str, token_type: str):
  178. token_key = cls._get_token_key(token, token_type)
  179. redis_client.delete(token_key)
  180. @classmethod
  181. def get_token_data(cls, token: str, token_type: str) -> Optional[dict[str, Any]]:
  182. key = cls._get_token_key(token, token_type)
  183. token_data_json = redis_client.get(key)
  184. if token_data_json is None:
  185. logging.warning(f"{token_type} token {token} not found with key {key}")
  186. return None
  187. token_data: Optional[dict[str, Any]] = json.loads(token_data_json)
  188. return token_data
  189. @classmethod
  190. def _get_current_token_for_account(cls, account_id: str, token_type: str) -> Optional[str]:
  191. key = cls._get_account_token_key(account_id, token_type)
  192. current_token: Optional[str] = redis_client.get(key)
  193. return current_token
  194. @classmethod
  195. def _set_current_token_for_account(
  196. cls, account_id: str, token: str, token_type: str, expiry_hours: Union[int, float]
  197. ):
  198. key = cls._get_account_token_key(account_id, token_type)
  199. expiry_time = int(expiry_hours * 60 * 60)
  200. redis_client.setex(key, expiry_time, token)
  201. @classmethod
  202. def _get_account_token_key(cls, account_id: str, token_type: str) -> str:
  203. return f"{token_type}:account:{account_id}"
  204. class RateLimiter:
  205. def __init__(self, prefix: str, max_attempts: int, time_window: int):
  206. self.prefix = prefix
  207. self.max_attempts = max_attempts
  208. self.time_window = time_window
  209. def _get_key(self, email: str) -> str:
  210. return f"{self.prefix}:{email}"
  211. def is_rate_limited(self, email: str) -> bool:
  212. key = self._get_key(email)
  213. current_time = int(time.time())
  214. window_start_time = current_time - self.time_window
  215. redis_client.zremrangebyscore(key, "-inf", window_start_time)
  216. attempts = redis_client.zcard(key)
  217. if attempts and int(attempts) >= self.max_attempts:
  218. return True
  219. return False
  220. def increment_rate_limit(self, email: str):
  221. key = self._get_key(email)
  222. current_time = int(time.time())
  223. redis_client.zadd(key, {current_time: current_time})
  224. redis_client.expire(key, self.time_window * 2)