예제 #1
0
 def inner(options):
     accounts = AccountManagementAPI()
     certs = CertificatesAPI()
     api_key = accounts.list_api_keys(
         filter={
             'key': getenv("MBED_CLOUD_SDK_API_KEY")
         }).next()
     certificates_owned = list(certs.list_certificates())
     dev_cert_info = None
     for certif in certificates_owned:
         if certif.type == "developer" and (
                 certif.owner_id == api_key.owner_id
                 or certif.owner_id == api_key.id):
             dev_cert_info = certs.get_certificate(certif.id)
             LOG.info("Found developer certificate named %s",
                      dev_cert_info.name)
             break
     else:
         LOG.warning(
             "Could not find developer certificate for this account."
             " Generting a new developer certificate.")
         dev_cert_info = CertificatesAPI().add_developer_certificate(
             "mbed-cli-auto {}".format(api_key.name),
             description="cetificate auto-generated by Mbed CLI")
     LOG.info(
         "Writing developer certificate %s into c file "
         "mbed_cloud_dev_credentials.c", dev_cert_info.name)
     with open("mbed_cloud_dev_credentials.c", "w") as fout:
         fout.write(dev_cert_info.header_file)
     return func(options)
예제 #2
0
    def inner(options):
        config = {}
        if getattr(options, 'api_key'):
            config["api_key"] = options.api_key
        if getattr(options, 'server_address'):
            config["host"] = options.server_address

        try:
            accounts = AccountManagementAPI(config)
            certs = CertificatesAPI(config)
        except Exception as e:
            LOG.error('Missing api key. Set it with '
                      '"mbed config -G CLOUD_SDK_API_KEY <api key>"')
            exit(1)

        # Get the currently in-use API key (may come from environment or
        # configuration files, which is handled by the cloud SDK)
        api_key_value = accounts.config.get("api_key")
        api_key = accounts.list_api_keys(filter={"key": api_key_value}).next()
        certificates_owned = list(certs.list_certificates())
        dev_cert_info = None
        for certif in certificates_owned:
            if certif.type == "developer" and (
                    certif.owner_id == api_key.owner_id
                    or certif.owner_id == api_key.id):
                dev_cert_info = certs.get_certificate(certif.id)
                LOG.info("Found developer certificate named %s",
                         dev_cert_info.name)
                break
        else:
            LOG.warning(
                "Could not find developer certificate for this account."
                " Generting a new developer certificate.")
            dev_cert_info = CertificatesAPI().add_developer_certificate(
                "mbed-cli-auto {}".format(api_key.name),
                description="cetificate auto-generated by Mbed CLI")
        if getattr(options, 'no_developer_cert'):
            LOG.info("Skipping download of developer certificate")
        else:
            LOG.info(
                "Writing developer certificate %s into c file "
                "mbed_cloud_dev_credentials.c", dev_cert_info.name)
            with open("mbed_cloud_dev_credentials.c", "w") as fout:
                fout.write(dev_cert_info.header_file)
        return func(options)
예제 #3
0
 def inner(options):
     if getattr(options, 'api_key', None):
         api_key = options.api_key
     else:
         api_key = getenv("MBED_CLOUD_SDK_API_KEY")
     if getattr(options, 'server_address', None):
         host_addr = options.server_address
     else:
         host_addr = getenv("MBED_CLOUD_SDK_HOST",
                            "https://api.us-east-1.mbedcloud.com/")
     config = {
         "api_key": api_key,
         "host": host_addr,
     }
     accounts = AccountManagementAPI(config)
     certs = CertificatesAPI(config)
     api_key = accounts.list_api_keys(filter={'key': api_key}).next()
     certificates_owned = list(certs.list_certificates())
     dev_cert_info = None
     for certif in certificates_owned:
         if certif.type == "developer" and (
                 certif.owner_id == api_key.owner_id
                 or certif.owner_id == api_key.id):
             dev_cert_info = certs.get_certificate(certif.id)
             LOG.info("Found developer certificate named %s",
                      dev_cert_info.name)
             break
     else:
         LOG.warning(
             "Could not find developer certificate for this account."
             " Generting a new developer certificate.")
         dev_cert_info = CertificatesAPI().add_developer_certificate(
             "mbed-cli-auto {}".format(api_key.name),
             description="cetificate auto-generated by Mbed CLI")
     LOG.info(
         "Writing developer certificate %s into c file "
         "mbed_cloud_dev_credentials.c", dev_cert_info.name)
     with open("mbed_cloud_dev_credentials.c", "w") as fout:
         fout.write(dev_cert_info.header_file)
     return func(options)
def _main():
    config = {}

    try:
        config["api_key"] = os.environ['CLOUD_SDK_API_KEY']
    except KeyError as e:
        LOG.error('Missing CLOUD_SDK_API_KEY enviromental key !')
        exit(1)

    accounts = AccountManagementAPI(config)
    certs = CertificatesAPI(config)

    api_key_value = accounts.config.get("api_key")
    api_key = next(accounts.list_api_keys(filter={"key": api_key_value}))

    certificates_owned = list(certs.list_certificates())
    dev_cert_info = None
    for certif in certificates_owned:
        if certif.type == "developer" and (certif.owner_id == api_key.owner_id
                                           or certif.owner_id == api_key.id):
            dev_cert_info = certs.get_certificate(certif.id)
            LOG.info("Found developer certificate named '%s'",
                     dev_cert_info.name)
            break
    else:
        LOG.warning("Could not find developer certificate for this account."
                    " Generating a new developer certificate.")
        dev_cert_info = certs.add_developer_certificate(
            "mbed-cli-auto {}".format(api_key.name),
            description="cetificate auto-generated by pelion-device-simulator")

    LOG.info(
        "Writing developer certificate %s into c file "
        "'mbed_cloud_dev_credentials.c'", dev_cert_info.name)
    with open("mbed_cloud_dev_credentials.c", "w") as fout:
        fout.write(dev_cert_info.header_file)
예제 #5
0
class DevCredentialsAPI:
    """API to manage developer certificate creation.

    Wrap the CertificatesAPI. Creates/gets and parses developer certificates.
    """

    def __init__(self, api_key):
        """Initialise the API."""
        self._cert_api = CertificatesAPI(dict(api_key=api_key))

    @property
    def existing_cert_names(self):
        """List all existing certificate names known to the Pelion account."""
        return [
            self._cert_api.get_certificate(c.id).name
            for c in self._cert_api.list_certificates()
        ]

    def get_dev_credentials(self, name):
        """Get an existing developer certificate from Pelion.

        Return a credentials object.

        :param str name: name of the developer certificate to create.
        """
        for cert in self._cert_api.list_certificates():
            this_cert = self._cert_api.get_certificate(cert.id)
            if this_cert.name == name:
                return _parse_cert_header(
                    this_cert.header_file,
                    "#include <inttypes.h>",
                    "MBED_CLOUD_DEV_",
                )
        raise ValueError(
            "The developer certificate does not exist. "
            "Available certificates: \n{}".format(
                "\n".join(self.existing_cert_names)
            )
        )

    def create_dev_credentials(self, name):
        """Create a new developer certificate and return a credentials object.

        :param str name: name of the developer certificate to create.
        """
        try:
            cert = self._cert_api.add_developer_certificate(name=name)
            return _parse_cert_header(
                cert.header_file, "#include <inttypes.h>", "MBED_CLOUD_DEV_"
            )
        except CloudApiException as err:
            if err.reason != "Conflict":
                raise
            raise ValueError(
                "The developer certificate you are trying to create "
                "already exists in the Pelion Device Management Portal."
            )

    def delete_developer_certificate(self, name):
        """Delete an existing developer certificate from device management."""
        for cert in self._cert_api.list_certificates():
            if cert.name == name:
                self._cert_api.delete_certificate(cert.id)
                return
        raise ValueError(
            "Certificate '{}' was not found in Device Management.".format(name)
        )