Exemplo n.º 1
0
    def parse_headers(headers, default_version, latest_version):
        """Determine the API version requested based on the headers supplied.

        :param headers: webob headers
        :param default_version: version to use if not specified in headers
        :param latest_version: version to use if latest is requested
        :returns: a tuple of (major, minor) version numbers
        :raises: webob.HTTPNotAcceptable
        """

        version_hdr = headers.get(Version.string, default_version)

        try:
            version_service, version_str = version_hdr.split()
        except ValueError:
            raise exc.HTTPNotAcceptable(
                _("Invalid service type for %s header") % Version.string)

        if version_str.lower() == 'latest':
            version_service, version_str = latest_version.split()

        if version_service != Version.service_string:
            raise exc.HTTPNotAcceptable(
                _("Invalid service type for %s header") % Version.string)
        try:
            version = tuple(int(i) for i in version_str.split('.'))
        except ValueError:
            version = ()

        if len(version) != 2:
            raise exc.HTTPNotAcceptable(
                _("Invalid value for %s header") % Version.string)
        return version
Exemplo n.º 2
0
 def get_validate_region_name(self, region_name):
     if region_name is None:
         message = _("region_name needs to be configured in digital.conf")
         raise exception.InvalidParameterValue(message)
     """matches the region of a public endpoint for the Keystone
     service."""
     regions = None
     try:
         regions = self.client.regions.list()
     except kc_exception.NotFound:
         pass
     except Exception:
         LOG.exception('Failed to list regions')
         raise exception.RegionsListFailed()
     region_list = []
     for region in regions:
         region_list.append(region.id)
     if region_name not in region_list:
         raise exception.InvalidParameterValue(_(
             'region_name %(region_name)s is invalid, '
             'expecting a region_name in %(region_name_list)s.') % {
                 'region_name': region_name,
                 'region_name_list': '/'.join(
                     region_list + ['unspecified'])})
     return region_name
Exemplo n.º 3
0
 def _check_version(self, version, headers=None):
     if headers is None:
         headers = {}
     # ensure that major version in the URL matches the header
     if version.major != BASE_VERSION:
         raise http_error.HTTPNotAcceptableAPIVersion(
             _("Mutually exclusive versions requested. Version %(ver)s "
               "requested but not supported by this service."
               "The supported version range is: "
               "[%(min)s, %(max)s].") % {
                   'ver': version,
                   'min': MIN_VER_STR,
                   'max': MAX_VER_STR
               },
             headers=headers,
             max_version=str(MAX_VER),
             min_version=str(MIN_VER))
     # ensure the minor version is within the supported range
     if version < MIN_VER or version > MAX_VER:
         raise http_error.HTTPNotAcceptableAPIVersion(
             _("Version %(ver)s was requested but the minor version is not "
               "supported by this service. The supported version range is: "
               "[%(min)s, %(max)s].") % {
                   'ver': version,
                   'min': MIN_VER_STR,
                   'max': MAX_VER_STR
               },
             headers=headers,
             max_version=str(MAX_VER),
             min_version=str(MIN_VER))
Exemplo n.º 4
0
    def get_cert(cert_ref, **kwargs):
        """Retrieves the specified cert.

        :param cert_ref: the UUID of the cert to retrieve

        :return: digital.common.cert_manager.cert_manager.Cert
                 representation of the certificate data
        :raises CertificateStorageException: if certificate retrieval fails
        """
        LOG.warning(
            "Loading certificate {0} from the local filesystem. "
            "CertManager type 'local' should be used for testing purpose.".
            format(cert_ref))

        filename_base = os.path.join(CONF.certificates.storage_path, cert_ref)

        filename_certificate = "{0}.crt".format(filename_base)
        filename_private_key = "{0}.key".format(filename_base)
        filename_intermediates = "{0}.int".format(filename_base)
        filename_pkp = "{0}.pass".format(filename_base)

        cert_data = dict()

        try:
            with open(filename_certificate, 'r') as cert_file:
                cert_data['certificate'] = cert_file.read()
        except IOError:
            LOG.error("Failed to read certificate for {0}.".format(cert_ref))
            raise exception.CertificateStorageException(
                msg=_("Certificate could not be read."))
        try:
            with open(filename_private_key, 'r') as key_file:
                cert_data['private_key'] = key_file.read()
        except IOError:
            LOG.error("Failed to read private key for {0}.".format(cert_ref))
            raise exception.CertificateStorageException(
                msg=_("Private Key could not be read."))

        try:
            if path.isfile(filename_intermediates):
                with open(filename_intermediates, 'r') as int_file:
                    cert_data['intermediates'] = int_file.read()
        except IOError as ioe:
            LOG.error("Failed to read certificate.")
            raise exception.CertificateStorageException(msg=str(ioe))

        try:
            if path.isfile(filename_pkp):
                with open(filename_pkp, 'r') as pass_file:
                    cert_data['private_key_passphrase'] = pass_file.read()
        except IOError as ioe:
            LOG.error("Failed to read certificate.")
            raise exception.CertificateStorageException(msg=str(ioe))

        return Cert(**cert_data)
Exemplo n.º 5
0
Arquivo: api.py Projeto: knowx/digital
def _get_ssl_configs(use_ssl):
    if use_ssl:
        cert_file = CONF.api.ssl_cert_file
        key_file = CONF.api.ssl_key_file

        if cert_file and not os.path.exists(cert_file):
            raise RuntimeError(_("Unable to find cert_file : %s") % cert_file)

        if key_file and not os.path.exists(key_file):
            raise RuntimeError(_("Unable to find key_file : %s") % key_file)

        return cert_file, key_file
    else:
        return None
Exemplo n.º 6
0
 def __init__(self, cert_container):
     if not isinstance(cert_container,
                       barbican_client.containers.CertificateContainer):
         raise TypeError(_(
             "Retrieved Barbican Container is not of the correct type "
             "(certificate)."))
     self._cert_container = cert_container
Exemplo n.º 7
0
    def validate(patch):
        if patch.path in patch.internal_attrs():
            msg = _("'%s' is an internal attribute and can not be updated")
            raise wsme.exc.ClientSideError(msg % patch.path)

        if patch.path in patch.non_removable_attrs() and patch.op == 'remove':
            msg = _("'%s' is a mandatory attribute and can not be removed")
            raise wsme.exc.ClientSideError(msg % patch.path)

        if patch.op != 'remove':
            if not patch.value:
                msg = _("'add' and 'replace' operations needs value")
                raise wsme.exc.ClientSideError(msg)

        ret = {'path': patch.path, 'op': patch.op}
        if patch.value:
            ret['value'] = patch.value
        return ret
Exemplo n.º 8
0
 def validate(self, value):
     for t in self.types:
         try:
             return wtypes.validate_value(t, value)
         except (exception.InvalidUUID, ValueError):
             pass
     else:
         raise ValueError(
             _("Wrong type. Expected '%(type)s', got '%(value)s'") % {
                 'type': self.types,
                 'value': type(value)
             })
Exemplo n.º 9
0
class DigitalException(Exception):
    """Base Digital Exception

    To correctly use this class, inherit from it and define
    a 'message' property. That message will get printf'd
    with the keyword arguments provided to the constructor.

    """
    message = _("An unknown exception occurred.")
    code = 500

    def __init__(self, message=None, **kwargs):
        self.kwargs = kwargs

        if 'code' not in self.kwargs and hasattr(self, 'code'):
            self.kwargs['code'] = self.code

        if message:
            self.message = message

        try:
            self.message = self.message % kwargs
        except Exception:
            # kwargs doesn't match a variable in the message
            # log the issue and the kwargs
            LOG.exception('Exception in string format operation, '
                          'kwargs: %s', kwargs)
            try:
                if CONF.fatal_exception_format_errors:
                    raise
            except cfg.NoSuchOptError:
                # Note: work around for Bug: #1447873
                if CONF.oslo_versionedobjects.fatal_exception_format_errors:
                    raise

        super(DigitalException, self).__init__(self.message)

    def __str__(self):
        if six.PY3:
            return self.message
        return self.message.encode('utf-8')

    def __unicode__(self):
        return self.message

    def format_message(self):
        if self.__class__.__name__.endswith('_Remote'):
            return self.args[0]
        else:
            return six.text_type(self)
Exemplo n.º 10
0
def _paginate_query(model, limit=None, marker=None, sort_key=None,
                    sort_dir=None, query=None):
    if not query:
        query = model_query(model)
    sort_keys = ['id']
    if sort_key and sort_key not in sort_keys:
        sort_keys.insert(0, sort_key)
    try:
        query = db_utils.paginate_query(query, model, limit, sort_keys,
                                        marker=marker, sort_dir=sort_dir)
    except db_exc.InvalidSortKey:
        raise exception.InvalidParameterValue(
            _('The sort_key value "%(key)s" is an invalid field for sorting')
            % {'key': sort_key})
    return query.all()
Exemplo n.º 11
0
    def __init__(self, app, conf, public_api_routes=None):
        if public_api_routes is None:
            public_api_routes = []
        route_pattern_tpl = '%s(\.json)?$'

        try:
            self.public_api_routes = [
                re.compile(route_pattern_tpl % route_tpl)
                for route_tpl in public_api_routes
            ]
        except re.error as e:
            msg = _('Cannot compile public API routes: %s') % e

            LOG.error(msg)
            raise exception.ConfigInvalid(error_msg=msg)

        super(AuthTokenMiddleware, self).__init__(app, conf)
Exemplo n.º 12
0
        def replacement_start_response(status, headers, exc_info=None):
            """Overrides the default response to make errors parsable."""
            try:
                status_code = int(status.split(' ')[0])
                state['status_code'] = status_code
            except (ValueError, TypeError):  # pragma: nocover
                raise Exception(
                    _('ErrorDocumentMiddleware received an invalid '
                      'status %s') % status)
            else:
                if (state['status_code'] // 100) not in (2, 3):
                    # Remove some headers so we can replace them later
                    # when we have the full error message and can
                    # compute the length.
                    headers = [(h, v) for (h, v) in headers
                               if h not in ('Content-Length', 'Content-Type')]
                # Save the headers in case we need to modify them.
                state['headers'] = headers

                return start_response(status, headers, exc_info)
Exemplo n.º 13
0
        def version_select():
            """Select the correct method based on version

            @return: Returns the correct versioned method
            @raises: HTTPNotAcceptable if there is no method which
                 matches the name and version constraints
            """

            from pecan import request
            ver = request.version

            func_list = self.versioned_methods[key]
            for func in func_list:
                if ver.matches(func.start_version, func.end_version):
                    return func.func

            raise exc.HTTPNotAcceptable(
                _("Version %(ver)s was requested but the requested API %(api)s "
                  "is not supported for this version.") % {
                      'ver': ver,
                      'api': key
                  })
Exemplo n.º 14
0
class TrustDeleteFailed(DigitalException):
    message = _("Failed to delete trust %(trust_id)s.")
Exemplo n.º 15
0
from oslo_config import cfg

from digital.i18n import _

barbican_group = cfg.OptGroup(name='barbican_client',
                              title='Options for the Barbican client')

barbican_client_opts = [
    cfg.StrOpt('region_name',
               help=_('Region in Identity service catalog to use for '
                      'communication with the OpenStack service.')),
    cfg.StrOpt('endpoint_type',
               default='publicURL',
               help=_('Type of endpoint in Identity service catalog to use '
                      'for communication with the OpenStack service.'))
]


def register_opts(conf):
    conf.register_group(barbican_group)
    conf.register_opts(barbican_client_opts, group=barbican_group)


def list_opts():
    return {barbican_group: barbican_client_opts}
Exemplo n.º 16
0
class TrusteeCreateFailed(DigitalException):
    message = _("Failed to create trustee %(username)s "
                "in domain %(domain_id)s")
Exemplo n.º 17
0
class TrusteeOrTrustToClusterFailed(DigitalException):
    message = _("Failed to create trustee or trust for Cluster: "
                "%(cluster_uuid)s")
Exemplo n.º 18
0
from oslo_config import cfg

from digital.i18n import _

trust_group = cfg.OptGroup(name='trust',
                           title='Trustee options for the digital services')

trust_opts = [
    cfg.BoolOpt('cluster_user_trust',
                default=False,
                help=_('This setting controls whether to assign a trust to'
                       ' the cluster user or not. You will need to set it to'
                       ' True for clusters with volume_driver=cinder or'
                       ' registry_enabled=true in the underlying cluster'
                       ' template to work. This is a potential security risk'
                       ' since the trust gives instances OpenStack API access'
                       " to the cluster's project. Note that this setting"
                       ' does not affect per-cluster trusts assigned to the'
                       'Digital service user.')),
    cfg.StrOpt('trustee_domain_id',
               help=_('Id of the domain to create trustee for clusters')),
    cfg.StrOpt('trustee_domain_name',
               help=_('Name of the domain to create trustee for s')),
    cfg.StrOpt('trustee_domain_admin_id',
               help=_('Id of the admin with roles sufficient to manage users'
                      ' in the trustee_domain')),
    cfg.StrOpt('trustee_domain_admin_name',
               help=_('Name of the admin with roles sufficient to manage users'
                      ' in the trustee_domain')),
    cfg.StrOpt('trustee_domain_admin_domain_id',
Exemplo n.º 19
0
class KeyPairNotFound(ResourceNotFound):
    message = _("Unable to find keypair %(keypair)s.")
Exemplo n.º 20
0
class MemberAlreadyExists(Conflict):
    message = _("A cluster with UUID %(uuid)s is already a member of the"
                "federation %(federation_name)s.")
Exemplo n.º 21
0
class FederationAlreadyExists(Conflict):
    message = _("A federation with UUID %(uuid)s already exists.")
Exemplo n.º 22
0
class FederationNotFound(ResourceNotFound):
    message = _("Federation %(federation)s could not be found.")
Exemplo n.º 23
0
class CertificatesToClusterFailed(DigitalException):
    message = _("Failed to create certificates for Cluster: %(cluster_uuid)s")
Exemplo n.º 24
0
class TrustCreateFailed(DigitalException):
    message = _("Failed to create trust for trustee %(trustee_user_id)s.")
Exemplo n.º 25
0
class DigitalServiceAlreadyExists(Conflict):
    message = _("A digital service with ID %(id)s already exists.")
Exemplo n.º 26
0
               'running commands as root.'),
    cfg.StrOpt('tempdir',
               help='Explicitly specify the temporary working directory.'),
    cfg.ListOpt('password_symbols',
                default=DEFAULT_PASSWORD_SYMBOLS,
                help='Symbols to use for passwords')
]

periodic_opts = [
    cfg.IntOpt('service_down_time',
               default=180,
               help='Max interval size between periodic tasks execution in '
               'seconds.'),
]

urlfetch_opts = [
    cfg.IntOpt('max_manifest_size',
               default=524288,
               help=_('Maximum raw byte size of any manifest.'))
]

ALL_OPTS = list(itertools.chain(utils_opts, periodic_opts, urlfetch_opts))


def register_opts(conf):
    conf.register_opts(ALL_OPTS)


def list_opts():
    return {"DEFAULT": ALL_OPTS}
Exemplo n.º 27
0
class DigitalServiceNotFound(ResourceNotFound):
    message = _("A digital service %(digital_service_id)s could not be found.")
Exemplo n.º 28
0
class RegionsListFailed(DigitalException):
    message = _("Failed to list regions.")
Exemplo n.º 29
0
class TrusteeDeleteFailed(DigitalException):
    message = _("Failed to delete trustee %(trustee_id)s")
Exemplo n.º 30
0
class ServicesListFailed(DigitalException):
    message = _("Failed to list services.")