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.

403 lines
17KB

  1. # -*- coding: utf-8 -*-
  2. from loguru import logger
  3. from . import http
  4. from . import exceptions
  5. from . import Bucket
  6. from .api import _make_range_string
  7. from .models import *
  8. from .compat import to_string, urlsplit, parse_qs
  9. from .crypto import BaseCryptoProvider
  10. from .exceptions import ClientError
  11. import copy
  12. import threading
  13. class CryptoBucket(Bucket):
  14. """用于加密Bucket和Object操作的类,诸如上传、下载Object等。创建、删除bucket的操作需使用Bucket类接口。
  15. 用法(假设Bucket属于杭州区域) ::
  16. >>> import oss2
  17. >>> auth = oss2.Auth('your-access-key-id', 'your-access-key-secret')
  18. >>> bucket = oss2.CryptoBucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'your-bucket', oss2.LocalRsaProvider())
  19. >>> bucket.put_object('readme.txt', 'content of the object')
  20. <oss2.models.PutObjectResult object at 0x029B9930>
  21. :param auth: 包含了用户认证信息的Auth对象
  22. :type auth: oss2.Auth
  23. :param str endpoint: 访问域名或者CNAME
  24. :param str bucket_name: Bucket名
  25. :param crypto_provider: 客户端加密类。该参数默认为空
  26. :type crypto_provider: oss2.crypto.BaseCryptoProvider
  27. :param bool is_cname: 如果endpoint是CNAME则设为True;反之,则为False。
  28. :param session: 会话。如果是None表示新开会话,非None则复用传入的会话
  29. :type session: oss2.Session
  30. :param float connect_timeout: 连接超时时间,以秒为单位。
  31. :param str app_name: 应用名。该参数不为空,则在User Agent中加入其值。
  32. 注意到,最终这个字符串是要作为HTTP Header的值传输的,所以必须要遵循HTTP标准。
  33. :param bool enable_crc: 如果开启crc校验则设为True;反之,则为False
  34. """
  35. def __init__(self, auth, endpoint, bucket_name, crypto_provider,
  36. is_cname=False,
  37. session=None,
  38. connect_timeout=None,
  39. app_name='',
  40. enable_crc=True,
  41. ):
  42. if not isinstance(crypto_provider, BaseCryptoProvider):
  43. raise ClientError('crypto_provider must be an instance of BaseCryptoProvider')
  44. logger.debug("Init CryptoBucket: {0}".format(bucket_name))
  45. super(CryptoBucket, self).__init__(auth, endpoint, bucket_name, is_cname, session, connect_timeout, app_name,
  46. enable_crc)
  47. self.crypto_provider = crypto_provider
  48. self.upload_contexts = {}
  49. self.upload_contexts_lock = threading.Lock()
  50. if self.app_name:
  51. self.user_agent = http.USER_AGENT + '/' + self.app_name + '/' + OSS_ENCRYPTION_CLIENT
  52. else:
  53. self.user_agent = http.USER_AGENT + '/' + OSS_ENCRYPTION_CLIENT
  54. def _init_user_agent(self, headers):
  55. if 'User-Agent' not in headers:
  56. headers['User-Agent'] = self.user_agent
  57. else:
  58. headers['User-Agent'] += '/' + OSS_ENCRYPTION_CLIENT
  59. def put_object(self, key, data,
  60. headers=None,
  61. progress_callback=None):
  62. """上传一个普通文件。
  63. 用法 ::
  64. >>> bucket.put_object('readme.txt', 'content of readme.txt')
  65. >>> with open(u'local_file.txt', 'rb') as f:
  66. >>> bucket.put_object('remote_file.txt', f)
  67. :param mat_desc: map,对象文件的description
  68. :param key: 上传到OSS的文件名
  69. :param data: 待上传的内容。
  70. :type data: bytes,str或file-like object
  71. :param headers: 用户指定的HTTP头部。可以指定Content-Type、Content-MD5、x-oss-meta-开头的头部等
  72. :type headers: 可以是dict,建议是oss2.CaseInsensitiveDict
  73. :param progress_callback: 用户指定的进度回调函数。可以用来实现进度条等功能。参考 :ref:`progress_callback` 。
  74. :return: :class:`PutObjectResult <oss2.models.PutObjectResult>`
  75. """
  76. logger.debug("Start to put object to CryptoBucket")
  77. headers = http.CaseInsensitiveDict(headers)
  78. self._init_user_agent(headers)
  79. content_crypto_material = self.crypto_provider.create_content_material()
  80. data = self.crypto_provider.make_encrypt_adapter(data, content_crypto_material.cipher)
  81. headers = content_crypto_material.to_object_meta(headers)
  82. return super(CryptoBucket, self).put_object(key, data, headers, progress_callback)
  83. def put_object_with_url(self, sign_url, data, headers=None, progress_callback=None):
  84. """ 使用加签的url上传对象
  85. :param sign_url: 加签的url
  86. :param data: 待上传的数据
  87. :param headers: 用户指定的HTTP头部。可以指定Content-Type、Content-MD5、x-oss-meta-开头的头部等,必须和签名时保持一致
  88. :param progress_callback: 用户指定的进度回调函数。参考 :ref:`progress_callback`
  89. :return:
  90. """
  91. raise ClientError("The operation is not support for CryptoBucket now")
  92. def append_object(self, key, position, data,
  93. headers=None,
  94. progress_callback=None,
  95. init_crc=None):
  96. raise ClientError("The operation is not support for CryptoBucket")
  97. def get_object(self, key,
  98. byte_range=None,
  99. headers=None,
  100. progress_callback=None,
  101. process=None,
  102. params=None):
  103. """下载一个文件。
  104. 用法 ::
  105. >>> result = bucket.get_object('readme.txt')
  106. >>> print(result.read())
  107. 'hello world'
  108. :param key: 文件名
  109. :param byte_range: 指定下载范围。参见 :ref:`byte_range`
  110. :param headers: HTTP头部
  111. :type headers: 可以是dict,建议是oss2.CaseInsensitiveDict
  112. :param progress_callback: 用户指定的进度回调函数。参考 :ref:`progress_callback`
  113. :param process: oss文件处理,如图像服务等。指定后process,返回的内容为处理后的文件。
  114. :param params: http 请求的查询字符串参数
  115. :type params: dict
  116. :return: file-like object
  117. :raises: 如果文件不存在,则抛出 :class:`NoSuchKey <oss2.exceptions.NoSuchKey>` ;还可能抛出其他异常
  118. """
  119. if process:
  120. raise ClientError("Process object operation is not support for Crypto Bucket")
  121. headers = http.CaseInsensitiveDict(headers)
  122. self._init_user_agent(headers)
  123. discard = 0
  124. range_string = ''
  125. if byte_range:
  126. if byte_range[0] is None and byte_range[1]:
  127. raise ClientError("Don't support range get while start is none and end is not")
  128. start, end = self.crypto_provider.adjust_range(byte_range[0], byte_range[1])
  129. adjust_byte_range = (start, end)
  130. range_string = _make_range_string(adjust_byte_range)
  131. if range_string:
  132. headers['range'] = range_string
  133. if byte_range[0] and adjust_byte_range[0] < byte_range[0]:
  134. discard = byte_range[0] - adjust_byte_range[0]
  135. logger.debug("adjust range of get object, byte_range: {0}, adjust_byte_range: {1}, discard: {2}".format(
  136. byte_range, adjust_byte_range, discard))
  137. logger.debug(
  138. "Start to get object from CryptoBucket: {0}, key: {1}, range: {2}, headers: {3}, params: {4}".format(
  139. self.bucket_name, to_string(key), range_string, headers, params))
  140. resp = self._do('GET', self.bucket_name, key, headers=headers, params=params)
  141. logger.debug("Get object done, req_id: {0}, status_code: {1}".format(resp.request_id, resp.status))
  142. return GetObjectResult(resp, progress_callback, self.enable_crc, crypto_provider=self.crypto_provider,
  143. discard=discard)
  144. def get_object_with_url(self, sign_url,
  145. byte_range=None,
  146. headers=None,
  147. progress_callback=None):
  148. """使用加签的url下载文件
  149. :param sign_url: 加签的url
  150. :param byte_range: 指定下载范围。参见 :ref:`byte_range`
  151. :param headers: HTTP头部
  152. :type headers: 可以是dict,建议是oss2.CaseInsensitiveDict,必须和签名时保持一致
  153. :param progress_callback: 用户指定的进度回调函数。参考 :ref:`progress_callback`
  154. :return: file-like object
  155. :raises: 如果文件不存在,则抛出 :class:`NoSuchKey <oss2.exceptions.NoSuchKey>` ;还可能抛出其他异常
  156. """
  157. query = parse_qs(urlsplit(sign_url).query)
  158. if query and (Bucket.PROCESS in query):
  159. raise ClientError("Process object operation is not support for Crypto Bucket")
  160. headers = http.CaseInsensitiveDict(headers)
  161. self._init_user_agent(headers)
  162. discard = 0
  163. range_string = ''
  164. if byte_range:
  165. if not byte_range[0] and byte_range[1]:
  166. raise ClientError("Don't support range get while start is none and end is not")
  167. start, end = self.crypto_provider.adjust_range(byte_range[0], byte_range[1])
  168. adjust_byte_range = (start, end)
  169. range_string = _make_range_string(adjust_byte_range)
  170. if range_string:
  171. headers['range'] = range_string
  172. if byte_range[0] and adjust_byte_range[0] < byte_range[0]:
  173. discard = byte_range[0] - adjust_byte_range[0]
  174. logger.debug("adjust range of get object, byte_range: {0}, adjust_byte_range: {1}, discard: {2}".format(
  175. byte_range, adjust_byte_range, discard))
  176. logger.debug(
  177. "Start to get object with url from CryptoBucket: {0}, sign_url: {1}, range: {2}, headers: {3}".format(
  178. self.bucket_name, sign_url, range_string, headers))
  179. resp = self._do_url('GET', sign_url, headers=headers)
  180. return GetObjectResult(resp, progress_callback, self.enable_crc,
  181. crypto_provider=self.crypto_provider, discard=discard)
  182. def create_select_object_meta(self, key, select_meta_params=None):
  183. raise ClientError("The operation is not support for Crypto Bucket")
  184. def select_object(self, key, sql,
  185. progress_callback=None,
  186. select_params=None
  187. ):
  188. raise ClientError("The operation is not support for CryptoBucket")
  189. def init_multipart_upload(self, key, headers=None, params=None, upload_context=None):
  190. """客户端加密初始化分片上传。
  191. :param params
  192. :param upload_context
  193. :param headers: HTTP头部
  194. :type headers: 可以是dict,建议是oss2.CaseInsensitiveDict
  195. :return: :class:`InitMultipartUploadResult <oss2.models.InitMultipartUploadResult>`
  196. 返回值中的 `crypto_multipart_context` 记录了加密Meta信息,在upload_part时需要一并传入
  197. """
  198. headers = http.CaseInsensitiveDict(headers)
  199. self._init_user_agent(headers)
  200. if not upload_context or not upload_context.data_size:
  201. raise ClientError("It is not support none upload_context and must specify data_size of upload_context ")
  202. logger.info("Start to init multipart upload by CryptoBucket, data_size: {0}, part_size: {1}".format(
  203. upload_context.data_size, upload_context.part_size))
  204. if upload_context.part_size:
  205. res = self.crypto_provider.cipher.is_valid_part_size(upload_context.part_size, upload_context.data_size)
  206. if not res:
  207. raise ClientError("part_size is invalid for multipart upload for CryptoBucket")
  208. else:
  209. upload_context.part_size = self.crypto_provider.cipher.determine_part_size(upload_context.data_size)
  210. content_crypto_material = self.crypto_provider.create_content_material()
  211. upload_context.content_crypto_material = content_crypto_material
  212. headers = content_crypto_material.to_object_meta(headers, upload_context)
  213. resp = super(CryptoBucket, self).init_multipart_upload(key, headers)
  214. return resp
  215. def upload_part(self, key, upload_id, part_number, data, progress_callback=None, headers=None, upload_context=None):
  216. """客户端加密上传一个分片。
  217. :param upload_context:
  218. :param str key: 待上传文件名,这个文件名要和 :func:`init_multipart_upload` 的文件名一致。
  219. :param str upload_id: 分片上传ID
  220. :param int part_number: 分片号,最小值是1.
  221. :param data: 待上传数据。
  222. :param progress_callback: 用户指定进度回调函数。可以用来实现进度条等功能。参考 :ref:`progress_callback` 。
  223. :param headers: 用户指定的HTTP头部。可以指定Content-MD5头部等
  224. :type headers: 可以是dict,建议是oss2.CaseInsensitiveDict
  225. :return: :class:`PutObjectResult <oss2.models.PutObjectResult>`
  226. """
  227. logger.info(
  228. "Start to upload multipart of CryptoBucket, upload_id = {0}, part_number = {1}".format(upload_id,
  229. part_number))
  230. headers = http.CaseInsensitiveDict(headers)
  231. self._init_user_agent(headers)
  232. if upload_context:
  233. context = upload_context
  234. else:
  235. raise ClientError("Could not init upload context, upload contexts flag is False and upload context is none")
  236. content_crypto_material = context.content_crypto_material
  237. if content_crypto_material.cek_alg != self.crypto_provider.cipher.alg or content_crypto_material.wrap_alg != \
  238. self.crypto_provider.wrap_alg:
  239. err_msg = 'Envelope or data encryption/decryption algorithm is inconsistent'
  240. raise InconsistentError(err_msg, self)
  241. headers = content_crypto_material.to_object_meta(headers, context)
  242. plain_key = self.crypto_provider.decrypt_encrypted_key(content_crypto_material.encrypted_key)
  243. plain_iv = self.crypto_provider.decrypt_encrypted_iv(content_crypto_material.encrypted_iv)
  244. offset = context.part_size * (part_number - 1)
  245. counter = self.crypto_provider.cipher.calc_offset(offset)
  246. cipher = copy.copy(content_crypto_material.cipher)
  247. cipher.initialize(plain_key, plain_iv, counter)
  248. data = self.crypto_provider.make_encrypt_adapter(data, cipher)
  249. resp = super(CryptoBucket, self).upload_part(key, upload_id, part_number, data, progress_callback, headers)
  250. return resp
  251. def complete_multipart_upload(self, key, upload_id, parts, headers=None):
  252. """客户端加密完成分片上传,创建文件。
  253. 当所有分片均已上传成功,才可以调用此函数
  254. :param str key: 待上传的文件名,这个文件名要和 :func:`init_multipart_upload` 的文件名一致。
  255. :param str upload_id: 分片上传ID
  256. :param parts: PartInfo列表。PartInfo中的part_number和etag是必填项。其中的etag可以从 :func:`upload_part` 的返回值中得到。
  257. :type parts: list of `PartInfo <oss2.models.PartInfo>`
  258. :param headers: HTTP头部
  259. :type headers: 可以是dict,建议是oss2.CaseInsensitiveDict
  260. :return: :class:`PutObjectResult <oss2.models.PutObjectResult>`
  261. """
  262. logger.info("Start to complete multipart upload of CryptoBucket, upload_id = {0}".format(upload_id))
  263. headers = http.CaseInsensitiveDict(headers)
  264. self._init_user_agent(headers)
  265. try:
  266. resp = super(CryptoBucket, self).complete_multipart_upload(key, upload_id, parts, headers)
  267. except exceptions as e:
  268. raise e
  269. return resp
  270. def abort_multipart_upload(self, key, upload_id, headers=None):
  271. """取消分片上传。
  272. :param headers: 可以是dict,建议是oss2.CaseInsensitiveDict
  273. :param str key: 待上传的文件名,这个文件名要和 :func:`init_multipart_upload` 的文件名一致。
  274. :param str upload_id: 分片上传ID
  275. :return: :class:`RequestResult <oss2.models.RequestResult>`
  276. """
  277. logger.info("Start to abort multipart upload of CryptoBucket, upload_id = {0}".format(upload_id))
  278. headers = http.CaseInsensitiveDict(headers)
  279. self._init_user_agent(headers)
  280. try:
  281. resp = super(CryptoBucket, self).abort_multipart_upload(key, upload_id)
  282. except exceptions as e:
  283. raise e
  284. return resp
  285. def upload_part_copy(self, source_bucket_name, source_key, byte_range, target_key, target_upload_id,
  286. target_part_number, headers=None):
  287. """分片拷贝。把一个已有文件的一部分或整体拷贝成目标文件的一个分片。
  288. :param target_part_number:
  289. :param target_upload_id:
  290. :param target_key:
  291. :param source_key:
  292. :param source_bucket_name:
  293. :param byte_range: 指定待拷贝内容在源文件里的范围。参见 :ref:`byte_range`
  294. :param headers: HTTP头部
  295. :type headers: 可以是dict,建议是oss2.CaseInsensitiveDict
  296. :return: :class:`PutObjectResult <oss2.models.PutObjectResult>`
  297. """
  298. raise ClientError("The operation is not support for CryptoBucket now")
  299. def process_object(self, key, process):
  300. raise ClientError("The operation is not support for CryptoBucket")