def create(self,
               name=None,
               payload_content_type='application/octet-stream',
               algorithm=None,
               bit_length=None,
               mode=None,
               expiration=None):
        """
        Creates a new Order in Barbican

        :param name: A friendly name for the secret
        :param payload_content_type: The format/type of the secret data
        :param algorithm: The algorithm the secret associated with
        :param bit_length: The bit length of the secret
        :param mode: The algorithm mode (e.g. CBC or CTR mode)
        :param expiration: The expiration time of the secret in ISO 8601
            format
        :returns: Order href for the created order
        """
        LOG.debug(_("Creating order"))

        order_dict = {'secret': {}}
        order_dict['secret']['name'] = name
        order_dict['secret'][
            'payload_content_type'] = payload_content_type
        order_dict['secret']['algorithm'] = algorithm
        order_dict['secret']['bit_length'] = bit_length
        order_dict['secret']['mode'] = mode
        order_dict['secret']['expiration'] = expiration
        self._remove_empty_keys(order_dict['secret'])

        LOG.debug(_("Request body: {0}").format(order_dict['secret']))

        resp = self.api.post(self.entity, order_dict)
        return resp['order_ref']
Example #2
0
    def connect(self, token=None):
        """
        Establishes a connection. If token is not None or empty, it will be
        used for this connection, and authentication will not take place.

        :param token: An authentication token
        """

        LOG.debug(_("Establishing connection"))

        self._session = requests.Session()

        # headers = {"Client-Id": self._client_id}
        # self._session.headers.update(headers)
        self._session.verify = True

        if token:
            self.auth_token = token
        else:
            LOG.debug(_("Authenticating token"))
            endpoint, self.auth_token = self.authenticate(
                self._auth_endpoint,
                self._user,
                self._key,
                self._tenant,
                service_type='key-store',
                endpoint=self._endpoint,
                cacert=self._cacert)
            if self.endpoint is None:
                self.endpoint = endpoint
    def connect(self, token=None):
        """
        Establishes a connection. If token is not None the
        token will be used for this connection and auth will
        not happen.
        """

        LOG.debug(_("Establishing connection"))

        self._session = requests.Session()

        #headers = {"Client-Id": self._client_id}
        #self._session.headers.update(headers)
        self._session.verify = True

        if token:
            self.auth_token = token
        else:
            LOG.debug(_("Authenticating token"))
            self._endpoint, self.auth_token = self.authenticate(
                self._auth_endpoint,
                self._user,
                self._key,
                self._tenant,
                endpoint=self._endpoint,
                cacert=self._cacert)
    def create_order(self,
                     mime_type,
                     name=None,
                     algorithm=None,
                     bit_length=None,
                     cypher_type=None):
        """
        Creates and returns an Order object with all of its metadata filled in.

        arguments:
            mime_type - The MIME type of the secret
            name - A friendly name for the secret
            algorithm - The algorithm the secret is used with
            bit_length - The bit length of the secret
            cypher_type - The cypher type (e.g. block cipher mode of operation)
        """
        LOG.debug(_("Creating order of mime_type {0}").format(mime_type))
        href = "{0}/{1}".format(self._tenant, self.ORDERS_PATH)
        LOG.debug("href: {0}".format(href))
        order_dict = {'secret': {}}
        order_dict['secret']['name'] = name
        order_dict['secret']['mime_type'] = mime_type
        order_dict['secret']['algorithm'] = algorithm
        order_dict['secret']['bit_length'] = bit_length
        order_dict['secret']['cypher_type'] = cypher_type
        self._remove_empty_keys(order_dict['secret'])
        LOG.debug(_("Request body: {0}").format(order_dict['secret']))
        hdrs, body = self._perform_http(href=href,
                                        method='POST',
                                        request_body=json.dumps(order_dict))

        LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))

        return self.get_order(body['order_ref'])
    def connect(self, token=None):
        """
        Establishes a connection. If token is not None the
        token will be used for this connection and auth will
        not happen.
        """

        LOG.debug(_("Establishing connection"))

        self._session = requests.Session()

        #headers = {"Client-Id": self._client_id}
        #self._session.headers.update(headers)
        self._session.verify = True

        if token:
            self.auth_token = token
        else:
            LOG.debug(_("Authenticating token"))
            self._endpoint, self.auth_token = self.authenticate(
                self._auth_endpoint,
                self._user,
                self._key,
                self._tenant,
                endpoint=self._endpoint,
                cacert=self._cacert
            )
Example #6
0
    def list_orders_by_href(self, href):
        """
        Returns a tuple containing three items: a list of orders pertaining
        to the offset and limit within href, a reference to the previous set
        of orders, and a reference to the next set of orders. Either of the
        references may be None.

        :param href: The full orders URI
        """
        LOG.debug(_("Listing orders by href"))
        LOG.debug("href: {0}".format(href))
        if href is None:
            return [], None, None

        hdrs, body = self._perform_http(href=href, method='GET')
        LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))

        orders_dict = body['orders']
        orders = [Order(self._conn, o) for o in orders_dict]

        prev_ref = body.get('previous')

        next_ref = body.get('next')

        return orders, prev_ref, next_ref
Example #7
0
    def create_order(self,
                     name=None,
                     payload_content_type='application/octet-stream',
                     algorithm='aes',
                     bit_length=256,
                     cypher_type='cbc',
                     expiration=None):
        """
        Creates and returns an Order object with all of its metadata filled in.

        :param name: A friendly name for the secret
        :param algorithm: The algorithm the secret is used with
        :param bit_length: The bit length of the secret
        :param cypher_type: The cypher type (e.g. block cipher mode)
        :param expiration: The expiration time of the secret in ISO 8601 format
        """
        LOG.debug(_("Creating order"))
        href = "{0}/{1}".format(self._tenant, self.ORDERS_PATH)
        LOG.debug("href: {0}".format(href))
        order_dict = {'secret': {}}
        order_dict['secret']['name'] = name
        order_dict['secret']['payload_content_type'] = payload_content_type
        order_dict['secret']['algorithm'] = algorithm
        order_dict['secret']['bit_length'] = bit_length
        order_dict['secret']['cypher_type'] = cypher_type
        order_dict['secret']['expiration'] = expiration
        self._remove_empty_keys(order_dict['secret'])
        LOG.debug(_("Request body: {0}").format(order_dict['secret']))
        hdrs, body = self._perform_http(href=href,
                                        method='POST',
                                        request_body=json.dumps(order_dict))

        LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))

        return self.get_order(body['order_ref'])
    def create_order(self,
                     mime_type,
                     name=None,
                     algorithm=None,
                     bit_length=None,
                     cypher_type=None):
        """
        Creates and returns an Order object with all of its metadata filled in.

        arguments:
            mime_type - The MIME type of the secret
            name - A friendly name for the secret
            algorithm - The algorithm the secret is used with
            bit_length - The bit length of the secret
            cypher_type - The cypher type (e.g. block cipher mode of operation)
        """
        LOG.debug(_("Creating order of mime_type {0}").format(mime_type))
        href = "{0}/{1}".format(self._tenant, self.ORDERS_PATH)
        LOG.debug("href: {0}".format(href))
        order_dict = {'secret': {}}
        order_dict['secret']['name'] = name
        order_dict['secret']['mime_type'] = mime_type
        order_dict['secret']['algorithm'] = algorithm
        order_dict['secret']['bit_length'] = bit_length
        order_dict['secret']['cypher_type'] = cypher_type
        self._remove_empty_keys(order_dict['secret'])
        LOG.debug(_("Request body: {0}").format(order_dict['secret']))
        hdrs, body = self._perform_http(href=href,
                                        method='POST',
                                        request_body=json.dumps(order_dict))

        LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))

        return self.get_order(body['order_ref'])
    def create(self,
               resource_type=None,
               resource_ref=None,
               resource_action=None,
               impersonation_allowed=False):
        """
        Creates a new Verification in Barbican

        :param resource_type: Type of resource to verify
        :param resource_ref: Reference to resource
        :param resource_action: Action to be performed on or with the resource
        :param impersonation_allowed: True if users/projects interacting
        :                             with resource can be impersonated
        :returns: Verification href for the created verification
        """
        LOG.debug(_("Creating verification"))

        verif_dict = {'resource_type': resource_type,
                      'resource_ref': resource_ref,
                      'resource_action': resource_action,
                      'impersonation_allowed': impersonation_allowed}
        self._remove_empty_keys(verif_dict)

        LOG.debug(_("Request body: {0}").format(verif_dict))

        resp = self.api.post(self.entity, verif_dict)
        return resp['verification_ref']
 def get_raw_secret_by_id(self, secret_id, mime_type):
     """
     Returns the raw secret using the secret's UUID and MIME type
     """
     LOG.debug(_("Getting raw secret - Secret ID: {0}").format(secret_id))
     href = "{0}/{1}/{2}".format(self._tenant, self.SECRETS_PATH, secret_id)
     return self.get_raw_secret(href, mime_type)
Example #11
0
 def deprecated(self, msg, *args, **kwargs):
     stdmsg = _("Deprecated: %s") % msg
     if CONF.fatal_deprecations:
         self.critical(stdmsg, *args, **kwargs)
         raise DeprecatedConfig(msg=stdmsg)
     else:
         self.warn(stdmsg, *args, **kwargs)
    def __init__(self,
                 auth_endpoint,
                 user,
                 key,
                 tenant,
                 token=None,
                 authenticate=None,
                 request=None,
                 **kwargs):
        """
        :param auth_endpoint: The auth URL to authenticate against
        :param user: The user to authenticate as
        :param key: The API key or password to auth with
        """

        LOG.debug(_("Creating Connection object"))

        self._auth_endpoint = auth_endpoint
        self.authenticate = authenticate or auth.authenticate
        self.request = request or requests.request
        self._user = user
        self._key = key
        self._tenant = tenant
        self._endpoint = (kwargs.get('endpoint')
                          or 'https://barbican.api.rackspacecloud.com/v1/')
        self._cacert = kwargs.get('cacert')

        self.connect(token=token)
 def get_secret_by_id(self, secret_id):
     """
     Returns a Secret object using the secret's UUID
     """
     LOG.debug(_("Getting secret - Secret ID: {0}").format(secret_id))
     href = "{0}/{1}/{2}".format(self._tenant, self.SECRETS_PATH, secret_id)
     return self.get_secret(href)
Example #14
0
 def deprecated(self, msg, *args, **kwargs):
     stdmsg = _("Deprecated: %s") % msg
     if CONF.fatal_deprecations:
         self.critical(stdmsg, *args, **kwargs)
         raise DeprecatedConfig(msg=stdmsg)
     else:
         self.warn(stdmsg, *args, **kwargs)
 def get_order(self, href):
     """
     Returns an Order object using the order's full reference
     """
     hdrs, body = self._perform_http(href=href, method='GET')
     LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))
     return Order(self._conn, body)
 def delete_order_by_id(self, order_id):
     """
     Deletes an order using its UUID
     """
     LOG.info(_("Deleting order - Order ID: {0}").format(order_id))
     href = "{0}/{1}/{2}".format(self._tenant, self.ORDERS_PATH, order_id)
     return self.delete_order(href)
 def delete_order_by_id(self, order_id):
     """
     Deletes an order using its UUID
     """
     LOG.info(_("Deleting order - Order ID: {0}").format(order_id))
     href = "{0}/{1}/{2}".format(self._tenant, self.ORDERS_PATH, order_id)
     return self.delete_order(href)
 def get_secret_by_id(self, secret_id):
     """
     Returns a Secret object using the secret's UUID
     """
     LOG.debug(_("Getting secret - Secret ID: {0}").format(secret_id))
     href = "{0}/{1}/{2}".format(self._tenant, self.SECRETS_PATH, secret_id)
     return self.get_secret(href)
 def get_raw_secret_by_id(self, secret_id, mime_type):
     """
     Returns the raw secret using the secret's UUID and MIME type
     """
     LOG.debug(_("Getting raw secret - Secret ID: {0}").format(secret_id))
     href = "{0}/{1}/{2}".format(self._tenant, self.SECRETS_PATH, secret_id)
     return self.get_raw_secret(href, mime_type)
 def delete_secret_by_id(self, secret_id):
     """
     Deletes a secret using its UUID
     """
     href = "{0}/{1}/{2}".format(self._tenant, self.SECRETS_PATH, secret_id)
     LOG.info(_("Deleting secret - Secret ID: {0}").format(secret_id))
     return self.delete_secret(href)
 def delete_secret_by_id(self, secret_id):
     """
     Deletes a secret using its UUID
     """
     href = "{0}/{1}/{2}".format(self._tenant, self.SECRETS_PATH, secret_id)
     LOG.info(_("Deleting secret - Secret ID: {0}").format(secret_id))
     return self.delete_secret(href)
 def get_order_by_id(self, order_id):
     """
     Returns an Order object using the order's UUID
     """
     LOG.debug(_("Getting order - Order ID: {0}").format(order_id))
     href = "{0}/{1}/{2}".format(self._tenant, self.ORDERS_PATH, order_id)
     return self.get_order(href)
 def get_order(self, href):
     """
     Returns an Order object using the order's full reference
     """
     hdrs, body = self._perform_http(href=href, method='GET')
     LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))
     return Order(self._conn, body)
 def get_order_by_id(self, order_id):
     """
     Returns an Order object using the order's UUID
     """
     LOG.debug(_("Getting order - Order ID: {0}").format(order_id))
     href = "{0}/{1}/{2}".format(self._tenant, self.ORDERS_PATH, order_id)
     return self.get_order(href)
Example #25
0
    def delete_order(self, href):
        """
        Deletes an order

        :param href: The full URI of the order
        """
        hdrs, body = self._perform_http(href=href, method='DELETE')
        LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))
Example #26
0
    def get_order(self, href):
        """
        Returns an Order object

        :param href: The full URI of the order
        """
        hdrs, body = self._perform_http(href=href, method='GET')
        LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))
        return Order(self._conn, body)
 def get_raw_secret(self, href, mime_type):
     """
     Returns the raw secret using the secret's UUID and MIME type
     """
     hdrs = {"Accept": mime_type}
     hdrs, body = self._perform_http(href=href, method='GET', headers=hdrs,
                                     parse_json=False)
     LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))
     return body
Example #28
0
    def create_secret(self,
                      name=None,
                      payload=None,
                      payload_content_type=None,
                      payload_content_encoding=None,
                      algorithm=None,
                      bit_length=None,
                      cypher_type=None,
                      expiration=None):
        """
        Creates and returns a Secret object with all of its metadata filled in.

        :param name: A friendly name for the secret
        :param payload: The unencrypted secret
        :param payload_content_type: The format/type of the secret
        :param payload_content_encoding: The encoding of the secret
        :param algorithm: The algorithm the secret is used with
        :param bit_length: The bit length of the secret
        :param cypher_type: The cypher type (e.g. block cipher mode)
        :param expiration: The expiration time of the secret in ISO 8601 format
        """
        LOG.debug(
            _("Creating secret of payload content type {0}").format(
                payload_content_type))
        href = "{0}/{1}".format(self._tenant, self.SECRETS_PATH)
        LOG.debug(_("href: {0}").format(href))
        secret_dict = {}
        secret_dict['name'] = name
        secret_dict['payload'] = payload
        secret_dict['payload_content_type'] = payload_content_type
        secret_dict['payload_content_encoding'] = payload_content_encoding
        secret_dict['algorithm'] = algorithm
        secret_dict['cypher_type'] = cypher_type
        secret_dict['bit_length'] = bit_length
        secret_dict['expiration'] = expiration
        self._remove_empty_keys(secret_dict)
        LOG.debug(_("Request body: {0}").format(secret_dict))
        hdrs, body = self._perform_http(href=href,
                                        method='POST',
                                        request_body=json.dumps(secret_dict))

        LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))

        return self.get_secret(body['secret_ref'])
Example #29
0
    def get_raw_secret_by_id(self, secret_id, payload_content_type):
        """
        Returns the raw secret

        :param secret_id: The UUID of the secret
        :param payload_content_type: The data type of the secret
        """
        LOG.debug(_("Getting raw secret - Secret ID: {0}").format(secret_id))
        href = "{0}/{1}/{2}".format(self._tenant, self.SECRETS_PATH, secret_id)
        return self.get_raw_secret(href, payload_content_type)
    def create_secret(self,
                      mime_type,
                      plain_text=None,
                      name=None,
                      algorithm=None,
                      bit_length=None,
                      cypher_type=None,
                      expiration=None):
        """
        Creates and returns a Secret object with all of its metadata filled in.

        arguments:
            mime_type - The MIME type of the secret
            plain_text - The unencrypted secret
            name - A friendly name for the secret
            algorithm - The algorithm the secret is used with
            bit_length - The bit length of the secret
            cypher_type - The cypher type (e.g. block cipher mode of operation)
            expiration - The expiration time for the secret in ISO 8601 format
        """
        LOG.debug(_("Creating secret of mime_type {0}").format(mime_type))
        href = "{0}/{1}".format(self._tenant, self.SECRETS_PATH)
        LOG.debug(_("href: {0}").format(href))
        secret_dict = {}
        secret_dict['mime_type'] = mime_type
        secret_dict['plain_text'] = plain_text
        secret_dict['name'] = name
        secret_dict['algorithm'] = algorithm
        secret_dict['cypher_type'] = cypher_type
        if bit_length is not None:
            secret_dict['bit_length'] = int(bit_length)
        if expiration is not None:
            secret_dict['expiration'] = parse_isotime(expiration)
        self._remove_empty_keys(secret_dict)
        LOG.debug(_("Request body: {0}").format(secret_dict))
        hdrs, body = self._perform_http(href=href,
                                        method='POST',
                                        request_body=json.dumps(secret_dict))

        LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))

        return self.get_secret(body['secret_ref'])
    def create_secret(self,
                      mime_type,
                      plain_text=None,
                      name=None,
                      algorithm=None,
                      bit_length=None,
                      cypher_type=None,
                      expiration=None):
        """
        Creates and returns a Secret object with all of its metadata filled in.

        arguments:
            mime_type - The MIME type of the secret
            plain_text - The unencrypted secret
            name - A friendly name for the secret
            algorithm - The algorithm the secret is used with
            bit_length - The bit length of the secret
            cypher_type - The cypher type (e.g. block cipher mode of operation)
            expiration - The expiration time for the secret in ISO 8601 format
        """
        LOG.debug(_("Creating secret of mime_type {0}").format(mime_type))
        href = "{0}/{1}".format(self._tenant, self.SECRETS_PATH)
        LOG.debug(_("href: {0}").format(href))
        secret_dict = {}
        secret_dict['mime_type'] = mime_type
        secret_dict['plain_text'] = plain_text
        secret_dict['name'] = name
        secret_dict['algorithm'] = algorithm
        secret_dict['cypher_type'] = cypher_type
        if bit_length is not None:
            secret_dict['bit_length'] = int(bit_length)
        if expiration is not None:
            secret_dict['expiration'] = parse_isotime(expiration)
        self._remove_empty_keys(secret_dict)
        LOG.debug(_("Request body: {0}").format(secret_dict))
        hdrs, body = self._perform_http(href=href,
                                        method='POST',
                                        request_body=json.dumps(secret_dict))

        LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))

        return self.get_secret(body['secret_ref'])
Example #32
0
    def get(self, order_ref):
        """
        Returns an Order object

        :param order_ref: The href for the order
        """
        LOG.debug(_("Getting order - Order href: {0}").format(order_ref))
        if not order_ref:
            raise ValueError('order_ref is required.')
        resp = self.api.get(order_ref)
        return Order(resp)
Example #33
0
class LogConfigError(Exception):

    message = _('Error loading logging config %(log_config)s: %(err_msg)s')

    def __init__(self, log_config, err_msg):
        self.log_config = log_config
        self.err_msg = err_msg

    def __str__(self):
        return self.message % dict(log_config=self.log_config,
                                   err_msg=self.err_msg)
 def get_raw_secret(self, href, mime_type):
     """
     Returns the raw secret using the secret's UUID and MIME type
     """
     hdrs = {"Accept": mime_type}
     hdrs, body = self._perform_http(href=href,
                                     method='GET',
                                     headers=hdrs,
                                     parse_json=False)
     LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))
     return body
    def get(self, verification_ref):
        """
        Returns a verification object

        :param verification_ref: The href for the verification instance
        """
        LOG.debug(_("Getting verification - "
                    "Verification href: {0}").format(verification_ref))
        if not verification_ref:
            raise ValueError('verif_ref is required.')
        resp = self.api.get(verification_ref)
        return Verification(resp)
 def list_orders(self, limit=10, offset=0):
     """
     Returns a tuple containing three items: a list of orders pertaining
     to the given offset and limit, a reference to the previous set of
     orders, and a reference to the next set of orders. Either of the
     references may be None.
     """
     LOG.debug(_("Listing orders - offset: {0}, limit: {1}").format(offset,
                                                                    limit))
     href = "{0}/{1}?limit={2}&offset={3}".format(self._tenant,
                                                  self.ORDERS_PATH,
                                                  limit, offset)
     return self.list_orders_by_href(href)
Example #37
0
    def get_raw_secret(self, href, payload_content_type):
        """
        Returns the raw secret

        :param href: The reference to the secret
        :param payload_content_type: The data type of the secret
        """
        hdrs = {"Accept": payload_content_type}
        hdrs, body = self._perform_http(href=href,
                                        method='GET',
                                        headers=hdrs,
                                        parse_json=False)
        LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))
        return body
Example #38
0
    def __init__(self, session=None, auth_plugin=None, endpoint=None,
                 tenant_id=None, insecure=False):
        """
        Barbican client object used to interact with barbican service.

        :param auth_plugin: Authentication backend plugin
            defaults to None
        :param endpoint: Barbican endpoint url.  Required when not using
            an auth_plugin.  When not provided, the client will try to
            fetch this from the auth service catalog
        :param tenant_id: The tenant ID used for context in barbican.
            Required when not using auth_plugin.  When not provided,
            the client will try to get this from the auth_plugin.
        """
        LOG.debug(_("Creating Client object"))

        self._session = session or requests.Session()
        self.verify = not insecure
        self.auth_plugin = auth_plugin

        if self.auth_plugin is not None:
            try:
                self._barbican_url = self.auth_plugin.barbican_url
            except:
                if endpoint:
                    self._barbican_url = endpoint
                else:
                    raise

            self._tenant_id = self.auth_plugin.tenant_id
            self._session.headers.update(
                {'X-Auth-Token': self.auth_plugin.auth_token}
            )
        else:
            if endpoint is None:
                raise ValueError('Barbican endpoint url must be provided, or '
                                 'must be available from auth_plugin')
            if tenant_id is None:
                raise ValueError('Tenant ID must be provided, or must be'
                                 ' available from the auth_plugin')
            if endpoint.endswith('/'):
                self._barbican_url = endpoint[:-1]
            else:
                self._barbican_url = endpoint
            self._tenant_id = tenant_id

        self.base_url = '{0}/{1}'.format(self._barbican_url, self._tenant_id)
        self.secrets = secrets.SecretManager(self)
        self.orders = orders.OrderManager(self)
        self.verifications = verifications.VerificationManager(self)
 def list_orders(self, limit=10, offset=0):
     """
     Returns a tuple containing three items: a list of orders pertaining
     to the given offset and limit, a reference to the previous set of
     orders, and a reference to the next set of orders. Either of the
     references may be None.
     """
     LOG.debug(
         _("Listing orders - offset: {0}, limit: {1}").format(
             offset, limit))
     href = "{0}/{1}?limit={2}&offset={3}".format(self._tenant,
                                                  self.ORDERS_PATH, limit,
                                                  offset)
     return self.list_orders_by_href(href)
    def list_orders_by_href(self, href):
        """
        Returns a tuple containing three items: a list of orders pertaining
        to the offset and limit within href, a reference to the previous set
        of orders, and a reference to the next set of orders. Either of the
        references may be None.
        """
        LOG.debug(_("Listing orders by href"))
        LOG.debug("href: {0}".format(href))
        if href is None:
            return [], None, None

        hdrs, body = self._perform_http(href=href, method='GET')
        LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))

        orders_dict = body['orders']
        orders = [Order(self._conn, o) for o in orders_dict]

        prev_ref = body.get('previous')

        next_ref = body.get('next')

        return orders, prev_ref, next_ref
    def list_secrets_by_href(self, href):
        """
        Returns a tuple containing three items: a list of secrets pertaining
        to the offset and limit within href, a reference to the previous set
        of secrets, and a reference to the next set of secrets. Either of the
        references may be None.
        """
        LOG.debug(_("Listing secrets by href"))
        LOG.debug("href: {0}".format(href))
        if href is None:
            return [], None, None

        hdrs, body = self._perform_http(href=href, method='GET')
        LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))

        secrets_dict = body['secrets']
        secrets = [Secret(self._conn, s) for s in secrets_dict]

        prev_ref = body.get('previous')

        next_ref = body.get('next')

        return secrets, prev_ref, next_ref
Example #42
0
    def list_secrets(self, limit=10, offset=0):
        """
        Returns a tuple containing three items: a list of secrets pertaining
        to the given offset and limit, a reference to the previous set of
        secrets, and a reference to the next set of secrets. Either of the
        references may be None.

        :param limit: The limit to the number of secrets to list
        :param offset: The offset from the beginning to start listing
        """
        LOG.debug(
            _("Listing secrets - offset: {0}, limit: {1}").format(
                offset, limit))
        href = "{0}/{1}?limit={2}&offset={3}".format(self._tenant,
                                                     self.SECRETS_PATH, limit,
                                                     offset)
        return self.list_secrets_by_href(href)
Example #43
0
    def __init__(self,
                 auth_endpoint=None,
                 user=None,
                 key=None,
                 tenant=None,
                 token=None,
                 **kwargs):
        """
        Authenticate and connect to the service endpoint, which can be
        received through authentication.

        Environment variables will be used by default when their corresponding
        arguments are not passed in.

        :param auth_endpoint: The auth URL to authenticate against
                              default: env('OS_AUTH_URL')
        :param user: The user to authenticate as
                     default: env('OS_USERNAME')
        :param key: The API key or password to auth with
                    default: env('OS_PASSWORD')
        :param tenant: The tenant ID
                       default: env('OS_TENANT_NAME')
        :keyword param endpoint: The barbican endpoint to connect to
                       default: env('BARBICAN_ENDPOINT')

        If a token is provided, an endpoint should be as well.
        """

        LOG.debug(_("Creating Connection object"))

        self.env = kwargs.get('fake_env') or env
        self._auth_endpoint = auth_endpoint or self.env('OS_AUTH_URL')
        self._user = user or self.env('OS_USERNAME')
        self._key = key or self.env('OS_PASSWORD')
        self._tenant = tenant or self.env('OS_TENANT_NAME')
        if not all([self._auth_endpoint, self._user, self._key, self._tenant]):
            raise ClientException("The authorization endpoint, username, key,"
                                  " and tenant name should either be passed i"
                                  "n or defined as environment variables.")
        self.authenticate = kwargs.get('authenticate') or auth.authenticate
        self.request = kwargs.get('request') or requests.request
        self._endpoint = (kwargs.get('endpoint')
                          or self.env('BARBICAN_ENDPOINT'))
        self._cacert = kwargs.get('cacert')
        self.connect(token=(token or self.env('AUTH_TOKEN')))
Example #44
0
    def __init__(self, session=None, auth_plugin=None, endpoint=None,
                 tenant_id=None, insecure=False, service_type='keystore',
                 interface='public'):
        """
        Barbican client object used to interact with barbican service.

        :param session: This can be either requests.Session or
            keystoneclient.session.Session
        :param auth_plugin: Authentication backend plugin
            defaults to None. This can also be a keystoneclient authentication
            plugin.
        :param endpoint: Barbican endpoint url.  Required when not using
            an auth_plugin.  When not provided, the client will try to
            fetch this from the auth service catalog
        :param tenant_id: The tenant ID used for context in barbican.
            Required when not using auth_plugin.  When not provided,
            the client will try to get this from the auth_plugin.
        :param insecure: Explicitly allow barbicanclient to perform
            "insecure" TLS (https) requests. The server's certificate
            will not be verified against any certificate authorities.
            This option should be used with caution.
        :param service_type: Used as an endpoint filter when using a
            keystone auth plugin. Defaults to 'keystore'
        :param interface: Another endpoint filter. Defaults to 'public'
        """
        LOG.debug(_("Creating Client object"))
        self._wrap_session_with_keystone_if_required(session, insecure)
        auth_plugin = self._update_session_auth_plugin(auth_plugin)

        if auth_plugin:
            self._barbican_url = self._session.get_endpoint(
                service_type=service_type, interface=interface)
            self._tenant_id = self._get_tenant_id(self._session, auth_plugin)
        else:
            # neither auth_plugin is provided nor it is available from session
            # fallback to passed in parameters
            self._validate_endpoint_and_tenant_id(endpoint, tenant_id)
            self._barbican_url = self._get_normalized_endpoint(endpoint)
            self._tenant_id = tenant_id

        self.base_url = '{0}/{1}'.format(self._barbican_url, self._tenant_id)
        self.secrets = secrets.SecretManager(self)
        self.orders = orders.OrderManager(self)
        self.verifications = verifications.VerificationManager(self)
Example #45
0
def setup_logging():
    """
    Sets up the logging options
    """

    if CONF.log_config:
        # Use a logging configuration file for all settings...
        if os.path.exists(CONF.log_config):
            logging.config.fileConfig(CONF.log_config)
            return
        else:
            raise RuntimeError("Unable to locate specified logging "
                               "config file: %s" % CONF.log_config)

    root_logger = logging.root
    if CONF.debug:
        root_logger.setLevel(logging.DEBUG)
    elif CONF.verbose:
        root_logger.setLevel(logging.INFO)
    else:
        root_logger.setLevel(logging.WARNING)

    formatter = logging.Formatter(CONF.log_format, CONF.log_date_format)

    if CONF.use_syslog:
        try:
            facility = getattr(logging.handlers.SysLogHandler,
                               CONF.syslog_log_facility)
        except AttributeError:
            raise ValueError(_("Invalid syslog facility"))

        handler = logging.handlers.SysLogHandler(address='/dev/log',
                                                 facility=facility)
    elif CONF.log_file:
        logfile = CONF.log_file
        if CONF.log_dir:
            logfile = os.path.join(CONF.log_dir, logfile)
        handler = logging.handlers.WatchedFileHandler(logfile)
    else:
        handler = logging.StreamHandler(sys.stdout)

    handler.setFormatter(formatter)
    root_logger.addHandler(handler)
    def __init__(self, auth_endpoint, user, key, tenant,
                 token=None, authenticate=None, request=None, **kwargs):
        """
        :param auth_endpoint: The auth URL to authenticate against
        :param user: The user to authenticate as
        :param key: The API key or password to auth with
        """

        LOG.debug(_("Creating Connection object"))

        self._auth_endpoint = auth_endpoint
        self.authenticate = authenticate or auth.authenticate
        self.request = request or requests.request
        self._user = user
        self._key = key
        self._tenant = tenant
        self._endpoint = (kwargs.get('endpoint')
                          or 'https://barbican.api.rackspacecloud.com/v1/')
        self._cacert = kwargs.get('cacert')

        self.connect(token=token)
Example #47
0
def _find_facility_from_conf():
    facility_names = logging.handlers.SysLogHandler.facility_names
    facility = getattr(logging.handlers.SysLogHandler,
                       CONF.syslog_log_facility,
                       None)

    if facility is None and CONF.syslog_log_facility in facility_names:
        facility = facility_names.get(CONF.syslog_log_facility)

    if facility is None:
        valid_facilities = facility_names.keys()
        consts = ['LOG_AUTH', 'LOG_AUTHPRIV', 'LOG_CRON', 'LOG_DAEMON',
                  'LOG_FTP', 'LOG_KERN', 'LOG_LPR', 'LOG_MAIL', 'LOG_NEWS',
                  'LOG_AUTH', 'LOG_SYSLOG', 'LOG_USER', 'LOG_UUCP',
                  'LOG_LOCAL0', 'LOG_LOCAL1', 'LOG_LOCAL2', 'LOG_LOCAL3',
                  'LOG_LOCAL4', 'LOG_LOCAL5', 'LOG_LOCAL6', 'LOG_LOCAL7']
        valid_facilities.extend(consts)
        raise TypeError(_('syslog facility must be one of: %s') %
                        ', '.join("'%s'" % fac
                                  for fac in valid_facilities))

    return facility
Example #48
0
def _find_facility_from_conf():
    facility_names = logging.handlers.SysLogHandler.facility_names
    facility = getattr(logging.handlers.SysLogHandler,
                       CONF.syslog_log_facility, None)

    if facility is None and CONF.syslog_log_facility in facility_names:
        facility = facility_names.get(CONF.syslog_log_facility)

    if facility is None:
        valid_facilities = facility_names.keys()
        consts = [
            'LOG_AUTH', 'LOG_AUTHPRIV', 'LOG_CRON', 'LOG_DAEMON', 'LOG_FTP',
            'LOG_KERN', 'LOG_LPR', 'LOG_MAIL', 'LOG_NEWS', 'LOG_AUTH',
            'LOG_SYSLOG', 'LOG_USER', 'LOG_UUCP', 'LOG_LOCAL0', 'LOG_LOCAL1',
            'LOG_LOCAL2', 'LOG_LOCAL3', 'LOG_LOCAL4', 'LOG_LOCAL5',
            'LOG_LOCAL6', 'LOG_LOCAL7'
        ]
        valid_facilities.extend(consts)
        raise TypeError(
            _('syslog facility must be one of: %s') %
            ', '.join("'%s'" % fac for fac in valid_facilities))

    return facility
Example #49
0
class DeprecatedConfig(Exception):
    message = _("Fatal call to deprecated config: %(msg)s")

    def __init__(self, msg):
        super(Exception, self).__init__(self.message % dict(msg=msg))
 def delete_order(self, href):
     """
     Deletes an order using its full reference
     """
     hdrs, body = self._perform_http(href=href, method='DELETE')
     LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))
 def delete_order(self, href):
     """
     Deletes an order using its full reference
     """
     hdrs, body = self._perform_http(href=href, method='DELETE')
     LOG.debug(_("Response - headers: {0}\nbody: {1}").format(hdrs, body))