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.

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