helpers.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. import base64
  2. import hashlib
  3. import hmac
  4. import os
  5. import time
  6. from configs import dify_config
  7. def get_signed_file_url(upload_file_id: str) -> str:
  8. url = f"{dify_config.FILES_URL}/files/{upload_file_id}/file-preview"
  9. timestamp = str(int(time.time()))
  10. nonce = os.urandom(16).hex()
  11. key = dify_config.SECRET_KEY.encode()
  12. msg = f"file-preview|{upload_file_id}|{timestamp}|{nonce}"
  13. sign = hmac.new(key, msg.encode(), hashlib.sha256).digest()
  14. encoded_sign = base64.urlsafe_b64encode(sign).decode()
  15. return f"{url}?timestamp={timestamp}&nonce={nonce}&sign={encoded_sign}"
  16. def get_signed_file_url_for_plugin(filename: str, mimetype: str, tenant_id: str, user_id: str) -> str:
  17. # Plugin access should use internal URL for Docker network communication
  18. base_url = dify_config.INTERNAL_FILES_URL or dify_config.FILES_URL
  19. url = f"{base_url}/files/upload/for-plugin"
  20. if user_id is None:
  21. user_id = "DEFAULT-USER"
  22. timestamp = str(int(time.time()))
  23. nonce = os.urandom(16).hex()
  24. key = dify_config.SECRET_KEY.encode()
  25. msg = f"upload|{filename}|{mimetype}|{tenant_id}|{user_id}|{timestamp}|{nonce}"
  26. sign = hmac.new(key, msg.encode(), hashlib.sha256).digest()
  27. encoded_sign = base64.urlsafe_b64encode(sign).decode()
  28. return f"{url}?timestamp={timestamp}&nonce={nonce}&sign={encoded_sign}&user_id={user_id}&tenant_id={tenant_id}"
  29. def verify_plugin_file_signature(
  30. *, filename: str, mimetype: str, tenant_id: str, user_id: str | None, timestamp: str, nonce: str, sign: str
  31. ) -> bool:
  32. if user_id is None:
  33. user_id = "DEFAULT-USER"
  34. data_to_sign = f"upload|{filename}|{mimetype}|{tenant_id}|{user_id}|{timestamp}|{nonce}"
  35. secret_key = dify_config.SECRET_KEY.encode()
  36. recalculated_sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  37. recalculated_encoded_sign = base64.urlsafe_b64encode(recalculated_sign).decode()
  38. # verify signature
  39. if sign != recalculated_encoded_sign:
  40. return False
  41. current_time = int(time.time())
  42. return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT
  43. def verify_image_signature(*, upload_file_id: str, timestamp: str, nonce: str, sign: str) -> bool:
  44. data_to_sign = f"image-preview|{upload_file_id}|{timestamp}|{nonce}"
  45. secret_key = dify_config.SECRET_KEY.encode()
  46. recalculated_sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  47. recalculated_encoded_sign = base64.urlsafe_b64encode(recalculated_sign).decode()
  48. # verify signature
  49. if sign != recalculated_encoded_sign:
  50. return False
  51. current_time = int(time.time())
  52. return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT
  53. def verify_file_signature(*, upload_file_id: str, timestamp: str, nonce: str, sign: str) -> bool:
  54. data_to_sign = f"file-preview|{upload_file_id}|{timestamp}|{nonce}"
  55. secret_key = dify_config.SECRET_KEY.encode()
  56. recalculated_sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  57. recalculated_encoded_sign = base64.urlsafe_b64encode(recalculated_sign).decode()
  58. # verify signature
  59. if sign != recalculated_encoded_sign:
  60. return False
  61. current_time = int(time.time())
  62. return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT
  63. def get_signed_document_proxy_url(dataset_id: str, document_id: str, filename: str) -> str:
  64. """Generate signed URL for document file proxy (for KKFileView)"""
  65. from urllib.parse import quote
  66. base_url = dify_config.CONSOLE_API_URL or ""
  67. # Encode filename for URL path
  68. encoded_filename = quote(filename)
  69. url = f"{base_url}/console/api/datasets/{dataset_id}/documents/{document_id}/file-proxy/{encoded_filename}"
  70. timestamp = str(int(time.time()))
  71. nonce = os.urandom(16).hex()
  72. key = dify_config.SECRET_KEY.encode()
  73. msg = f"document-proxy|{dataset_id}|{document_id}|{filename}|{timestamp}|{nonce}"
  74. sign = hmac.new(key, msg.encode(), hashlib.sha256).digest()
  75. encoded_sign = base64.urlsafe_b64encode(sign).decode()
  76. return f"{url}?timestamp={timestamp}&nonce={nonce}&sign={encoded_sign}"
  77. def verify_document_proxy_signature(
  78. *, dataset_id: str, document_id: str, filename: str, timestamp: str, nonce: str, sign: str
  79. ) -> bool:
  80. """Verify signature for document file proxy"""
  81. data_to_sign = f"document-proxy|{dataset_id}|{document_id}|{filename}|{timestamp}|{nonce}"
  82. secret_key = dify_config.SECRET_KEY.encode()
  83. recalculated_sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  84. recalculated_encoded_sign = base64.urlsafe_b64encode(recalculated_sign).decode()
  85. # verify signature
  86. if sign != recalculated_encoded_sign:
  87. return False
  88. current_time = int(time.time())
  89. return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT
  90. def generate_document_proxy_token(dataset_id: str, document_id: str, filename: str) -> str:
  91. """Generate a secure token for document file proxy access
  92. The token encodes all necessary information (dataset_id, document_id, filename,
  93. timestamp, nonce, and signature) into a single URL-safe base64 string.
  94. Args:
  95. dataset_id: Dataset UUID
  96. document_id: Document UUID
  97. filename: Original filename
  98. Returns:
  99. URL-safe base64-encoded token
  100. """
  101. import json
  102. timestamp = str(int(time.time()))
  103. nonce = os.urandom(16).hex()
  104. key = dify_config.SECRET_KEY.encode()
  105. msg = f"document-proxy|{dataset_id}|{document_id}|{filename}|{timestamp}|{nonce}"
  106. sign = hmac.new(key, msg.encode(), hashlib.sha256).digest()
  107. encoded_sign = base64.urlsafe_b64encode(sign).decode()
  108. # Create payload with all parameters
  109. payload = {
  110. "dataset_id": dataset_id,
  111. "document_id": document_id,
  112. "filename": filename,
  113. "timestamp": timestamp,
  114. "nonce": nonce,
  115. "sign": encoded_sign,
  116. }
  117. # Encode payload as base64 URL-safe string
  118. token_bytes = json.dumps(payload).encode('utf-8')
  119. token = base64.urlsafe_b64encode(token_bytes).decode('utf-8').rstrip('=')
  120. return token
  121. def verify_document_proxy_token(token: str) -> dict[str, str] | None:
  122. """Verify and decode a document file proxy token
  123. Args:
  124. token: Base64-encoded token from URL
  125. Returns:
  126. Dict with verified parameters (dataset_id, document_id, filename) if valid,
  127. None otherwise
  128. """
  129. import json
  130. try:
  131. # Add padding if needed
  132. padding = 4 - (len(token) % 4)
  133. if padding != 4:
  134. token += '=' * padding
  135. # Decode base64 token
  136. token_bytes = base64.urlsafe_b64decode(token)
  137. payload = json.loads(token_bytes.decode('utf-8'))
  138. # Extract parameters
  139. dataset_id = payload.get("dataset_id")
  140. document_id = payload.get("document_id")
  141. filename = payload.get("filename")
  142. timestamp = payload.get("timestamp")
  143. nonce = payload.get("nonce")
  144. sign = payload.get("sign")
  145. if not all([dataset_id, document_id, filename, timestamp, nonce, sign]):
  146. return None
  147. # Verify signature using existing function
  148. if not verify_document_proxy_signature(
  149. dataset_id=dataset_id,
  150. document_id=document_id,
  151. filename=filename,
  152. timestamp=timestamp,
  153. nonce=nonce,
  154. sign=sign
  155. ):
  156. return None
  157. # Return verified parameters
  158. return {
  159. "dataset_id": dataset_id,
  160. "document_id": document_id,
  161. "filename": filename,
  162. }
  163. except (ValueError, AttributeError, KeyError, json.JSONDecodeError):
  164. return None