選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

helper.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import json
  2. import logging
  3. import re
  4. import secrets
  5. import string
  6. import struct
  7. import subprocess
  8. import time
  9. import uuid
  10. from collections.abc import Generator, Mapping
  11. from datetime import datetime
  12. from hashlib import sha256
  13. from typing import TYPE_CHECKING, Any, Optional, Union, cast
  14. from zoneinfo import available_timezones
  15. from flask import Response, stream_with_context
  16. from flask_restful import fields
  17. from pydantic import BaseModel
  18. from configs import dify_config
  19. from core.app.features.rate_limiting.rate_limit import RateLimitGenerator
  20. from core.file import helpers as file_helpers
  21. from core.model_runtime.utils.encoders import jsonable_encoder
  22. from extensions.ext_redis import redis_client
  23. if TYPE_CHECKING:
  24. from models.account import Account
  25. from models.model import EndUser
  26. def extract_tenant_id(user: Union["Account", "EndUser"]) -> str | None:
  27. """
  28. Extract tenant_id from Account or EndUser object.
  29. Args:
  30. user: Account or EndUser object
  31. Returns:
  32. tenant_id string if available, None otherwise
  33. Raises:
  34. ValueError: If user is neither Account nor EndUser
  35. """
  36. from models.account import Account
  37. from models.model import EndUser
  38. if isinstance(user, Account):
  39. return user.current_tenant_id
  40. elif isinstance(user, EndUser):
  41. return user.tenant_id
  42. else:
  43. raise ValueError(f"Invalid user type: {type(user)}. Expected Account or EndUser.")
  44. def run(script):
  45. return subprocess.getstatusoutput("source /root/.bashrc && " + script)
  46. class AppIconUrlField(fields.Raw):
  47. def output(self, key, obj):
  48. if obj is None:
  49. return None
  50. from models.model import App, IconType, Site
  51. if isinstance(obj, dict) and "app" in obj:
  52. obj = obj["app"]
  53. if isinstance(obj, App | Site) and obj.icon_type == IconType.IMAGE.value:
  54. return file_helpers.get_signed_file_url(obj.icon)
  55. return None
  56. class AvatarUrlField(fields.Raw):
  57. def output(self, key, obj):
  58. if obj is None:
  59. return None
  60. from models.account import Account
  61. if isinstance(obj, Account) and obj.avatar is not None:
  62. return file_helpers.get_signed_file_url(obj.avatar)
  63. return None
  64. class TimestampField(fields.Raw):
  65. def format(self, value) -> int:
  66. return int(value.timestamp())
  67. def email(email):
  68. # Define a regex pattern for email addresses
  69. pattern = r"^[\w\.!#$%&'*+\-/=?^_`{|}~]+@([\w-]+\.)+[\w-]{2,}$"
  70. # Check if the email matches the pattern
  71. if re.match(pattern, email) is not None:
  72. return email
  73. error = "{email} is not a valid email.".format(email=email)
  74. raise ValueError(error)
  75. def uuid_value(value):
  76. if value == "":
  77. return str(value)
  78. try:
  79. uuid_obj = uuid.UUID(value)
  80. return str(uuid_obj)
  81. except ValueError:
  82. error = "{value} is not a valid uuid.".format(value=value)
  83. raise ValueError(error)
  84. def alphanumeric(value: str):
  85. # check if the value is alphanumeric and underlined
  86. if re.match(r"^[a-zA-Z0-9_]+$", value):
  87. return value
  88. raise ValueError(f"{value} is not a valid alphanumeric value")
  89. def timestamp_value(timestamp):
  90. try:
  91. int_timestamp = int(timestamp)
  92. if int_timestamp < 0:
  93. raise ValueError
  94. return int_timestamp
  95. except ValueError:
  96. error = "{timestamp} is not a valid timestamp.".format(timestamp=timestamp)
  97. raise ValueError(error)
  98. class StrLen:
  99. """Restrict input to an integer in a range (inclusive)"""
  100. def __init__(self, max_length, argument="argument"):
  101. self.max_length = max_length
  102. self.argument = argument
  103. def __call__(self, value):
  104. length = len(value)
  105. if length > self.max_length:
  106. error = "Invalid {arg}: {val}. {arg} cannot exceed length {length}".format(
  107. arg=self.argument, val=value, length=self.max_length
  108. )
  109. raise ValueError(error)
  110. return value
  111. class FloatRange:
  112. """Restrict input to an float in a range (inclusive)"""
  113. def __init__(self, low, high, argument="argument"):
  114. self.low = low
  115. self.high = high
  116. self.argument = argument
  117. def __call__(self, value):
  118. value = _get_float(value)
  119. if value < self.low or value > self.high:
  120. error = "Invalid {arg}: {val}. {arg} must be within the range {lo} - {hi}".format(
  121. arg=self.argument, val=value, lo=self.low, hi=self.high
  122. )
  123. raise ValueError(error)
  124. return value
  125. class DatetimeString:
  126. def __init__(self, format, argument="argument"):
  127. self.format = format
  128. self.argument = argument
  129. def __call__(self, value):
  130. try:
  131. datetime.strptime(value, self.format)
  132. except ValueError:
  133. error = "Invalid {arg}: {val}. {arg} must be conform to the format {format}".format(
  134. arg=self.argument, val=value, format=self.format
  135. )
  136. raise ValueError(error)
  137. return value
  138. def _get_float(value):
  139. try:
  140. return float(value)
  141. except (TypeError, ValueError):
  142. raise ValueError("{} is not a valid float".format(value))
  143. def timezone(timezone_string):
  144. if timezone_string and timezone_string in available_timezones():
  145. return timezone_string
  146. error = "{timezone_string} is not a valid timezone.".format(timezone_string=timezone_string)
  147. raise ValueError(error)
  148. def generate_string(n):
  149. letters_digits = string.ascii_letters + string.digits
  150. result = ""
  151. for i in range(n):
  152. result += secrets.choice(letters_digits)
  153. return result
  154. def extract_remote_ip(request) -> str:
  155. if request.headers.get("CF-Connecting-IP"):
  156. return cast(str, request.headers.get("CF-Connecting-IP"))
  157. elif request.headers.getlist("X-Forwarded-For"):
  158. return cast(str, request.headers.getlist("X-Forwarded-For")[0])
  159. else:
  160. return cast(str, request.remote_addr)
  161. def generate_text_hash(text: str) -> str:
  162. hash_text = str(text) + "None"
  163. return sha256(hash_text.encode()).hexdigest()
  164. def compact_generate_response(response: Union[Mapping, Generator, RateLimitGenerator]) -> Response:
  165. if isinstance(response, dict):
  166. return Response(response=json.dumps(jsonable_encoder(response)), status=200, mimetype="application/json")
  167. else:
  168. def generate() -> Generator:
  169. yield from response
  170. return Response(stream_with_context(generate()), status=200, mimetype="text/event-stream")
  171. def length_prefixed_response(magic_number: int, response: Union[Mapping, Generator, RateLimitGenerator]) -> Response:
  172. """
  173. This function is used to return a response with a length prefix.
  174. Magic number is a one byte number that indicates the type of the response.
  175. For a compatibility with latest plugin daemon https://github.com/langgenius/dify-plugin-daemon/pull/341
  176. Avoid using line-based response, it leads a memory issue.
  177. We uses following format:
  178. | Field | Size | Description |
  179. |---------------|----------|---------------------------------|
  180. | Magic Number | 1 byte | Magic number identifier |
  181. | Reserved | 1 byte | Reserved field |
  182. | Header Length | 2 bytes | Header length (usually 0xa) |
  183. | Data Length | 4 bytes | Length of the data |
  184. | Reserved | 6 bytes | Reserved fields |
  185. | Data | Variable | Actual data content |
  186. | Reserved Fields | Header | Data |
  187. |-----------------|----------|----------|
  188. | 4 bytes total | Variable | Variable |
  189. all data is in little endian
  190. """
  191. def pack_response_with_length_prefix(response: bytes) -> bytes:
  192. header_length = 0xA
  193. data_length = len(response)
  194. # | Magic Number 1byte | Reserved 1byte | Header Length 2bytes | Data Length 4bytes | Reserved 6bytes | Data
  195. return struct.pack("<BBHI", magic_number, 0, header_length, data_length) + b"\x00" * 6 + response
  196. if isinstance(response, dict):
  197. return Response(
  198. response=pack_response_with_length_prefix(json.dumps(jsonable_encoder(response)).encode("utf-8")),
  199. status=200,
  200. mimetype="application/json",
  201. )
  202. elif isinstance(response, BaseModel):
  203. return Response(
  204. response=pack_response_with_length_prefix(response.model_dump_json().encode("utf-8")),
  205. status=200,
  206. mimetype="application/json",
  207. )
  208. def generate() -> Generator:
  209. for chunk in response:
  210. if isinstance(chunk, str):
  211. yield pack_response_with_length_prefix(chunk.encode("utf-8"))
  212. else:
  213. yield pack_response_with_length_prefix(chunk)
  214. return Response(stream_with_context(generate()), status=200, mimetype="text/event-stream")
  215. class TokenManager:
  216. @classmethod
  217. def generate_token(
  218. cls,
  219. token_type: str,
  220. account: Optional["Account"] = None,
  221. email: Optional[str] = None,
  222. additional_data: Optional[dict] = None,
  223. ) -> str:
  224. if account is None and email is None:
  225. raise ValueError("Account or email must be provided")
  226. account_id = account.id if account else None
  227. account_email = account.email if account else email
  228. if account_id:
  229. old_token = cls._get_current_token_for_account(account_id, token_type)
  230. if old_token:
  231. if isinstance(old_token, bytes):
  232. old_token = old_token.decode("utf-8")
  233. cls.revoke_token(old_token, token_type)
  234. token = str(uuid.uuid4())
  235. token_data = {"account_id": account_id, "email": account_email, "token_type": token_type}
  236. if additional_data:
  237. token_data.update(additional_data)
  238. expiry_minutes = dify_config.model_dump().get(f"{token_type.upper()}_TOKEN_EXPIRY_MINUTES")
  239. if expiry_minutes is None:
  240. raise ValueError(f"Expiry minutes for {token_type} token is not set")
  241. token_key = cls._get_token_key(token, token_type)
  242. expiry_time = int(expiry_minutes * 60)
  243. redis_client.setex(token_key, expiry_time, json.dumps(token_data))
  244. if account_id:
  245. cls._set_current_token_for_account(account_id, token, token_type, expiry_minutes)
  246. return token
  247. @classmethod
  248. def _get_token_key(cls, token: str, token_type: str) -> str:
  249. return f"{token_type}:token:{token}"
  250. @classmethod
  251. def revoke_token(cls, token: str, token_type: str):
  252. token_key = cls._get_token_key(token, token_type)
  253. redis_client.delete(token_key)
  254. @classmethod
  255. def get_token_data(cls, token: str, token_type: str) -> Optional[dict[str, Any]]:
  256. key = cls._get_token_key(token, token_type)
  257. token_data_json = redis_client.get(key)
  258. if token_data_json is None:
  259. logging.warning(f"{token_type} token {token} not found with key {key}")
  260. return None
  261. token_data: Optional[dict[str, Any]] = json.loads(token_data_json)
  262. return token_data
  263. @classmethod
  264. def _get_current_token_for_account(cls, account_id: str, token_type: str) -> Optional[str]:
  265. key = cls._get_account_token_key(account_id, token_type)
  266. current_token: Optional[str] = redis_client.get(key)
  267. return current_token
  268. @classmethod
  269. def _set_current_token_for_account(
  270. cls, account_id: str, token: str, token_type: str, expiry_hours: Union[int, float]
  271. ):
  272. key = cls._get_account_token_key(account_id, token_type)
  273. expiry_time = int(expiry_hours * 60 * 60)
  274. redis_client.setex(key, expiry_time, token)
  275. @classmethod
  276. def _get_account_token_key(cls, account_id: str, token_type: str) -> str:
  277. return f"{token_type}:account:{account_id}"
  278. class RateLimiter:
  279. def __init__(self, prefix: str, max_attempts: int, time_window: int):
  280. self.prefix = prefix
  281. self.max_attempts = max_attempts
  282. self.time_window = time_window
  283. def _get_key(self, email: str) -> str:
  284. return f"{self.prefix}:{email}"
  285. def is_rate_limited(self, email: str) -> bool:
  286. key = self._get_key(email)
  287. current_time = int(time.time())
  288. window_start_time = current_time - self.time_window
  289. redis_client.zremrangebyscore(key, "-inf", window_start_time)
  290. attempts = redis_client.zcard(key)
  291. if attempts and int(attempts) >= self.max_attempts:
  292. return True
  293. return False
  294. def increment_rate_limit(self, email: str):
  295. key = self._get_key(email)
  296. current_time = int(time.time())
  297. redis_client.zadd(key, {current_time: current_time})
  298. redis_client.expire(key, self.time_window * 2)