Esempio n. 1
0
    async def get_queue_metadata(self, queue_name, timeout=None):
        '''
        Retrieves user-defined metadata and queue properties on the specified
        queue. Metadata is associated with the queue as name-value pairs.

        :param str queue_name:
            The name of an existing queue.
        :param int timeout:
            The server timeout, expressed in seconds.
        :return:
            A dictionary representing the queue metadata with an 
            approximate_message_count int property on the dict estimating the 
            number of messages in the queue.
        :rtype: dict(str, str)
        '''
        _validate_not_none('queue_name', queue_name)
        request = HTTPRequest()
        request.method = 'GET'
        request.host_locations = self._get_host_locations(secondary=True)
        request.path = _get_path(queue_name)
        request.query = {
            'comp': 'metadata',
            'timeout': _int_to_str(timeout),
        }

        return await self._perform_request(request, _parse_metadata_and_message_count)
Esempio n. 2
0
def _update_entity(entity, if_match, encryption_required=False,
                   key_encryption_key=None, encryption_resolver=None):
    '''
    Constructs an update entity request.
    :param entity:
        The entity to insert. Could be a dict or an entity object.
    :param object key_encryption_key:
        The user-provided key-encryption-key. Must implement the following methods:
        wrap_key(key)--wraps the specified key using an algorithm of the user's choice.
        get_key_wrap_algorithm()--returns the algorithm used to wrap the specified symmetric key.
        get_kid()--returns a string key id for this key-encryption-key.
    :param function(partition_key, row_key, property_name) encryption_resolver:
        A function that takes in an entities partition key, row key, and property name and returns
        a boolean that indicates whether that property should be encrypted.
    '''
    _validate_not_none('if_match', if_match)
    _validate_entity(entity, key_encryption_key is not None)
    _validate_encryption_required(encryption_required, key_encryption_key)

    request = HTTPRequest()
    request.method = 'PUT'
    request.headers = {
        _DEFAULT_CONTENT_TYPE_HEADER[0]: _DEFAULT_CONTENT_TYPE_HEADER[1],
        _DEFAULT_ACCEPT_HEADER[0]: _DEFAULT_ACCEPT_HEADER[1],
        'If-Match': _to_str(if_match),
    }
    if key_encryption_key:
        entity = _encrypt_entity(entity, key_encryption_key, encryption_resolver)
    request.body = _get_request_body(_convert_entity_to_json(entity))

    return request
Esempio n. 3
0
def _validate_entity(entity, encrypt=None):
    # Validate entity exists
    _validate_not_none('entity', entity)

    # Entity inherits from dict, so just validating dict is fine
    if not isinstance(entity, dict):
        raise TypeError(_ERROR_INVALID_ENTITY_TYPE)

    # Validate partition key and row key are present
    _validate_object_has_param('PartitionKey', entity)
    _validate_object_has_param('RowKey', entity)

    # Two properties are added during encryption. Validate sufficient space
    max_properties = 255
    if encrypt:
        max_properties = max_properties - 2

    # Validate there are not more than 255 properties including Timestamp
    if (len(entity) > max_properties) or (len(entity) == max_properties and 'Timestamp' not in entity):
        raise ValueError(_ERROR_TOO_MANY_PROPERTIES)

    # Validate the property names are not too long
    for propname in entity:
        if len(propname) > 255:
            raise ValueError(_ERROR_PROPERTY_NAME_TOO_LONG)
Esempio n. 4
0
    async def set_queue_metadata(self, queue_name, metadata=None, timeout=None):
        '''
        Sets user-defined metadata on the specified queue. Metadata is
        associated with the queue as name-value pairs.

        :param str queue_name:
            The name of an existing queue.
        :param dict metadata:
            A dict containing name-value pairs to associate with the
            queue as metadata.
        :param int timeout:
            The server timeout, expressed in seconds.
        '''
        _validate_not_none('queue_name', queue_name)
        request = HTTPRequest()
        request.method = 'PUT'
        request.host_locations = self._get_host_locations()
        request.path = _get_path(queue_name)
        self._set_basic_headers(request)
        request.query = {
            'comp': 'metadata',
            'timeout': _int_to_str(timeout),
        }
        _add_metadata_headers(metadata, request)

        await self._perform_request(request)
Esempio n. 5
0
def _decrypt_entity(entity, encrypted_properties_list, content_encryption_key,
                    entityIV, isJavaV1):
    '''
    Decrypts the specified entity using AES256 in CBC mode with 128 bit padding. Unwraps the CEK 
    using either the specified KEK or the key returned by the key_resolver. Properties 
    specified in the encrypted_properties_list, will be decrypted and decoded to utf-8 strings.

    :param entity:
        The entity being retrieved and decrypted. Could be a dict or an entity object.
    :param list encrypted_properties_list:
        The encrypted list of all the properties that are encrypted.
    :param bytes[] content_encryption_key:
        The key used internally to encrypt the entity. Extrated from the entity metadata.
    :param bytes[] entityIV:
        The intialization vector used to seed the encryption algorithm. Extracted from the
        entity metadata.
    :return: The decrypted entity
    :rtype: Entity
    '''

    _validate_not_none('entity', entity)

    decrypted_entity = deepcopy(entity)
    try:
        for property in entity.keys():
            if property in encrypted_properties_list:
                value = entity[property]

                propertyIV = _generate_property_iv(entityIV,
                                                   entity['PartitionKey'],
                                                   entity['RowKey'], property,
                                                   isJavaV1)
                cipher = _generate_AES_CBC_cipher(content_encryption_key,
                                                  propertyIV)

                # Decrypt the property.
                decryptor = cipher.decryptor()
                decrypted_data = (decryptor.update(value.value) +
                                  decryptor.finalize())

                # Unpad the data.
                unpadder = PKCS7(128).unpadder()
                decrypted_data = (unpadder.update(decrypted_data) +
                                  unpadder.finalize())

                decrypted_data = decrypted_data.decode('utf-8')

                decrypted_entity[property] = decrypted_data

        decrypted_entity.pop('_ClientEncryptionMetadata1')
        decrypted_entity.pop('_ClientEncryptionMetadata2')
        return decrypted_entity
    except:
        raise AzureException(_ERROR_DECRYPTION_FAILURE)
Esempio n. 6
0
    async def create_queue(self, queue_name, metadata=None, fail_on_exist=False, timeout=None):
        '''
        Creates a queue under the given account.

        :param str queue_name:
            The name of the queue to create. A queue name must be from 3 through 
            63 characters long and may only contain lowercase letters, numbers, 
            and the dash (-) character. The first and last letters in the queue 
            must be alphanumeric. The dash (-) character cannot be the first or 
            last character. Consecutive dash characters are not permitted in the 
            queue name.
        :param metadata:
            A dict containing name-value pairs to associate with the queue as 
            metadata. Note that metadata names preserve the case with which they 
            were created, but are case-insensitive when set or read. 
        :type metadata: dict(str, str)
        :param bool fail_on_exist:
            Specifies whether to throw an exception if the queue already exists.
        :param int timeout:
            The server timeout, expressed in seconds.
        :return:
            A boolean indicating whether the queue was created. If fail_on_exist 
            was set to True, this will throw instead of returning false.
        :rtype: bool
        '''
        _validate_not_none('queue_name', queue_name)
        request = HTTPRequest()
        request.method = 'PUT'
        request.host_locations = self._get_host_locations()
        request.path = _get_path(queue_name)
        request.query = {'timeout': _int_to_str(timeout)}
        self._set_basic_headers(request)
        _add_metadata_headers(metadata, request)

        def _return_request(request):
            return request

        if not fail_on_exist:
            try:
                response = await self._perform_request(request, parser=_return_request)
                if response.status == _HTTP_RESPONSE_NO_CONTENT:
                    return False
                return True
            except AzureHttpError as ex:
                _dont_fail_on_exist(ex)
                return False
        else:
            response = await self._perform_request(request, parser=_return_request)
            if response.status == _HTTP_RESPONSE_NO_CONTENT:
                raise AzureConflictHttpError(
                    _ERROR_CONFLICT.format(response.message), response.status)
            return True
Esempio n. 7
0
def _encrypt_queue_message(message, key_encryption_key):
    '''
    Encrypts the given plain text message using AES256 in CBC mode with 128 bit padding.
    Wraps the generated content-encryption-key using the user-provided key-encryption-key (kek). 
    Returns a json-formatted string containing the encrypted message and the encryption metadata.

    :param object message:
        The plain text messge to be encrypted.
    :param object key_encryption_key:
        The user-provided key-encryption-key. Must implement the following methods:
        wrap_key(key)--wraps the specified key using an algorithm of the user's choice.
        get_key_wrap_algorithm()--returns the algorithm used to wrap the specified symmetric key.
        get_kid()--returns a string key id for this key-encryption-key.
    :return: A json-formatted string containing the encrypted message and the encryption metadata.
    :rtype: str
    '''

    _validate_not_none('message', message)
    _validate_not_none('key_encryption_key', key_encryption_key)
    _validate_key_encryption_key_wrap(key_encryption_key)

    # AES256 uses 256 bit (32 byte) keys and always with 16 byte blocks
    content_encryption_key = os.urandom(32)
    initialization_vector = os.urandom(16)

    # Queue encoding functions all return unicode strings, and encryption should
    # operate on binary strings.
    message = message.encode('utf-8')

    cipher = _generate_AES_CBC_cipher(content_encryption_key,
                                      initialization_vector)

    # PKCS7 with 16 byte blocks ensures compatibility with AES.
    padder = PKCS7(128).padder()
    padded_data = padder.update(message) + padder.finalize()

    # Encrypt the data.
    encryptor = cipher.encryptor()
    encrypted_data = encryptor.update(padded_data) + encryptor.finalize()

    # Build the dictionary structure.
    queue_message = {
        'EncryptedMessageContents':
        _encode_base64(encrypted_data),
        'EncryptionData':
        _generate_encryption_data_dict(key_encryption_key,
                                       content_encryption_key,
                                       initialization_vector)
    }

    return dumps(queue_message)
Esempio n. 8
0
    async def peek_messages(self, queue_name, num_messages=None, timeout=None):
        '''
        Retrieves one or more messages from the front of the queue, but does
        not alter the visibility of the message.

        Only messages that are visible may be retrieved. When a message is retrieved 
        for the first time with a call to get_messages, its dequeue_count property 
        is set to 1. If it is not deleted and is subsequently retrieved again, the 
        dequeue_count property is incremented. The client may use this value to 
        determine how many times a message has been retrieved. Note that a call 
        to peek_messages does not increment the value of DequeueCount, but returns 
        this value for the client to read.

        If the key-encryption-key or resolver field is set on the local service object, the messages will be
        decrypted before being returned.

        :param str queue_name:
            The name of the queue to peek messages from.
        :param int num_messages:
            A nonzero integer value that specifies the number of
            messages to peek from the queue, up to a maximum of 32. By default,
            a single message is peeked from the queue with this operation.
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: 
            A list of :class:`~azure.azure_async.queue.models.QueueMessage` objects. Note that
            time_next_visible and pop_receipt will not be populated as peek does 
            not pop the message and can only retrieve already visible messages.
        :rtype: list(:class:`~azure.azure_async.queue.models.QueueMessage`)
        '''

        _validate_decryption_required(self.require_encryption, self.key_encryption_key,
                                      self.key_resolver_function)

        _validate_not_none('queue_name', queue_name)
        request = HTTPRequest()
        request.method = 'GET'
        request.host_locations = self._get_host_locations(secondary=True)
        request.path = _get_path(queue_name, True)
        request.query = {
            'peekonly': 'true',
            'numofmessages': _to_str(num_messages),
            'timeout': _int_to_str(timeout)
        }

        return await self._perform_request(request, _convert_xml_to_queue_messages,
                                     [self.decode_function, self.require_encryption,
                                      self.key_encryption_key, self.key_resolver_function])
Esempio n. 9
0
    async def get_messages(self, queue_name, num_messages=None, visibility_timeout=None, timeout=None):
        '''
        Retrieves one or more messages from the front of the queue.

        When a message is retrieved from the queue, the response includes the message 
        content and a pop_receipt value, which is required to delete the message. 
        The message is not automatically deleted from the queue, but after it has 
        been retrieved, it is not visible to other clients for the time interval 
        specified by the visibility_timeout parameter.

        If the key-encryption-key or resolver field is set on the local service object, the messages will be
        decrypted before being returned.

        :param str queue_name:
            The name of the queue to get messages from.
        :param int num_messages:
            A nonzero integer value that specifies the number of
            messages to retrieve from the queue, up to a maximum of 32. If
            fewer are visible, the visible messages are returned. By default,
            a single message is retrieved from the queue with this operation.
        :param int visibility_timeout:
            Specifies the new visibility timeout value, in seconds, relative
            to server time. The new value must be larger than or equal to 1
            second, and cannot be larger than 7 days. The visibility timeout of 
            a message can be set to a value later than the expiry time.
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: A :class:`~azure.azure_async.queue.models.QueueMessage` object representing the information passed.
        :rtype: list(:class:`~azure.azure_async.queue.models.QueueMessage`)
        '''
        _validate_decryption_required(self.require_encryption, self.key_encryption_key,
                                      self.key_resolver_function)

        _validate_not_none('queue_name', queue_name)
        request = HTTPRequest()
        request.method = 'GET'
        request.host_locations = self._get_host_locations()
        request.path = _get_path(queue_name, True)
        request.query = {
            'numofmessages': _to_str(num_messages),
            'visibilitytimeout': _to_str(visibility_timeout),
            'timeout': _int_to_str(timeout)
        }

        return await self._perform_request(request, _convert_xml_to_queue_messages,
                                     [self.decode_function, self.require_encryption,
                                      self.key_encryption_key, self.key_resolver_function])
Esempio n. 10
0
    def generate_account_shared_access_signature(self, resource_types, permission,
                                                 expiry, start=None, ip=None, protocol=None):
        '''
        Generates a shared access signature for the queue service.
        Use the returned signature with the sas_token parameter of QueueService.

        :param ResourceTypes resource_types:
            Specifies the resource types that are accessible with the account SAS.
        :param AccountPermissions permission:
            The permissions associated with the shared access signature. The 
            user is restricted to operations allowed by the permissions. 
            Required unless an id is given referencing a stored access policy 
            which contains this field. This field must be omitted if it has been 
            specified in an associated stored access policy.
        :param expiry:
            The time at which the shared access signature becomes invalid. 
            Required unless an id is given referencing a stored access policy 
            which contains this field. This field must be omitted if it has 
            been specified in an associated stored access policy. Azure will always 
            convert values to UTC. If a date is passed in without timezone info, it 
            is assumed to be UTC.
        :type expiry: datetime or str
        :param start:
            The time at which the shared access signature becomes valid. If 
            omitted, start time for this call is assumed to be the time when the 
            azure_async service receives the request. Azure will always convert values
            to UTC. If a date is passed in without timezone info, it is assumed to 
            be UTC.
        :type start: datetime or str
        :param str ip:
            Specifies an IP address or a range of IP addresses from which to accept requests.
            If the IP address from which the request originates does not match the IP address
            or address range specified on the SAS token, the request is not authenticated.
            For example, specifying sip=168.1.5.65 or sip=168.1.5.60-168.1.5.70 on the SAS
            restricts the request to those IP addresses.
        :param str protocol:
            Specifies the protocol permitted for a request made. The default value
            is https,http. See :class:`~azure.azure_async.common.models.Protocol` for possible values.
        :return: A Shared Access Signature (sas) token.
        :rtype: str
        '''
        _validate_not_none('self.account_name', self.account_name)
        _validate_not_none('self.account_key', self.account_key)

        sas = QueueSharedAccessSignature(self.account_name, self.account_key)
        return sas.generate_account(Services.QUEUE, resource_types, permission,
                                    expiry, start=start, ip=ip, protocol=protocol)
Esempio n. 11
0
    async def clear_messages(self, queue_name, timeout=None):
        '''
        Deletes all messages from the specified queue.

        :param str queue_name:
            The name of the queue whose messages to clear.
        :param int timeout:
            The server timeout, expressed in seconds.
        '''
        _validate_not_none('queue_name', queue_name)
        request = HTTPRequest()
        request.method = 'DELETE'
        request.host_locations = self._get_host_locations()
        self._set_basic_headers(request)
        request.path = _get_path(queue_name, True)
        request.query = {'timeout': _int_to_str(timeout)}
        await self._perform_request(request)
Esempio n. 12
0
def _merge_entity(entity, if_match, require_encryption=False, key_encryption_key=None):
    '''
    Constructs a merge entity request.
    '''
    _validate_not_none('if_match', if_match)
    _validate_entity(entity)
    _validate_encryption_unsupported(require_encryption, key_encryption_key)

    request = HTTPRequest()
    request.method = 'MERGE'
    request.headers = {
        _DEFAULT_CONTENT_TYPE_HEADER[0]: _DEFAULT_CONTENT_TYPE_HEADER[1],
        _DEFAULT_ACCEPT_HEADER[0]: _DEFAULT_ACCEPT_HEADER[1],
        'If-Match': _to_str(if_match)
    }
    request.body = _get_request_body(_convert_entity_to_json(entity))

    return request
def _encrypt_blob(blob, key_encryption_key):
    '''
    Encrypts the given blob using AES256 in CBC mode with 128 bit padding.
    Wraps the generated content-encryption-key using the user-provided key-encryption-key (kek). 
    Returns a json-formatted string containing the encryption metadata. This method should
    only be used when a blob is small enough for single shot upload. Encrypting larger blobs
    is done as a part of the _upload_blob_chunks method.

    :param bytes blob:
        The blob to be encrypted.
    :param object key_encryption_key:
        The user-provided key-encryption-key. Must implement the following methods:
        wrap_key(key)--wraps the specified key using an algorithm of the user's choice.
        get_key_wrap_algorithm()--returns the algorithm used to wrap the specified symmetric key.
        get_kid()--returns a string key id for this key-encryption-key.
    :return: A tuple of json-formatted string containing the encryption metadata and the encrypted blob data.
    :rtype: (str, bytes)
    '''

    _validate_not_none('blob', blob)
    _validate_not_none('key_encryption_key', key_encryption_key)
    _validate_key_encryption_key_wrap(key_encryption_key)

    # AES256 uses 256 bit (32 byte) keys and always with 16 byte blocks
    content_encryption_key = urandom(32)
    initialization_vector = urandom(16)

    cipher = _generate_AES_CBC_cipher(content_encryption_key,
                                      initialization_vector)

    # PKCS7 with 16 byte blocks ensures compatibility with AES.
    padder = PKCS7(128).padder()
    padded_data = padder.update(blob) + padder.finalize()

    # Encrypt the data.
    encryptor = cipher.encryptor()
    encrypted_data = encryptor.update(padded_data) + encryptor.finalize()
    encryption_data = _generate_encryption_data_dict(key_encryption_key,
                                                     content_encryption_key,
                                                     initialization_vector)
    encryption_data['EncryptionMode'] = 'FullBlob'

    return dumps(encryption_data), encrypted_data
Esempio n. 14
0
def _decrypt(message, encryption_data, key_encryption_key=None, resolver=None):
    '''
    Decrypts the given ciphertext using AES256 in CBC mode with 128 bit padding.
    Unwraps the content-encryption-key using the user-provided or resolved key-encryption-key (kek). Returns the original plaintex.

    :param str message:
        The ciphertext to be decrypted.
    :param _EncryptionData encryption_data:
        The metadata associated with this ciphertext.
    :param object key_encryption_key:
        The user-provided key-encryption-key. Must implement the following methods:
        unwrap_key(key, algorithm)--returns the unwrapped form of the specified symmetric key using the string-specified algorithm.
        get_kid()--returns a string key id for this key-encryption-key.
    :param function resolver(kid):
        The user-provided key resolver. Uses the kid string to return a key-encryption-key implementing the interface defined above.
    :return: The decrypted plaintext.
    :rtype: str
    '''
    _validate_not_none('message', message)
    content_encryption_key = _validate_and_unwrap_cek(encryption_data,
                                                      key_encryption_key,
                                                      resolver)

    if not (_EncryptionAlgorithm.AES_CBC_256
            == encryption_data.encryption_agent.encryption_algorithm):
        raise ValueError(_ERROR_UNSUPPORTED_ENCRYPTION_ALGORITHM)

    cipher = _generate_AES_CBC_cipher(content_encryption_key,
                                      encryption_data.content_encryption_IV)

    # decrypt data
    decrypted_data = message
    decryptor = cipher.decryptor()
    decrypted_data = (decryptor.update(decrypted_data) + decryptor.finalize())

    # unpad data
    unpadder = PKCS7(128).unpadder()
    decrypted_data = (unpadder.update(decrypted_data) + unpadder.finalize())

    return decrypted_data
Esempio n. 15
0
    async def delete_queue(self, queue_name, fail_not_exist=False, timeout=None):
        '''
        Deletes the specified queue and any messages it contains.

        When a queue is successfully deleted, it is immediately marked for deletion 
        and is no longer accessible to clients. The queue is later removed from 
        the Queue service during garbage collection.

        Note that deleting a queue is likely to take at least 40 seconds to complete. 
        If an operation is attempted against the queue while it was being deleted, 
        an :class:`AzureConflictHttpError` will be thrown.

        :param str queue_name:
            The name of the queue to delete.
        :param bool fail_not_exist:
            Specifies whether to throw an exception if the queue doesn't exist.
        :param int timeout:
            The server timeout, expressed in seconds.
        :return:
            A boolean indicating whether the queue was deleted. If fail_not_exist 
            was set to True, this will throw instead of returning false.
        :rtype: bool
        '''
        _validate_not_none('queue_name', queue_name)
        request = HTTPRequest()
        request.method = 'DELETE'
        request.host_locations = self._get_host_locations()
        request.path = _get_path(queue_name)
        request.query = {'timeout': _int_to_str(timeout)}
        self._set_basic_headers(request)
        if not fail_not_exist:
            try:
                await self._perform_request(request)
                return True
            except AzureHttpError as ex:
                _dont_fail_not_exist(ex)
                return False
        else:
            await self._perform_request(request)
            return True
Esempio n. 16
0
    async def set_queue_acl(self, queue_name, signed_identifiers=None, timeout=None):
        '''
        Sets stored access policies for the queue that may be used with Shared 
        Access Signatures. 
        
        When you set permissions for a queue, the existing permissions are replaced. 
        To update the queue's permissions, call :func:`~get_queue_acl` to fetch 
        all access policies associated with the queue, modify the access policy 
        that you wish to change, and then call this function with the complete 
        set of data to perform the update.

        When you establish a stored access policy on a queue, it may take up to 
        30 seconds to take effect. During this interval, a shared access signature 
        that is associated with the stored access policy will throw an 
        :class:`AzureHttpError` until the access policy becomes active.

        :param str queue_name:
            The name of an existing queue.
        :param signed_identifiers:
            A dictionary of access policies to associate with the queue. The 
            dictionary may contain up to 5 elements. An empty dictionary 
            will clear the access policies set on the service. 
        :type signed_identifiers: dict(str, :class:`~azure.azure_async.common.models.AccessPolicy`)
        :param int timeout:
            The server timeout, expressed in seconds.
        '''
        _validate_not_none('queue_name', queue_name)
        _validate_access_policies(signed_identifiers)
        request = HTTPRequest()
        request.method = 'PUT'
        request.host_locations = self._get_host_locations()
        request.path = _get_path(queue_name)
        self._set_basic_headers(request)
        request.query = {
            'comp': 'acl',
            'timeout': _int_to_str(timeout),
        }
        request.body = _get_request_body(
            _convert_signed_identifiers_to_xml(signed_identifiers))
        await self._perform_request(request)
Esempio n. 17
0
    async def get_queue_acl(self, queue_name, timeout=None):
        '''
        Returns details about any stored access policies specified on the
        queue that may be used with Shared Access Signatures.

        :param str queue_name:
            The name of an existing queue.
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: A dictionary of access policies associated with the queue.
        :rtype: dict(str, :class:`~azure.azure_async.common.models.AccessPolicy`)
        '''
        _validate_not_none('queue_name', queue_name)
        request = HTTPRequest()
        request.method = 'GET'
        request.host_locations = self._get_host_locations(secondary=True)
        request.path = _get_path(queue_name)
        request.query = {
            'comp': 'acl',
            'timeout': _int_to_str(timeout),
        }

        return await self._perform_request(request, _convert_xml_to_signed_identifiers)
Esempio n. 18
0
def _get_entity(partition_key, row_key, select, accept):
    '''
    Constructs a get entity request.
    '''
    _validate_not_none('partition_key', partition_key)
    _validate_not_none('row_key', row_key)
    _validate_not_none('accept', accept)
    request = HTTPRequest()
    request.method = 'GET'
    request.headers = {'Accept': _to_str(accept)}
    request.query = {'$select': _to_str(select)}

    return request
Esempio n. 19
0
def _delete_entity(partition_key, row_key, if_match):
    '''
     Constructs a delete entity request.
    '''
    _validate_not_none('if_match', if_match)
    _validate_not_none('partition_key', partition_key)
    _validate_not_none('row_key', row_key)
    request = HTTPRequest()
    request.method = 'DELETE'
    request.headers = {
        _DEFAULT_ACCEPT_HEADER[0]: _DEFAULT_ACCEPT_HEADER[1],
        'If-Match': _to_str(if_match)
    }

    return request
Esempio n. 20
0
    async def delete_message(self, queue_name, message_id, pop_receipt, timeout=None):
        '''
        Deletes the specified message.

        Normally after a client retrieves a message with the get_messages operation, 
        the client is expected to process and delete the message. To delete the 
        message, you must have two items of data: id and pop_receipt. The 
        id is returned from the previous get_messages operation. The 
        pop_receipt is returned from the most recent :func:`~get_messages` or 
        :func:`~update_message` operation. In order for the delete_message operation 
        to succeed, the pop_receipt specified on the request must match the 
        pop_receipt returned from the :func:`~get_messages` or :func:`~update_message` 
        operation. 

        :param str queue_name:
            The name of the queue from which to delete the message.
        :param str message_id:
            The message id identifying the message to delete.
        :param str pop_receipt:
            A valid pop receipt value returned from an earlier call
            to the :func:`~get_messages` or :func:`~update_message`.
        :param int timeout:
            The server timeout, expressed in seconds.
        '''
        _validate_not_none('queue_name', queue_name)
        _validate_not_none('message_id', message_id)
        _validate_not_none('pop_receipt', pop_receipt)
        request = HTTPRequest()
        request.method = 'DELETE'
        request.host_locations = self._get_host_locations()
        request.path = _get_path(queue_name, True, message_id)
        self._set_basic_headers(request)
        request.query = {
            'popreceipt': _to_str(pop_receipt),
            'timeout': _int_to_str(timeout)
        }
        await self._perform_request(request)
    async def append_blob_from_bytes(self,
                                     container_name,
                                     blob_name,
                                     blob,
                                     index=0,
                                     count=None,
                                     validate_content=False,
                                     maxsize_condition=None,
                                     progress_callback=None,
                                     lease_id=None,
                                     timeout=None):
        '''
        Appends to the content of an existing blob from an array of bytes, with
        automatic chunking and progress notifications.

        :param str container_name:
            Name of existing container.
        :param str blob_name:
            Name of blob to create or update.
        :param bytes blob:
            Content of blob as an array of bytes.
        :param int index:
            Start index in the array of bytes.
        :param int count:
            Number of bytes to upload. Set to None or negative value to upload
            all bytes starting from index.
        :param bool validate_content:
            If true, calculates an MD5 hash for each chunk of the blob. The azure_async
            service checks the hash of the content that has arrived with the hash 
            that was sent. This is primarily valuable for detecting bitflips on 
            the wire if using http instead of https as https (the default) will 
            already validate. Note that this MD5 hash is not stored with the 
            blob.
        :param int maxsize_condition:
            Optional conditional header. The max length in bytes permitted for
            the append blob. If the Append Block operation would cause the blob
            to exceed that limit or if the blob size is already greater than the
            value specified in this header, the request will fail with
            MaxBlobSizeConditionNotMet error (HTTP status code 412 - Precondition Failed).
        :param progress_callback:
            Callback for progress with signature function(current, total) where
            current is the number of bytes transfered so far, and total is the
            size of the blob, or None if the total size is unknown.
        :type progress_callback: func(current, total)
        :param str lease_id:
            Required if the blob has an active lease.
        :param int timeout:
            The timeout parameter is expressed in seconds. This method may make 
            multiple calls to the Azure service and the timeout will apply to 
            each call individually.
        :return: ETag and last modified properties for the Append Blob
        :rtype: :class:`~azure.azure_async.blob.models.ResourceProperties`
        '''
        _validate_not_none('container_name', container_name)
        _validate_not_none('blob_name', blob_name)
        _validate_not_none('blob', blob)
        _validate_not_none('index', index)
        _validate_type_bytes('blob', blob)
        _validate_encryption_unsupported(self.require_encryption,
                                         self.key_encryption_key)

        if index < 0:
            raise IndexError(_ERROR_VALUE_NEGATIVE.format('index'))

        if count is None or count < 0:
            count = len(blob) - index

        stream = BytesIO(blob)
        stream.seek(index)

        return await self.append_blob_from_stream(
            container_name,
            blob_name,
            stream,
            count=count,
            validate_content=validate_content,
            maxsize_condition=maxsize_condition,
            lease_id=lease_id,
            progress_callback=progress_callback,
            timeout=timeout)
    async def append_block(self,
                           container_name,
                           blob_name,
                           block,
                           validate_content=False,
                           maxsize_condition=None,
                           appendpos_condition=None,
                           lease_id=None,
                           if_modified_since=None,
                           if_unmodified_since=None,
                           if_match=None,
                           if_none_match=None,
                           timeout=None):
        '''
        Commits a new block of data to the end of an existing append blob.
        
        :param str container_name:
            Name of existing container.
        :param str blob_name:
            Name of existing blob.
        :param bytes block:
            Content of the block in bytes.
        :param bool validate_content:
            If true, calculates an MD5 hash of the block content. The azure_async
            service checks the hash of the content that has arrived
            with the hash that was sent. This is primarily valuable for detecting 
            bitflips on the wire if using http instead of https as https (the default) 
            will already validate. Note that this MD5 hash is not stored with the 
            blob.
        :param int maxsize_condition:
            Optional conditional header. The max length in bytes permitted for
            the append blob. If the Append Block operation would cause the blob
            to exceed that limit or if the blob size is already greater than the
            value specified in this header, the request will fail with
            MaxBlobSizeConditionNotMet error (HTTP status code 412 - Precondition Failed).
        :param int appendpos_condition:
            Optional conditional header, used only for the Append Block operation.
            A number indicating the byte offset to compare. Append Block will
            succeed only if the append position is equal to this number. If it
            is not, the request will fail with the
            AppendPositionConditionNotMet error
            (HTTP status code 412 - Precondition Failed).
        :param str lease_id:
            Required if the blob has an active lease.
        :param datetime if_modified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC. 
            Specify this header to perform the operation only
            if the resource has been modified since the specified time.
        :param datetime if_unmodified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC.
            Specify this header to perform the operation only if
            the resource has not been modified since the specified date/time.
        :param str if_match:
            An ETag value, or the wildcard character (*). Specify this header to perform
            the operation only if the resource's ETag matches the value specified.
        :param str if_none_match:
            An ETag value, or the wildcard character (*). Specify this header
            to perform the operation only if the resource's ETag does not match
            the value specified. Specify the wildcard character (*) to perform
            the operation only if the resource does not exist, and fail the
            operation if it does exist.
        :param int timeout:
            The timeout parameter is expressed in seconds.
        :return:
            ETag, last modified, append offset, and committed block count 
            properties for the updated Append Blob
        :rtype: :class:`~azure.azure_async.blob.models.AppendBlockProperties`
        '''
        _validate_not_none('container_name', container_name)
        _validate_not_none('blob_name', blob_name)
        _validate_not_none('block', block)
        _validate_encryption_unsupported(self.require_encryption,
                                         self.key_encryption_key)

        request = HTTPRequest()
        request.method = 'PUT'
        request.host_locations = self._get_host_locations()
        request.path = _get_path(container_name, blob_name)
        request.query = {
            'comp': 'appendblock',
            'timeout': _int_to_str(timeout),
        }
        request.headers = {
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate',
            'Host': f'{self.account_name}.blob.core.windows.net',
            'Content-Type': 'application/octet-stream',
            'x-ms-blob-condition-maxsize': _to_str(maxsize_condition),
            'x-ms-blob-condition-appendpos': _to_str(appendpos_condition),
            'x-ms-lease-id': _to_str(lease_id),
            'If-Modified-Since': _datetime_to_utc_string(if_modified_since),
            'If-Unmodified-Since':
            _datetime_to_utc_string(if_unmodified_since),
            'If-Match': _to_str(if_match),
            'If-None-Match': _to_str(if_none_match)
        }
        request.body = _get_data_bytes_only('block', block)

        if validate_content:
            computed_md5 = _get_content_md5(request.body)
            request.headers['Content-MD5'] = _to_str(computed_md5)

        return await self._perform_request(request, _parse_append_block)
    async def create_blob(self,
                          container_name,
                          blob_name,
                          content_settings=None,
                          metadata=None,
                          lease_id=None,
                          if_modified_since=None,
                          if_unmodified_since=None,
                          if_match=None,
                          if_none_match=None,
                          timeout=None):
        '''
        Creates a blob or overrides an existing blob. Use if_match=* to
        prevent overriding an existing blob. 

        See create_blob_from_* for high level
        functions that handle the creation and upload of large blobs with
        automatic chunking and progress notifications.

        :param str container_name:
            Name of existing container.
        :param str blob_name:
            Name of blob to create or update.
        :param ~azure.azure_async.blob.models.ContentSettings content_settings:
            ContentSettings object used to set blob properties.
        :param metadata:
            Name-value pairs associated with the blob as metadata.
        :type metadata: dict(str, str)
        :param str lease_id:
            Required if the blob has an active lease.
        :param datetime if_modified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC. 
            Specify this header to perform the operation only
            if the resource has been modified since the specified time.
        :param datetime if_unmodified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC.
            Specify this header to perform the operation only if
            the resource has not been modified since the specified date/time.
        :param str if_match:
            An ETag value, or the wildcard character (*). Specify this header to
            perform the operation only if the resource's ETag matches the value specified.
        :param str if_none_match:
            An ETag value, or the wildcard character (*). Specify this header
            to perform the operation only if the resource's ETag does not match
            the value specified. Specify the wildcard character (*) to perform
            the operation only if the resource does not exist, and fail the
            operation if it does exist.
        :param int timeout:
            The timeout parameter is expressed in seconds.
        :return: ETag and last modified properties for the updated Append Blob
        :rtype: :class:`~azure.azure_async.blob.models.ResourceProperties`
        '''
        _validate_not_none('container_name', container_name)
        _validate_not_none('blob_name', blob_name)
        _validate_encryption_unsupported(self.require_encryption,
                                         self.key_encryption_key)

        request = HTTPRequest()
        request.method = 'PUT'
        request.host_locations = self._get_host_locations()
        request.path = _get_path(container_name, blob_name)
        request.query = {'timeout': _int_to_str(timeout)}
        request.headers = {
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate',
            'Host': f'{self.account_name}.blob.core.windows.net',
            'Content-Type': 'application/octet-stream',
            'x-ms-blob-type': _to_str(self.blob_type),
            'x-ms-lease-id': _to_str(lease_id),
            'If-Modified-Since': _datetime_to_utc_string(if_modified_since),
            'If-Unmodified-Since':
            _datetime_to_utc_string(if_unmodified_since),
            'If-Match': _to_str(if_match),
            'If-None-Match': _to_str(if_none_match)
        }
        _add_metadata_headers(metadata, request)
        if content_settings is not None:
            request.headers.update(content_settings._to_headers())

        return await self._perform_request(request, _parse_base_properties)
Esempio n. 24
0
    async def update_message(self, queue_name, message_id, pop_receipt, visibility_timeout, content=None, timeout=None):
        '''
        Updates the visibility timeout of a message. You can also use this
        operation to update the contents of a message.

        This operation can be used to continually extend the invisibility of a 
        queue message. This functionality can be useful if you want a worker role 
        to "lease" a queue message. For example, if a worker role calls get_messages 
        and recognizes that it needs more time to process a message, it can 
        continually extend the message's invisibility until it is processed. If 
        the worker role were to fail during processing, eventually the message 
        would become visible again and another worker role could process it.

        If the key-encryption-key field is set on the local service object, this method will
        encrypt the content before uploading.

        :param str queue_name:
            The name of the queue containing the message to update.
        :param str message_id:
            The message id identifying the message to update.
        :param str pop_receipt:
            A valid pop receipt value returned from an earlier call
            to the :func:`~get_messages` or :func:`~update_message` operation.
        :param int visibility_timeout:
            Specifies the new visibility timeout value, in seconds,
            relative to server time. The new value must be larger than or equal
            to 0, and cannot be larger than 7 days. The visibility timeout of a
            message cannot be set to a value later than the expiry time. A
            message can be updated until it has been deleted or has expired.
        :param obj content:
            Message content. Allowed type is determined by the encode_function 
            set on the service. Default is str.
        :param int timeout:
            The server timeout, expressed in seconds.
        :return: 
            A list of :class:`~azure.azure_async.queue.models.QueueMessage` objects. For convenience,
            this object is also populated with the content, although it is not returned by the service.
        :rtype: list(:class:`~azure.azure_async.queue.models.QueueMessage`)
        '''

        _validate_encryption_required(self.require_encryption, self.key_encryption_key)

        _validate_not_none('queue_name', queue_name)
        _validate_not_none('message_id', message_id)
        _validate_not_none('pop_receipt', pop_receipt)
        _validate_not_none('visibility_timeout', visibility_timeout)
        request = HTTPRequest()
        request.method = 'PUT'
        request.host_locations = self._get_host_locations()
        self._set_basic_headers(request)
        request.path = _get_path(queue_name, True, message_id)
        request.query = {
            'popreceipt': _to_str(pop_receipt),
            'visibilitytimeout': _int_to_str(visibility_timeout),
            'timeout': _int_to_str(timeout)
        }

        if content is not None:
            request.body = _get_request_body(_convert_queue_message_xml(content, self.encode_function,
                                                                        self.key_encryption_key))

        return await self._perform_request(request, _parse_queue_message_from_headers)
Esempio n. 25
0
def _extract_encryption_metadata(entity, require_encryption,
                                 key_encryption_key, key_resolver):
    '''
    Extracts the encryption metadata from the given entity, setting them to be utf-8 strings.
    If no encryption metadata is present, will return None for all return values unless
    require_encryption is true, in which case the method will throw.

    :param entity:
        The entity being retrieved and decrypted. Could be a dict or an entity object.
    :param bool require_encryption:
        If set, will enforce that the retrieved entity is encrypted and decrypt it.
    :param object key_encryption_key:
        The user-provided key-encryption-key. Must implement the following methods:
        unwrap_key(key, algorithm)--returns the unwrapped form of the specified symmetric key using the 
        string-specified algorithm.
        get_kid()--returns a string key id for this key-encryption-key.
    :param function key_resolver(kid):
        The user-provided key resolver. Uses the kid string to return a key-encryption-key implementing
        the interface defined above.
    :returns: a tuple containing the entity iv, the list of encrypted properties, the entity cek,
        and whether the entity was encrypted using JavaV1.
    :rtype: tuple (bytes[], list, bytes[], bool)
    '''
    _validate_not_none('entity', entity)

    try:
        encrypted_properties_list = _decode_base64_to_bytes(
            entity['_ClientEncryptionMetadata2'])
        encryption_data = entity['_ClientEncryptionMetadata1']
        encryption_data = _dict_to_encryption_data(loads(encryption_data))
    except Exception:
        # Message did not have properly formatted encryption metadata.
        if require_encryption:
            raise ValueError(_ERROR_ENTITY_NOT_ENCRYPTED)
        else:
            return None, None, None, None

    if not (encryption_data.encryption_agent.encryption_algorithm
            == _EncryptionAlgorithm.AES_CBC_256):
        raise ValueError(_ERROR_UNSUPPORTED_ENCRYPTION_ALGORITHM)

    content_encryption_key = _validate_and_unwrap_cek(encryption_data,
                                                      key_encryption_key,
                                                      key_resolver)

    # Special check for compatibility with Java V1 encryption protocol.
    isJavaV1 = (encryption_data.key_wrapping_metadata is None) or \
               ((encryption_data.encryption_agent.protocol == _ENCRYPTION_PROTOCOL_V1) and
                'EncryptionLibrary' in encryption_data.key_wrapping_metadata and
                'Java' in encryption_data.key_wrapping_metadata['EncryptionLibrary'])

    metadataIV = _generate_property_iv(encryption_data.content_encryption_IV,
                                       entity['PartitionKey'],
                                       entity['RowKey'],
                                       '_ClientEncryptionMetadata2', isJavaV1)

    cipher = _generate_AES_CBC_cipher(content_encryption_key, metadataIV)

    # Decrypt the data.
    decryptor = cipher.decryptor()
    encrypted_properties_list = decryptor.update(
        encrypted_properties_list) + decryptor.finalize()

    # Unpad the data.
    unpadder = PKCS7(128).unpadder()
    encrypted_properties_list = unpadder.update(
        encrypted_properties_list) + unpadder.finalize()

    encrypted_properties_list = encrypted_properties_list.decode('utf-8')

    if isJavaV1:
        # Strip the square braces from the ends and split string into list.
        encrypted_properties_list = encrypted_properties_list[1:-1]
        encrypted_properties_list = encrypted_properties_list.split(', ')
    else:
        encrypted_properties_list = loads(encrypted_properties_list)

    return encryption_data.content_encryption_IV, encrypted_properties_list, content_encryption_key, isJavaV1
Esempio n. 26
0
    async def put_message(self, queue_name, content, visibility_timeout=None, time_to_live=None, timeout=None):
        '''
        Adds a new message to the back of the message queue. 

        The visibility timeout specifies the time that the message will be 
        invisible. After the timeout expires, the message will become visible. 
        If a visibility timeout is not specified, the default value of 0 is used.

        The message time-to-live specifies how long a message will remain in the 
        queue. The message will be deleted from the queue when the time-to-live 
        period expires.

        If the key-encryption-key field is set on the local service object, this method will
        encrypt the content before uploading.

        :param str queue_name:
            The name of the queue to put the message into.
        :param obj content:
            Message content. Allowed type is determined by the encode_function 
            set on the service. Default is str. The encoded message can be up to 
            64KB in size.
        :param int visibility_timeout:
            If not specified, the default value is 0. Specifies the
            new visibility timeout value, in seconds, relative to server time.
            The value must be larger than or equal to 0, and cannot be
            larger than 7 days. The visibility timeout of a message cannot be
            set to a value later than the expiry time. visibility_timeout
            should be set to a value smaller than the time-to-live value.
        :param int time_to_live:
            Specifies the time-to-live interval for the message, in
            seconds. The maximum time-to-live allowed is 7 days. If this
            parameter is omitted, the default time-to-live is 7 days.
        :param int timeout:
            The server timeout, expressed in seconds.
        :return:
            A :class:`~azure.azure_async.queue.models.QueueMessage` object.
            This object is also populated with the content although it is not
            returned from the service.
        :rtype: :class:`~azure.azure_async.queue.models.QueueMessage`
        '''

        _validate_encryption_required(self.require_encryption, self.key_encryption_key)

        _validate_not_none('queue_name', queue_name)
        _validate_not_none('content', content)
        request = HTTPRequest()
        request.method = 'POST'
        request.host_locations = self._get_host_locations()
        request.path = _get_path(queue_name, True)
        self._set_basic_headers(request)
        request.query = {
            'visibilitytimeout': _to_str(visibility_timeout),
            'messagettl': _to_str(time_to_live),
            'timeout': _int_to_str(timeout)
        }

        request.body = _get_request_body(_convert_queue_message_xml(content, self.encode_function,
                                                                    self.key_encryption_key))

        message_list = await self._perform_request(request,
                                                   _convert_xml_to_queue_messages,
                                                    [self.decode_function, False, None, None, content])
        return message_list[0]
Esempio n. 27
0
def _encrypt_entity(entity, key_encryption_key, encryption_resolver):
    '''
    Encrypts the given entity using AES256 in CBC mode with 128 bit padding.
    Will generate a content-encryption-key (cek) to encrypt the properties either
    stored in an EntityProperty with the 'encrypt' flag set or those
    specified by the encryption resolver. This cek is then wrapped using the 
    provided key_encryption_key (kek). Only strings may be encrypted and the
    result is stored as binary on the service. 

    :param entity:
        The entity to insert. Could be a dict or an entity object.
    :param object key_encryption_key:
        The user-provided key-encryption-key. Must implement the following methods:
        wrap_key(key)--wraps the specified key using an algorithm of the user's choice.
        get_key_wrap_algorithm()--returns the algorithm used to wrap the specified symmetric key.
        get_kid()--returns a string key id for this key-encryption-key.
    :param function(partition_key, row_key, property_name) encryption_resolver:
        A function that takes in an entities partition key, row key, and property name and returns 
        a boolean that indicates whether that property should be encrypted.
    :return: An entity with both the appropriate properties encrypted and the 
        encryption data.
    :rtype: object
    '''

    _validate_not_none('entity', entity)
    _validate_not_none('key_encryption_key', key_encryption_key)
    _validate_key_encryption_key_wrap(key_encryption_key)

    # AES256 uses 256 bit (32 byte) keys and always with 16 byte blocks
    content_encryption_key = os.urandom(32)
    entity_initialization_vector = os.urandom(16)

    encrypted_properties = []
    encrypted_entity = Entity()
    for key, value in entity.items():
        # If the property resolver says it should be encrypted
        # or it is an EntityProperty with the 'encrypt' property set.
        if (isinstance(value, EntityProperty) and value.encrypt) or \
                (encryption_resolver is not None \
                         and encryption_resolver(entity['PartitionKey'], entity['RowKey'], key)):

            # Only strings can be encrypted and None is not an instance of str.
            if isinstance(value, EntityProperty):
                if value.type == EdmType.STRING:
                    value = value.value
                else:
                    raise ValueError(_ERROR_UNSUPPORTED_TYPE_FOR_ENCRYPTION)
            if not isinstance(value, str):
                raise ValueError(_ERROR_UNSUPPORTED_TYPE_FOR_ENCRYPTION)

                # Value is now confirmed to hold a valid string value to be encrypted
            # and should be added to the list of encrypted properties.
            encrypted_properties.append(key)

            propertyIV = _generate_property_iv(entity_initialization_vector,
                                               entity['PartitionKey'],
                                               entity['RowKey'], key, False)

            # Encode the strings for encryption.
            value = value.encode('utf-8')

            cipher = _generate_AES_CBC_cipher(content_encryption_key,
                                              propertyIV)

            # PKCS7 with 16 byte blocks ensures compatibility with AES.
            padder = PKCS7(128).padder()
            padded_data = padder.update(value) + padder.finalize()

            # Encrypt the data.
            encryptor = cipher.encryptor()
            encrypted_data = encryptor.update(
                padded_data) + encryptor.finalize()

            # Set the new value of this key to be a binary EntityProperty for proper serialization.
            value = EntityProperty(EdmType.BINARY, encrypted_data)

        encrypted_entity[key] = value

    encrypted_properties = dumps(encrypted_properties)

    # Generate the metadata iv.
    metadataIV = _generate_property_iv(entity_initialization_vector,
                                       entity['PartitionKey'],
                                       entity['RowKey'],
                                       '_ClientEncryptionMetadata2', False)

    encrypted_properties = encrypted_properties.encode('utf-8')

    cipher = _generate_AES_CBC_cipher(content_encryption_key, metadataIV)

    padder = PKCS7(128).padder()
    padded_data = padder.update(encrypted_properties) + padder.finalize()

    encryptor = cipher.encryptor()
    encrypted_data = encryptor.update(padded_data) + encryptor.finalize()

    encrypted_entity['_ClientEncryptionMetadata2'] = EntityProperty(
        EdmType.BINARY, encrypted_data)

    encryption_data = _generate_encryption_data_dict(
        key_encryption_key, content_encryption_key,
        entity_initialization_vector)

    encrypted_entity['_ClientEncryptionMetadata1'] = dumps(encryption_data)
    return encrypted_entity
    async def append_blob_from_text(self,
                                    container_name,
                                    blob_name,
                                    text,
                                    encoding='utf-8',
                                    validate_content=False,
                                    maxsize_condition=None,
                                    progress_callback=None,
                                    lease_id=None,
                                    timeout=None):
        '''
        Appends to the content of an existing blob from str/unicode, with
        automatic chunking and progress notifications.

        :param str container_name:
            Name of existing container.
        :param str blob_name:
            Name of blob to create or update.
        :param str text:
            Text to upload to the blob.
        :param str encoding:
            Python encoding to use to convert the text to bytes.
        :param bool validate_content:
            If true, calculates an MD5 hash for each chunk of the blob. The azure_async
            service checks the hash of the content that has arrived with the hash 
            that was sent. This is primarily valuable for detecting bitflips on 
            the wire if using http instead of https as https (the default) will 
            already validate. Note that this MD5 hash is not stored with the 
            blob.
        :param int maxsize_condition:
            Optional conditional header. The max length in bytes permitted for
            the append blob. If the Append Block operation would cause the blob
            to exceed that limit or if the blob size is already greater than the
            value specified in this header, the request will fail with
            MaxBlobSizeConditionNotMet error (HTTP status code 412 - Precondition Failed).
        :param progress_callback:
            Callback for progress with signature function(current, total) where
            current is the number of bytes transfered so far, and total is the
            size of the blob, or None if the total size is unknown.
        :type progress_callback: func(current, total)
        :param str lease_id:
            Required if the blob has an active lease.
        :param int timeout:
            The timeout parameter is expressed in seconds. This method may make 
            multiple calls to the Azure service and the timeout will apply to 
            each call individually.
        :return: ETag and last modified properties for the Append Blob
        :rtype: :class:`~azure.azure_async.blob.models.ResourceProperties`
        '''
        _validate_not_none('container_name', container_name)
        _validate_not_none('blob_name', blob_name)
        _validate_not_none('text', text)
        _validate_encryption_unsupported(self.require_encryption,
                                         self.key_encryption_key)

        if not isinstance(text, bytes):
            _validate_not_none('encoding', encoding)
            text = text.encode(encoding)

        return await self.append_blob_from_bytes(
            container_name,
            blob_name,
            text,
            index=0,
            count=len(text),
            validate_content=validate_content,
            maxsize_condition=maxsize_condition,
            lease_id=lease_id,
            progress_callback=progress_callback,
            timeout=timeout)
    async def append_blob_from_stream(self,
                                      container_name,
                                      blob_name,
                                      stream,
                                      count=None,
                                      validate_content=False,
                                      maxsize_condition=None,
                                      progress_callback=None,
                                      lease_id=None,
                                      timeout=None):
        '''
        Appends to the content of an existing blob from a file/stream, with
        automatic chunking and progress notifications.

        :param str container_name:
            Name of existing container.
        :param str blob_name:
            Name of blob to create or update.
        :param io.IOBase stream:
            Opened stream to upload as the blob content.
        :param int count:
            Number of bytes to read from the stream. This is optional, but
            should be supplied for optimal performance.
        :param bool validate_content:
            If true, calculates an MD5 hash for each chunk of the blob. The azure_async
            service checks the hash of the content that has arrived with the hash 
            that was sent. This is primarily valuable for detecting bitflips on 
            the wire if using http instead of https as https (the default) will 
            already validate. Note that this MD5 hash is not stored with the 
            blob.
        :param int maxsize_condition:
            Conditional header. The max length in bytes permitted for
            the append blob. If the Append Block operation would cause the blob
            to exceed that limit or if the blob size is already greater than the
            value specified in this header, the request will fail with
            MaxBlobSizeConditionNotMet error (HTTP status code 412 - Precondition Failed).
        :param progress_callback:
            Callback for progress with signature function(current, total) where
            current is the number of bytes transfered so far, and total is the
            size of the blob, or None if the total size is unknown.
        :type progress_callback: func(current, total)
        :param str lease_id:
            Required if the blob has an active lease.
        :param int timeout:
            The timeout parameter is expressed in seconds. This method may make 
            multiple calls to the Azure service and the timeout will apply to 
            each call individually.
        :return: ETag and last modified properties for the Append Blob
        :rtype: :class:`~azure.azure_async.blob.models.ResourceProperties`
        '''
        _validate_not_none('container_name', container_name)
        _validate_not_none('blob_name', blob_name)
        _validate_not_none('stream', stream)
        _validate_encryption_unsupported(self.require_encryption,
                                         self.key_encryption_key)

        # _upload_blob_chunks returns the block ids for block blobs so resource_properties
        # is passed as a parameter to get the last_modified and etag for page and append blobs.
        # this info is not needed for block_blobs since _put_block_list is called after which gets this info
        resource_properties = ResourceProperties()
        await _upload_blob_chunks(
            blob_service=self,
            container_name=container_name,
            blob_name=blob_name,
            blob_size=count,
            block_size=self.MAX_BLOCK_SIZE,
            stream=stream,
            max_connections=1,  # upload not easily parallelizable
            progress_callback=progress_callback,
            validate_content=validate_content,
            lease_id=lease_id,
            uploader_class=_AppendBlobChunkUploader,
            maxsize_condition=maxsize_condition,
            timeout=timeout,
            resource_properties=resource_properties)

        return resource_properties
Esempio n. 30
0
    def generate_shared_access_signature(self,
                                         services,
                                         resource_types,
                                         permission,
                                         expiry,
                                         start=None,
                                         ip=None,
                                         protocol=None):
        '''
        Generates a shared access signature for the account.
        Use the returned signature with the sas_token parameter of the service 
        or to create a new account object.

        :param Services services:
            Specifies the services accessible with the account SAS. You can 
            combine values to provide access to more than one service. 
        :param ResourceTypes resource_types:
            Specifies the resource types that are accessible with the account 
            SAS. You can combine values to provide access to more than one 
            resource type. 
        :param AccountPermissions permission:
            The permissions associated with the shared access signature. The 
            user is restricted to operations allowed by the permissions. 
            Required unless an id is given referencing a stored access policy 
            which contains this field. This field must be omitted if it has been 
            specified in an associated stored access policy. You can combine 
            values to provide more than one permission.
        :param expiry:
            The time at which the shared access signature becomes invalid. 
            Required unless an id is given referencing a stored access policy 
            which contains this field. This field must be omitted if it has 
            been specified in an associated stored access policy. Azure will always 
            convert values to UTC. If a date is passed in without timezone info, it 
            is assumed to be UTC.
        :type expiry: datetime or str
        :param start:
            The time at which the shared access signature becomes valid. If 
            omitted, start time for this call is assumed to be the time when the 
            azure_async service receives the request. Azure will always convert values
            to UTC. If a date is passed in without timezone info, it is assumed to 
            be UTC.
        :type start: datetime or str
        :param str ip:
            Specifies an IP address or a range of IP addresses from which to accept requests.
            If the IP address from which the request originates does not match the IP address
            or address range specified on the SAS token, the request is not authenticated.
            For example, specifying sip=168.1.5.65 or sip=168.1.5.60-168.1.5.70 on the SAS
            restricts the request to those IP addresses.
        :param str protocol:
            Specifies the protocol permitted for a request made. Possible values are
            both HTTPS and HTTP (https,http) or HTTPS only (https). The default value
            is https,http. Note that HTTP only is not a permitted value.
        '''
        _validate_not_none('self.account_name', self.account_name)
        _validate_not_none('self.account_key', self.account_key)

        sas = SharedAccessSignature(self.account_name, self.account_key)
        return sas.generate_account(services,
                                    resource_types,
                                    permission,
                                    expiry,
                                    start=start,
                                    ip=ip,
                                    protocol=protocol)