helper.py 9.5 KB

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