예제 #1
0
def iot_digitaltwin_property_update(cmd,
                                    interface_payload,
                                    device_id,
                                    hub_name=None,
                                    resource_group_name=None,
                                    login=None):
    if exists(interface_payload):
        interface_payload = str(read_file_content(interface_payload))

    target_json = None
    try:
        target_json = shell_safe_json_parse(interface_payload)
    except ValueError:
        pass

    if target_json:
        interface_payload = target_json

    target = get_iot_hub_connection_string(cmd,
                                           hub_name,
                                           resource_group_name,
                                           login=login)
    service_sdk, errors = _bind_sdk(target, SdkType.service_sdk)
    try:
        result = service_sdk.update_interfaces(device_id,
                                               interfaces=interface_payload)
        return result
    except errors.CloudError as e:
        raise CLIError(unpack_msrest_error(e))
예제 #2
0
def iot_digitaltwin_invoke_command(cmd, interface, device_id, command_name, command_payload=None,
                                   timeout=10, hub_name=None, resource_group_name=None, login=None):
    device_interfaces = _iot_digitaltwin_interface_list(cmd, device_id, hub_name, resource_group_name, login)
    interface_list = _get_device_default_interface_dict(device_interfaces)

    target_interface = next((item for item in interface_list if item['name'] == interface), None)

    if not target_interface:
        raise CLIError('Target interface is not implemented by the device!')

    if command_payload:
        if exists(command_payload):
            command_payload = str(read_file_content(command_payload))

        target_json = None
        try:
            target_json = shell_safe_json_parse(command_payload)
        except ValueError:
            pass

        if target_json or isinstance(target_json, bool):
            command_payload = target_json

    target = get_iot_hub_connection_string(cmd, hub_name, resource_group_name, login=login)
    service_sdk, errors = _bind_sdk(target, SdkType.service_sdk)
    try:
        result = service_sdk.invoke_interface_command(device_id,
                                                      interface,
                                                      command_name,
                                                      command_payload,
                                                      connect_timeout_in_seconds=timeout,
                                                      response_timeout_in_seconds=timeout)
        return result
    except errors.CloudError as e:
        raise CLIError(unpack_msrest_error(e))
예제 #3
0
def _device_interface_elements(cmd, device_id, interface, target_type,
                               hub_name, resource_group_name, login):
    discovery = IotHubDiscovery(cmd)
    target = discovery.get_target(hub_name=hub_name,
                                  resource_group_name=resource_group_name,
                                  login=login)
    service_sdk, errors = _bind_sdk(target, SdkType.service_sdk)
    interface_elements = []
    try:
        payload = {"id": {}}
        payload["id"] = interface
        target_payload = shell_safe_json_parse(str(payload))
        interface_def = service_sdk.invoke_interface_command(
            device_id, INTERFACE_MODELDEFINITION, INTERFACE_COMMANDNAME,
            target_payload)
        if interface_def and interface_def.get("contents"):
            interface_contents = interface_def.get("contents")
            for content in interface_contents:
                if isinstance(content.get("@type"),
                              list) and target_type in content.get("@type"):
                    interface_elements.append(content)
                elif content.get("@type") == target_type:
                    interface_elements.append(content)
        return interface_elements
    except errors.CloudError as e:
        raise CLIError(unpack_msrest_error(e))
    except Exception:
        # returning an empty collection to continue
        return []
예제 #4
0
def iot_dps_registration_delete(client, dps_name, resource_group_name, registration_id):
    target = get_iot_dps_connection_string(client, dps_name, resource_group_name)
    try:
        m_sdk, errors = _bind_sdk(target, SdkType.dps_sdk)
        return m_sdk.registration_status.delete_registration_state(registration_id)
    except errors.ErrorDetailsException as e:
        raise CLIError(e)
예제 #5
0
def iot_dps_device_enrollment_get(client, enrollment_id, dps_name, resource_group_name):
    target = get_iot_dps_connection_string(client, dps_name, resource_group_name)
    try:
        m_sdk, errors = _bind_sdk(target, SdkType.dps_sdk)
        return m_sdk.device_enrollment.get(enrollment_id)
    except errors.ErrorDetailsException as e:
        raise CLIError(e)
def device_twin_show(cmd,
                     device_id,
                     app_id,
                     central_dns_suffix="azureiotcentral.com"):
    from azext_iot.common._azure import get_iot_central_tokens

    tokens = get_iot_central_tokens(cmd, app_id, central_dns_suffix)
    exception = None

    # The device could be in any hub associated with the given app.
    # We must search through each IoT Hub until device is found.
    for token_group in tokens.values():
        sas_token = token_group["iothubTenantSasToken"]["sasToken"]
        endpoint = find_between(sas_token, "SharedAccessSignature sr=",
                                "&sig=")
        target = {"entity": endpoint}
        auth = BasicSasTokenAuthentication(sas_token=sas_token)
        service_sdk, errors = _bind_sdk(target, SdkType.service_sdk, auth=auth)
        try:
            return service_sdk.get_twin(device_id)
        except errors.CloudError as e:
            if exception is None:
                exception = CLIError(unpack_msrest_error(e))

    raise exception
예제 #7
0
def _device_interface_elements(cmd, device_id, interface, target_type,
                               hub_name, resource_group_name, login):
    target = get_iot_hub_connection_string(cmd,
                                           hub_name,
                                           resource_group_name,
                                           login=login)
    service_sdk, errors = _bind_sdk(target, SdkType.service_sdk)
    interface_elements = []
    try:
        payload = {'id': {}}
        payload['id'] = interface
        target_payload = shell_safe_json_parse(str(payload))
        interface_def = service_sdk.invoke_interface_command(
            device_id, INTERFACE_MODELDEFINITION, INTERFACE_COMMANDNAME,
            target_payload)
        if interface_def and interface_def.get('contents'):
            interface_contents = interface_def.get('contents')
            for content in interface_contents:
                if isinstance(content.get('@type'),
                              list) and target_type in content.get('@type'):
                    interface_elements.append(content)
                elif content.get('@type') == target_type:
                    interface_elements.append(content)
        return interface_elements
    except errors.CloudError as e:
        raise CLIError(unpack_msrest_error(e))
    except Exception:  # pylint: disable=broad-except
        # returning an empty collection to continue
        return []
예제 #8
0
def _iot_digitaltwin_interface_list(cmd, device_id, hub_name=None, resource_group_name=None, login=None):
    target = get_iot_hub_connection_string(cmd, hub_name, resource_group_name, login=login)
    service_sdk, errors = _bind_sdk(target, SdkType.service_sdk)
    try:
        device_interfaces = service_sdk.get_interfaces(device_id)
        return device_interfaces
    except errors.CloudError as e:
        raise CLIError(unpack_msrest_error(e))
예제 #9
0
def iot_dps_device_enrollment_group_create(client,
                                           enrollment_id,
                                           dps_name,
                                           resource_group_name,
                                           certificate_path=None,
                                           secondary_certificate_path=None,
                                           root_ca_name=None,
                                           secondary_root_ca_name=None,
                                           primary_key=None,
                                           secondary_key=None,
                                           iot_hub_host_name=None,
                                           initial_twin_tags=None,
                                           initial_twin_properties=None,
                                           provisioning_status=None,
                                           reprovision_policy=None,
                                           allocation_policy=None,
                                           iot_hubs=None):
    target = get_iot_dps_connection_string(client, dps_name,
                                           resource_group_name)
    try:
        m_sdk, errors = _bind_sdk(target, SdkType.dps_sdk)
        if not certificate_path and not secondary_certificate_path:
            if not root_ca_name and not secondary_root_ca_name:
                attestation = AttestationMechanism(
                    AttestationType.symmetricKey.value, None, None,
                    SymmetricKeyAttestation(primary_key, secondary_key))
        if certificate_path or secondary_certificate_path:
            if root_ca_name or secondary_root_ca_name:
                raise CLIError(
                    'Please provide either certificate path or certficate name'
                )
            attestation = _get_attestation_with_x509_signing_cert(
                certificate_path, secondary_certificate_path)
        if root_ca_name or secondary_root_ca_name:
            if certificate_path or secondary_certificate_path:
                raise CLIError(
                    'Please provide either certificate path or certficate name'
                )
            attestation = _get_attestation_with_x509_ca_cert(
                root_ca_name, secondary_root_ca_name)
        reprovision = _get_reprovision_policy(reprovision_policy)
        initial_twin = _get_initial_twin(initial_twin_tags,
                                         initial_twin_properties)
        iot_hub_list = iot_hubs.split() if iot_hubs else iot_hubs
        _validate_allocation_policy_for_enrollment(allocation_policy,
                                                   iot_hub_host_name,
                                                   iot_hub_list)
        if iot_hub_host_name and allocation_policy is None:
            allocation_policy = AllocationType.static.value
            iot_hub_list = iot_hub_host_name.split()
        group_enrollment = EnrollmentGroup(enrollment_id, attestation, None,
                                           initial_twin, None,
                                           provisioning_status, reprovision,
                                           allocation_policy, iot_hub_list)
        return m_sdk.device_enrollment_group.create_or_update(
            enrollment_id, group_enrollment)
    except errors.ProvisioningServiceErrorDetailsException as e:
        raise CLIError(e)
예제 #10
0
def iot_dps_registration_list(client, dps_name, resource_group_name,
                              enrollment_id):
    target = get_iot_dps_connection_string(client, dps_name,
                                           resource_group_name)
    try:
        m_sdk, errors = _bind_sdk(target, SdkType.dps_sdk)
        return m_sdk.registration_state.query_registration_state(enrollment_id)
    except errors.ProvisioningServiceErrorDetailsException as e:
        raise CLIError(e)
예제 #11
0
def iot_dps_device_enrollment_create(client,
                                     enrollment_id,
                                     attestation_type,
                                     dps_name,
                                     resource_group_name,
                                     endorsement_key=None,
                                     certificate_path=None,
                                     secondary_certificate_path=None,
                                     primary_key=None,
                                     secondary_key=None,
                                     device_id=None,
                                     iot_hub_host_name=None,
                                     initial_twin_tags=None,
                                     initial_twin_properties=None,
                                     provisioning_status=None,
                                     reprovision_policy=None,
                                     allocation_policy=None,
                                     iot_hubs=None,
                                     edge_enabled=False):
    target = get_iot_dps_connection_string(client, dps_name,
                                           resource_group_name)
    try:
        m_sdk, errors = _bind_sdk(target, SdkType.dps_sdk)
        if attestation_type == AttestationType.tpm.value:
            if not endorsement_key:
                raise CLIError('Endorsement key is requried')
            attestation = AttestationMechanism(AttestationType.tpm.value,
                                               TpmAttestation(endorsement_key))
        if attestation_type == AttestationType.x509.value:
            attestation = _get_attestation_with_x509_client_cert(
                certificate_path, secondary_certificate_path)
        if attestation_type == AttestationType.symmetricKey.value:
            attestation = AttestationMechanism(
                AttestationType.symmetricKey.value, None, None,
                SymmetricKeyAttestation(primary_key, secondary_key))
        reprovision = _get_reprovision_policy(reprovision_policy)
        initial_twin = _get_initial_twin(initial_twin_tags,
                                         initial_twin_properties)
        iot_hub_list = iot_hubs.split() if iot_hubs else iot_hubs
        _validate_allocation_policy_for_enrollment(allocation_policy,
                                                   iot_hub_host_name,
                                                   iot_hub_list)
        if iot_hub_host_name and allocation_policy is None:
            allocation_policy = AllocationType.static.value
            iot_hub_list = iot_hub_host_name.split()

        capabilities = DeviceCapabilities(iot_edge=edge_enabled)
        enrollment = IndividualEnrollment(enrollment_id, attestation,
                                          capabilities, device_id, None,
                                          initial_twin, None,
                                          provisioning_status, reprovision,
                                          allocation_policy, iot_hub_list)
        return m_sdk.device_enrollment.create_or_update(
            enrollment_id, enrollment)
    except errors.ProvisioningServiceErrorDetailsException as e:
        raise CLIError(e)
예제 #12
0
def iot_central_device_show(cmd, device_id, app_id):
    sasToken = get_iot_hub_token_from_central_app_id(cmd, app_id)
    endpoint = find_between(sasToken, 'SharedAccessSignature sr=', '&sig=')
    target = {'entity': endpoint}
    auth = BasicSasTokenAuthentication(sas_token=sasToken)
    service_sdk, errors = _bind_sdk(target, SdkType.service_sdk, auth=auth)
    try:
        return service_sdk.get_twin(device_id)
    except errors.CloudError as e:
        raise CLIError(unpack_msrest_error(e))
예제 #13
0
def iot_dps_device_enrollment_list(client, dps_name, resource_group_name, top=None):
    from azext_iot.dps_sdk.models.query_specification import QuerySpecification
    target = get_iot_dps_connection_string(client, dps_name, resource_group_name)
    try:
        m_sdk, errors = _bind_sdk(target, SdkType.dps_sdk)

        query_command = "SELECT *"
        query = QuerySpecification(query_command)
        return _execute_query(query, m_sdk.device_enrollment.query, top)
    except errors.ErrorDetailsException as e:
        raise CLIError(e)
예제 #14
0
def _iot_digitaltwin_interface_list(cmd,
                                    device_id,
                                    hub_name=None,
                                    resource_group_name=None,
                                    login=None):
    discovery = IotHubDiscovery(cmd)
    target = discovery.get_target(hub_name=hub_name,
                                  resource_group_name=resource_group_name,
                                  login=login)
    service_sdk, errors = _bind_sdk(target, SdkType.service_sdk)
    try:
        device_interfaces = service_sdk.get_interfaces(device_id)
        return device_interfaces
    except errors.CloudError as e:
        raise CLIError(unpack_msrest_error(e))
예제 #15
0
def _iot_pnp_model_delete(cmd, endpoint, repository, model_id, login):
    target = get_iot_pnp_connection_string(cmd,
                                           endpoint,
                                           repository,
                                           login=login)

    pnp_sdk, errors = _bind_sdk(target, SdkType.pnp_sdk)
    try:
        headers = get_sas_token(target)
        return pnp_sdk.delete_model(model_id,
                                    repository_id=target.get(
                                        'repository_id', None),
                                    api_version=PNP_API_VERSION,
                                    custom_headers=headers)
    except errors.HttpOperationError as e:
        raise CLIError(unpack_pnp_http_error(e))
예제 #16
0
def iot_dps_device_enrollment_group_create(client,
                                           enrollment_id,
                                           dps_name,
                                           resource_group_name,
                                           certificate_path=None,
                                           secondary_certificate_path=None,
                                           root_ca_name=None,
                                           secondary_root_ca_name=None,
                                           iot_hub_host_name=None,
                                           initial_twin_tags=None,
                                           initial_twin_properties=None,
                                           provisioning_status=None):
    target = get_iot_dps_connection_string(client, dps_name,
                                           resource_group_name)
    try:
        m_sdk, errors = _bind_sdk(target, SdkType.dps_sdk)

        if not certificate_path and not secondary_certificate_path:
            if not root_ca_name and not secondary_root_ca_name:
                raise CLIError('Please provide at least one certificate')

        if certificate_path or secondary_certificate_path:
            if root_ca_name or secondary_root_ca_name:
                raise CLIError(
                    'Please provide either certificate path or certficate name'
                )
            attestation = _get_attestation_with_x509_signing_cert(
                certificate_path, secondary_certificate_path)

        if root_ca_name or secondary_root_ca_name:
            if certificate_path or secondary_certificate_path:
                raise CLIError(
                    'Please provide either certificate path or certficate name'
                )
            attestation = _get_attestation_with_x509_ca_cert(
                root_ca_name, secondary_root_ca_name)

        initial_twin = _get_initial_twin(initial_twin_tags,
                                         initial_twin_properties)
        group_enrollment = EnrollmentGroup(enrollment_id, attestation,
                                           iot_hub_host_name, initial_twin,
                                           None, provisioning_status)

        return m_sdk.device_enrollment_group.create_or_update(
            enrollment_id, group_enrollment)
    except errors.ErrorDetailsException as e:
        raise CLIError(e)
예제 #17
0
def _iot_pnp_model_create_or_update(cmd, endpoint, repository, model_def,
                                    pnpModelType, is_update, login):

    target = get_iot_pnp_connection_string(cmd,
                                           endpoint,
                                           repository,
                                           login=login)
    pnp_sdk, errors = _bind_sdk(target, SdkType.pnp_sdk)
    etag = None
    model_def = _validate_model_definition(model_def)
    model_id = model_def.get('@id')
    if not model_id:
        raise CLIError(
            'PnP Model definition requires @id! Please include @id and try again.'
        )

    if is_update:
        model_list = _iot_pnp_model_list(cmd,
                                         endpoint,
                                         repository,
                                         model_id,
                                         pnpModelType,
                                         -1,
                                         login=login)
        if model_list and model_list[0].urn_id == model_id:
            etag = model_list[0].etag
        else:
            raise CLIError(
                'No PnP Model definition found for @id "{}"'.format(model_id))

    contents = json.loads(
        json.dumps(model_def, separators=(',', ':'), indent=2))
    try:
        headers = get_sas_token(target)
        return pnp_sdk.create_or_update_model(model_id,
                                              api_version=PNP_API_VERSION,
                                              content=contents,
                                              repository_id=target.get(
                                                  'repository_id', None),
                                              if_match=etag,
                                              custom_headers=headers)
    except errors.HttpOperationError as e:
        raise CLIError(unpack_pnp_http_error(e))
예제 #18
0
def _iot_pnp_model_publish(cmd, endpoint, repository, model_id, model_def,
                           etag, login):

    target = get_iot_pnp_connection_string(cmd,
                                           endpoint,
                                           repository,
                                           login=login)
    pnp_sdk, errors = _bind_sdk(target, SdkType.pnp_sdk)

    contents = json.loads(
        json.dumps(model_def, separators=(',', ':'), indent=2))
    try:
        headers = get_sas_token(target)
        return pnp_sdk.create_or_update_model(model_id,
                                              api_version=PNP_API_VERSION,
                                              content=contents,
                                              if_match=etag,
                                              custom_headers=headers)
    except errors.HttpOperationError as e:
        raise CLIError(unpack_pnp_http_error(e))
예제 #19
0
def iot_dps_device_enrollment_create(client,
                                     enrollment_id,
                                     attestation_type,
                                     dps_name,
                                     resource_group_name,
                                     endorsement_key=None,
                                     certificate_path=None,
                                     secondary_certificate_path=None,
                                     device_id=None,
                                     iot_hub_host_name=None,
                                     initial_twin_tags=None,
                                     initial_twin_properties=None,
                                     provisioning_status=None):
    target = get_iot_dps_connection_string(client, dps_name, resource_group_name)
    try:
        m_sdk, errors = _bind_sdk(target, SdkType.dps_sdk)

        if attestation_type == AttestationType.tpm.value:
            if not endorsement_key:
                raise CLIError('Endorsement key is requried')
            tpm = TpmAttestation(endorsement_key)
            attestation = AttestationMechanism(AttestationType.tpm.value, tpm)
        if attestation_type == AttestationType.x509.value:
            attestation = _get_attestation_with_x509_client_cert(certificate_path, secondary_certificate_path)

        initial_twin = _get_initial_twin(initial_twin_tags, initial_twin_properties)
        enrollment = IndividualEnrollment(enrollment_id,
                                          attestation,
                                          device_id,
                                          None,
                                          iot_hub_host_name,
                                          initial_twin,
                                          None,
                                          provisioning_status)

        return m_sdk.device_enrollment.create_or_update(enrollment_id, enrollment)
    except errors.ErrorDetailsException as e:
        raise CLIError(e)
예제 #20
0
def _iot_pnp_model_show(cmd, endpoint, repository, model_id, expand,
                        pnpModelType, login):
    target = get_iot_pnp_connection_string(cmd,
                                           endpoint,
                                           repository,
                                           login=login)
    pnp_sdk, errors = _bind_sdk(target, SdkType.pnp_sdk)
    try:
        headers = get_sas_token(target)
        result = pnp_sdk.get_model(model_id,
                                   api_version=PNP_API_VERSION,
                                   repository_id=target.get(
                                       'repository_id', None),
                                   custom_headers=headers,
                                   expand=expand)

        if not result or result["@type"].lower() != pnpModelType.value.lower():
            raise CLIError(
                'PnP Model definition for "{}", not found.'.format(model_id))

        return result
    except errors.HttpOperationError as e:
        raise CLIError(unpack_pnp_http_error(e))
예제 #21
0
def _iot_pnp_model_list(cmd, endpoint, repository, search_string, pnpModelType,
                        top, login):
    target = get_iot_pnp_connection_string(cmd,
                                           endpoint,
                                           repository,
                                           login=login)

    pnp_sdk, errors = _bind_sdk(target, SdkType.pnp_sdk)
    try:
        headers = get_sas_token(target)
        search_options = SearchOptions(search_keyword=search_string,
                                       model_filter_type=pnpModelType.value)
        if top > 0:
            search_options.page_size = top

        result = pnp_sdk.search(search_options,
                                api_version=PNP_API_VERSION,
                                repository_id=target.get(
                                    'repository_id', None),
                                custom_headers=headers)
        return result.results
    except errors.HttpOperationError as e:
        raise CLIError(unpack_pnp_http_error(e))
예제 #22
0
def iot_dps_device_enrollment_update(client,
                                     enrollment_id,
                                     dps_name,
                                     resource_group_name,
                                     etag=None,
                                     endorsement_key=None,
                                     certificate_path=None,
                                     secondary_certificate_path=None,
                                     remove_certificate=None,
                                     remove_secondary_certificate=None,
                                     device_id=None,
                                     iot_hub_host_name=None,
                                     initial_twin_tags=None,
                                     initial_twin_properties=None,
                                     provisioning_status=None):
    target = get_iot_dps_connection_string(client, dps_name, resource_group_name)
    try:
        m_sdk, errors = _bind_sdk(target, SdkType.dps_sdk)

        enrollment_record = m_sdk.device_enrollment.get(enrollment_id)

        # Verify etag
        if etag and 'etag' in enrollment_record and etag != enrollment_record['etag'].replace('"', ''):
            raise LookupError("enrollment etag doesn't match.")
        if not etag:
            etag = enrollment_record['etag'].replace('"', '')

        # Verify and update attestation information
        attestation_type = enrollment_record['attestation']['type']
        if attestation_type == AttestationType.tpm.value:
            if certificate_path or secondary_certificate_path:
                raise CLIError('Cannot update certificate while enrollment is using tpm attestation mechanism')
            if remove_certificate or remove_secondary_certificate:
                raise CLIError('Cannot remove certificate while enrollment is using tpm attestation mechanism')
            if endorsement_key:
                enrollment_record['attestation']['tpm']['endorsement_key'] = endorsement_key
        else:
            if endorsement_key:
                raise CLIError('Cannot update endorsement key while enrollment is using x509 attestation mechanism')
            enrollment_record['attestation'] = _get_updated_attestation_with_x509_client_cert(enrollment_record['attestation'],
                                                                                              certificate_path,
                                                                                              secondary_certificate_path,
                                                                                              remove_certificate,
                                                                                              remove_secondary_certificate)

        # Update enrollment information
        if iot_hub_host_name:
            enrollment_record['iotHubHostName'] = iot_hub_host_name
        if device_id:
            enrollment_record['deviceId'] = device_id
        if provisioning_status:
            enrollment_record['provisioningStatus'] = provisioning_status
        enrollment_record['registrationState'] = None

        enrollment_record['initialTwin'] = _get_updated_inital_twin(enrollment_record,
                                                                    initial_twin_tags,
                                                                    initial_twin_properties)

        return m_sdk.device_enrollment.create_or_update(enrollment_id, enrollment_record, etag)
    except errors.ErrorDetailsException as e:
        raise CLIError(e)
예제 #23
0
def iot_dps_device_enrollment_group_update(client,
                                           enrollment_id,
                                           dps_name,
                                           resource_group_name,
                                           etag=None,
                                           certificate_path=None,
                                           secondary_certificate_path=None,
                                           root_ca_name=None,
                                           secondary_root_ca_name=None,
                                           remove_certificate=None,
                                           remove_secondary_certificate=None,
                                           iot_hub_host_name=None,
                                           initial_twin_tags=None,
                                           initial_twin_properties=None,
                                           provisioning_status=None):
    target = get_iot_dps_connection_string(client, dps_name, resource_group_name)
    try:
        m_sdk, errors = _bind_sdk(target, SdkType.dps_sdk)

        enrollment_record = m_sdk.device_enrollment_group.get(enrollment_id)

        # Verify etag
        if etag and 'etag' in enrollment_record and etag != enrollment_record['etag'].replace('"', ''):
            raise LookupError("enrollment etag doesn't match.")
        if not etag:
            etag = enrollment_record['etag'].replace('"', '')

        # Update enrollment information
        if not certificate_path and not secondary_certificate_path:
            if not root_ca_name and not secondary_root_ca_name:
                # Check if certificate can be safely removed while no new certificate has been provided
                if remove_certificate and remove_secondary_certificate:
                    raise CLIError('Please provide at least one certificate')

                if not _can_remove_primary_certificate(remove_certificate, enrollment_record['attestation']):
                    raise CLIError('Please provide at least one certificate while removing the only primary certificate')

                if not _can_remove_secondary_certificate(remove_secondary_certificate, enrollment_record['attestation']):
                    raise CLIError('Please provide at least one certificate while removing the only secondary certificate')

        if certificate_path or secondary_certificate_path:
            if root_ca_name or secondary_root_ca_name:
                raise CLIError('Please provide either certificate path or certficate name')
            enrollment_record['attestation'] = _get_updated_attestation_with_x509_signing_cert(enrollment_record['attestation'],
                                                                                               certificate_path,
                                                                                               secondary_certificate_path,
                                                                                               remove_certificate,
                                                                                               remove_secondary_certificate)

        if root_ca_name or secondary_root_ca_name:
            if certificate_path or secondary_certificate_path:
                raise CLIError('Please provide either certificate path or certficate name')
            enrollment_record['attestation'] = _get_updated_attestation_with_x509_ca_cert(enrollment_record['attestation'],
                                                                                          root_ca_name,
                                                                                          secondary_root_ca_name,
                                                                                          remove_certificate,
                                                                                          remove_secondary_certificate)

        if iot_hub_host_name:
            enrollment_record['iotHubHostName'] = iot_hub_host_name
        if provisioning_status:
            enrollment_record['provisioningStatus'] = provisioning_status

        enrollment_record['initialTwin'] = _get_updated_inital_twin(enrollment_record,
                                                                    initial_twin_tags,
                                                                    initial_twin_properties)

        return m_sdk.device_enrollment_group.create_or_update(enrollment_id, enrollment_record, etag)
    except errors.ErrorDetailsException as e:
        raise CLIError(e)
예제 #24
0
def iot_dps_device_enrollment_group_update(client,
                                           enrollment_id,
                                           dps_name,
                                           resource_group_name,
                                           etag=None,
                                           certificate_path=None,
                                           secondary_certificate_path=None,
                                           root_ca_name=None,
                                           secondary_root_ca_name=None,
                                           remove_certificate=None,
                                           remove_secondary_certificate=None,
                                           primary_key=None,
                                           secondary_key=None,
                                           iot_hub_host_name=None,
                                           initial_twin_tags=None,
                                           initial_twin_properties=None,
                                           provisioning_status=None,
                                           reprovision_policy=None,
                                           allocation_policy=None,
                                           iot_hubs=None):
    target = get_iot_dps_connection_string(client, dps_name,
                                           resource_group_name)
    try:
        m_sdk, errors = _bind_sdk(target, SdkType.dps_sdk)
        enrollment_record = m_sdk.device_enrollment_group.get(enrollment_id)
        # Verify etag
        if etag and hasattr(
                enrollment_record,
                'etag') and etag != enrollment_record.etag.replace('"', ''):
            raise LookupError("enrollment etag doesn't match.")
        if not etag:
            etag = enrollment_record.etag.replace('"', '')
        # Update enrollment information
        if enrollment_record.attestation.type == AttestationType.symmetricKey.value:
            enrollment_record.attestation = m_sdk.device_enrollment_group.attestation_mechanism_method(
                enrollment_id)
            if primary_key:
                enrollment_record.attestation.symmetric_key.primary_key = primary_key
            if secondary_key:
                enrollment_record.attestation.symmetric_key.secondary_key = secondary_key

        if enrollment_record.attestation.type == AttestationType.x509.value:
            if not certificate_path and not secondary_certificate_path:
                if not root_ca_name and not secondary_root_ca_name:
                    # Check if certificate can be safely removed while no new certificate has been provided
                    if remove_certificate and remove_secondary_certificate:
                        raise CLIError(
                            'Please provide at least one certificate')

                    if not _can_remove_primary_certificate(
                            remove_certificate, enrollment_record.attestation):
                        raise CLIError(
                            'Please provide at least one certificate while removing the only primary certificate'
                        )

                    if not _can_remove_secondary_certificate(
                            remove_secondary_certificate,
                            enrollment_record.attestation):
                        raise CLIError(
                            'Please provide at least one certificate while removing the only secondary certificate'
                        )

            if certificate_path or secondary_certificate_path:
                if root_ca_name or secondary_root_ca_name:
                    raise CLIError(
                        'Please provide either certificate path or certficate name'
                    )
                enrollment_record.attestation = _get_updated_attestation_with_x509_signing_cert(
                    enrollment_record.attestation, certificate_path,
                    secondary_certificate_path, remove_certificate,
                    remove_secondary_certificate)
            if root_ca_name or secondary_root_ca_name:
                if certificate_path or secondary_certificate_path:
                    raise CLIError(
                        'Please provide either certificate path or certficate name'
                    )
                enrollment_record.attestation = _get_updated_attestation_with_x509_ca_cert(
                    enrollment_record.attestation, root_ca_name,
                    secondary_root_ca_name, remove_certificate,
                    remove_secondary_certificate)
        if iot_hub_host_name:
            enrollment_record.allocation_policy = AllocationType.static.value
            enrollment_record.iot_hubs = iot_hub_host_name.split()
            enrollment_record.iot_hub_host_name = None
        if provisioning_status:
            enrollment_record.provisioning_status = provisioning_status
        if reprovision_policy:
            enrollment_record.reprovision_policy = _get_reprovision_policy(
                reprovision_policy)
        enrollment_record.initial_twin = _get_updated_inital_twin(
            enrollment_record, initial_twin_tags, initial_twin_properties)
        iot_hub_list = iot_hubs.split() if iot_hubs else iot_hubs
        _validate_allocation_policy_for_enrollment(allocation_policy,
                                                   iot_hub_host_name,
                                                   iot_hub_list)
        if allocation_policy:
            enrollment_record.allocation_policy = allocation_policy
            enrollment_record.iot_hubs = iot_hub_list
            enrollment_record.iot_hub_host_name = None
        return m_sdk.device_enrollment_group.create_or_update(
            enrollment_id, enrollment_record, etag)
    except errors.ProvisioningServiceErrorDetailsException as e:
        raise CLIError(e)
예제 #25
0
def iot_dps_device_enrollment_update(client,
                                     enrollment_id,
                                     dps_name,
                                     resource_group_name,
                                     etag=None,
                                     endorsement_key=None,
                                     certificate_path=None,
                                     secondary_certificate_path=None,
                                     remove_certificate=None,
                                     remove_secondary_certificate=None,
                                     primary_key=None,
                                     secondary_key=None,
                                     device_id=None,
                                     iot_hub_host_name=None,
                                     initial_twin_tags=None,
                                     initial_twin_properties=None,
                                     provisioning_status=None,
                                     reprovision_policy=None,
                                     allocation_policy=None,
                                     iot_hubs=None):
    target = get_iot_dps_connection_string(client, dps_name,
                                           resource_group_name)
    try:
        m_sdk, errors = _bind_sdk(target, SdkType.dps_sdk)
        enrollment_record = m_sdk.device_enrollment.get(enrollment_id)
        # Verify etag
        if etag and hasattr(
                enrollment_record,
                'etag') and etag != enrollment_record.etag.replace('"', ''):
            raise LookupError("enrollment etag doesn't match.")
        if not etag:
            etag = enrollment_record.etag.replace('"', '')
        # Verify and update attestation information
        attestation_type = enrollment_record.attestation.type
        _validate_arguments_for_attestation_mechanism(
            attestation_type, endorsement_key, certificate_path,
            secondary_certificate_path, remove_certificate,
            remove_secondary_certificate, primary_key, secondary_key)
        if attestation_type == AttestationType.tpm.value:
            if endorsement_key:
                enrollment_record.attestation.tpm.endorsement_key = endorsement_key
        elif attestation_type == AttestationType.x509.value:
            enrollment_record.attestation = _get_updated_attestation_with_x509_client_cert(
                enrollment_record.attestation, certificate_path,
                secondary_certificate_path, remove_certificate,
                remove_secondary_certificate)
        else:
            enrollment_record.attestation = m_sdk.device_enrollment.attestation_mechanism_method(
                enrollment_id)
            if primary_key:
                enrollment_record.attestation.symmetric_key.primary_key = primary_key
            if secondary_key:
                enrollment_record.attestation.symmetric_key.secondary_key = secondary_key
        # Update enrollment information
        if iot_hub_host_name:
            enrollment_record.allocation_policy = AllocationType.static.value
            enrollment_record.iot_hubs = iot_hub_host_name.split()
            enrollment_record.iot_hub_host_name = None
        if device_id:
            enrollment_record.device_id = device_id
        if provisioning_status:
            enrollment_record.provisioning_status = provisioning_status
        enrollment_record.registrationState = None
        if reprovision_policy:
            enrollment_record.reprovision_policy = _get_reprovision_policy(
                reprovision_policy)
        enrollment_record.initial_twin = _get_updated_inital_twin(
            enrollment_record, initial_twin_tags, initial_twin_properties)
        iot_hub_list = iot_hubs.split() if iot_hubs else iot_hubs
        _validate_allocation_policy_for_enrollment(allocation_policy,
                                                   iot_hub_host_name,
                                                   iot_hub_list)
        if allocation_policy:
            enrollment_record.allocation_policy = allocation_policy
            enrollment_record.iot_hubs = iot_hub_list
            enrollment_record.iot_hub_host_name = None
        return m_sdk.device_enrollment.create_or_update(
            enrollment_id, enrollment_record, etag)
    except errors.ProvisioningServiceErrorDetailsException as e:
        raise CLIError(e)