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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 DatetimeString:
  112. def __init__(self, format, argument="argument"):
  113. self.format = format
  114. self.argument = argument
  115. def __call__(self, value):
  116. try:
  117. datetime.strptime(value, self.format)
  118. except ValueError:
  119. error = "Invalid {arg}: {val}. {arg} must be conform to the format {format}".format(
  120. arg=self.argument, val=value, format=self.format
  121. )
  122. raise ValueError(error)
  123. return value
  124. def _get_float(value):
  125. try:
  126. return float(value)
  127. except (TypeError, ValueError):
  128. raise ValueError("{} is not a valid float".format(value))
  129. def timezone(timezone_string):
  130. if timezone_string and timezone_string in available_timezones():
  131. return timezone_string
  132. error = "{timezone_string} is not a valid timezone.".format(timezone_string=timezone_string)
  133. raise ValueError(error)
  134. def generate_string(n):
  135. letters_digits = string.ascii_letters + string.digits
  136. result = ""
  137. for i in range(n):
  138. result += secrets.choice(letters_digits)
  139. return result
  140. def extract_remote_ip(request) -> str:
  141. if request.headers.get("CF-Connecting-IP"):
  142. return cast(str, request.headers.get("CF-Connecting-IP"))
  143. elif request.headers.getlist("X-Forwarded-For"):
  144. return cast(str, request.headers.getlist("X-Forwarded-For")[0])
  145. else:
  146. return cast(str, request.remote_addr)
  147. def generate_text_hash(text: str) -> str:
  148. hash_text = str(text) + "None"
  149. return sha256(hash_text.encode()).hexdigest()
  150. def compact_generate_response(response: Union[Mapping, Generator, RateLimitGenerator]) -> Response:
  151. if isinstance(response, dict):
  152. return Response(response=json.dumps(jsonable_encoder(response)), status=200, mimetype="application/json")
  153. else:
  154. def generate() -> Generator:
  155. yield from response
  156. return Response(stream_with_context(generate()), status=200, mimetype="text/event-stream")
  157. def length_prefixed_response(magic_number: int, response: Union[Mapping, Generator, RateLimitGenerator]) -> Response:
  158. """
  159. This function is used to return a response with a length prefix.
  160. Magic number is a one byte number that indicates the type of the response.
  161. For a compatibility with latest plugin daemon https://github.com/langgenius/dify-plugin-daemon/pull/341
  162. Avoid using line-based response, it leads a memory issue.
  163. We uses following format:
  164. | Field | Size | Description |
  165. |---------------|----------|---------------------------------|
  166. | Magic Number | 1 byte | Magic number identifier |
  167. | Reserved | 1 byte | Reserved field |
  168. | Header Length | 2 bytes | Header length (usually 0xa) |
  169. | Data Length | 4 bytes | Length of the data |
  170. | Reserved | 6 bytes | Reserved fields |
  171. | Data | Variable | Actual data content |
  172. | Reserved Fields | Header | Data |
  173. |-----------------|----------|----------|
  174. | 4 bytes total | Variable | Variable |
  175. all data is in little endian
  176. """
  177. def pack_response_with_length_prefix(response: bytes) -> bytes:
  178. header_length = 0xA
  179. data_length = len(response)
  180. # | Magic Number 1byte | Reserved 1byte | Header Length 2bytes | Data Length 4bytes | Reserved 6bytes | Data
  181. return struct.pack("<BBHI", magic_number, 0, header_length, data_length) + b"\x00" * 6 + response
  182. if isinstance(response, dict):
  183. return Response(
  184. response=pack_response_with_length_prefix(json.dumps(jsonable_encoder(response)).encode("utf-8")),
  185. status=200,
  186. mimetype="application/json",
  187. )
  188. elif isinstance(response, BaseModel):
  189. return Response(
  190. response=pack_response_with_length_prefix(response.model_dump_json().encode("utf-8")),
  191. status=200,
  192. mimetype="application/json",
  193. )
  194. def generate() -> Generator:
  195. for chunk in response:
  196. if isinstance(chunk, str):
  197. yield pack_response_with_length_prefix(chunk.encode("utf-8"))
  198. else:
  199. yield pack_response_with_length_prefix(chunk)
  200. return Response(stream_with_context(generate()), status=200, mimetype="text/event-stream")
  201. class TokenManager:
  202. @classmethod
  203. def generate_token(
  204. cls,
  205. token_type: str,
  206. account: Optional["Account"] = None,
  207. email: Optional[str] = None,
  208. additional_data: Optional[dict] = None,
  209. ) -> str:
  210. if account is None and email is None:
  211. raise ValueError("Account or email must be provided")
  212. account_id = account.id if account else None
  213. account_email = account.email if account else email
  214. if account_id:
  215. old_token = cls._get_current_token_for_account(account_id, token_type)
  216. if old_token:
  217. if isinstance(old_token, bytes):
  218. old_token = old_token.decode("utf-8")
  219. cls.revoke_token(old_token, token_type)
  220. token = str(uuid.uuid4())
  221. token_data = {"account_id": account_id, "email": account_email, "token_type": token_type}
  222. if additional_data:
  223. token_data.update(additional_data)
  224. expiry_minutes = dify_config.model_dump().get(f"{token_type.upper()}_TOKEN_EXPIRY_MINUTES")
  225. if expiry_minutes is None:
  226. raise ValueError(f"Expiry minutes for {token_type} token is not set")
  227. token_key = cls._get_token_key(token, token_type)
  228. expiry_time = int(expiry_minutes * 60)
  229. redis_client.setex(token_key, expiry_time, json.dumps(token_data))
  230. if account_id:
  231. cls._set_current_token_for_account(account_id, token, token_type, expiry_minutes)
  232. return token
  233. @classmethod
  234. def _get_token_key(cls, token: str, token_type: str) -> str:
  235. return f"{token_type}:token:{token}"
  236. @classmethod
  237. def revoke_token(cls, token: str, token_type: str):
  238. token_key = cls._get_token_key(token, token_type)
  239. redis_client.delete(token_key)
  240. @classmethod
  241. def get_token_data(cls, token: str, token_type: str) -> Optional[dict[str, Any]]:
  242. key = cls._get_token_key(token, token_type)
  243. token_data_json = redis_client.get(key)
  244. if token_data_json is None:
  245. logging.warning(f"{token_type} token {token} not found with key {key}")
  246. return None
  247. token_data: Optional[dict[str, Any]] = json.loads(token_data_json)
  248. return token_data
  249. @classmethod
  250. def _get_current_token_for_account(cls, account_id: str, token_type: str) -> Optional[str]:
  251. key = cls._get_account_token_key(account_id, token_type)
  252. current_token: Optional[str] = redis_client.get(key)
  253. return current_token
  254. @classmethod
  255. def _set_current_token_for_account(
  256. cls, account_id: str, token: str, token_type: str, expiry_hours: Union[int, float]
  257. ):
  258. key = cls._get_account_token_key(account_id, token_type)
  259. expiry_time = int(expiry_hours * 60 * 60)
  260. redis_client.setex(key, expiry_time, token)
  261. @classmethod
  262. def _get_account_token_key(cls, account_id: str, token_type: str) -> str:
  263. return f"{token_type}:account:{account_id}"
  264. class RateLimiter:
  265. def __init__(self, prefix: str, max_attempts: int, time_window: int):
  266. self.prefix = prefix
  267. self.max_attempts = max_attempts
  268. self.time_window = time_window
  269. def _get_key(self, email: str) -> str:
  270. return f"{self.prefix}:{email}"
  271. def is_rate_limited(self, email: str) -> bool:
  272. key = self._get_key(email)
  273. current_time = int(time.time())
  274. window_start_time = current_time - self.time_window
  275. redis_client.zremrangebyscore(key, "-inf", window_start_time)
  276. attempts = redis_client.zcard(key)
  277. if attempts and int(attempts) >= self.max_attempts:
  278. return True
  279. return False
  280. def increment_rate_limit(self, email: str):
  281. key = self._get_key(email)
  282. current_time = int(time.time())
  283. redis_client.zadd(key, {current_time: current_time})
  284. redis_client.expire(key, self.time_window * 2)