How to use the keystonemiddleware.i18n._ function in keystonemiddleware

To help you get started, we’ve selected a few keystonemiddleware examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github openstack / keystonemiddleware / keystonemiddleware / auth_token / __init__.py View on Github external
for d_o in o.deprecated_opts:
            opt_types[d_o.name] = type_dest

    opts = {}
    for k, v in six.iteritems(conf):
        dest = k
        try:
            if v is not None:
                type_, dest = opt_types[k]
                v = type_(v)
        except KeyError:
            # This option is not known to auth_token.
            pass
        except ValueError as e:
            raise ksm_exceptions.ConfigurationError(
                _('Unable to convert the value of %(key)s option into correct '
                  'type: %(ex)s') % {'key': k, 'ex': e})
        opts[dest] = v
    return opts
github openstack / keystonemiddleware / keystonemiddleware / ec2_token.py View on Github external
def __call__(self, req):
        # NOTE(alevine): We need to calculate the hash here because
        # subsequent access to request modifies the req.body so the hash
        # calculation will yield invalid results.
        body_hash = hashlib.sha256(req.body).hexdigest()

        signature = self._get_signature(req)
        if not signature:
            msg = _("Signature not provided")
            return self._ec2_error_response("AuthFailure", msg)
        access = self._get_access(req)
        if not access:
            msg = _("Access key not provided")
            return self._ec2_error_response("AuthFailure", msg)

        if 'X-Amz-Signature' in req.params or 'Authorization' in req.headers:
            auth_params = {}
        else:
            # Make a copy of args for authentication and signature verification
            auth_params = dict(req.params)
            # Not part of authentication args
            auth_params.pop('Signature', None)

        headers = req.headers
        if six.PY3:
github openstack / keystonemiddleware / keystonemiddleware / auth_token / _memcache_crypt.py View on Github external
"""
    # cache backends return None when no data is found. We don't mind
    # that this particular special value is unsigned.
    if signed_data is None:
        return None

    # First we calculate the signature
    provided_mac = signed_data[:DIGEST_LENGTH_B64]
    calculated_mac = sign_data(
        keys['MAC'],
        signed_data[DIGEST_LENGTH_B64:])

    # Then verify that it matches the provided value
    if not secretutils.constant_time_compare(provided_mac, calculated_mac):
        raise InvalidMacError(_('Invalid MAC; data appears to be corrupted.'))

    data = base64.b64decode(signed_data[DIGEST_LENGTH_B64:])

    # then if necessary decrypt the data
    if keys['strategy'] == b'ENCRYPT':
        data = decrypt_data(keys['ENCRYPTION'], data)

    return data
github openstack / keystonemiddleware / keystonemiddleware / auth_token / __init__.py View on Github external
def _invalid_user_token(self, msg=False):
        # NOTE(jamielennox): use False as the default so that None is valid
        if msg is False:
            msg = _('Token authorization failed')

        raise ksm_exceptions.InvalidToken(msg)
github openstack / keystonemiddleware / keystonemiddleware / auth_token / _signing_dir.py View on Github external
def _verify_signing_dir(self):
        if os.path.isdir(self._directory_name):
            if not os.access(self._directory_name, os.W_OK):
                raise exc.ConfigurationError(
                    _('unable to access signing_dir %s') %
                    self._directory_name)
            uid = os.getuid()
            if os.stat(self._directory_name).st_uid != uid:
                self._log.warning('signing_dir is not owned by %s', uid)
            current_mode = stat.S_IMODE(os.stat(self._directory_name).st_mode)
            if current_mode != stat.S_IRWXU:
                self._log.warning(
                    'signing_dir mode is %(mode)s instead of %(need)s',
                    {'mode': oct(current_mode), 'need': oct(stat.S_IRWXU)})
        else:
            os.makedirs(self._directory_name, stat.S_IRWXU)
github openstack / keystonemiddleware / keystonemiddleware / ec2_token.py View on Github external
data=creds_json, headers=headers,
                                    verify=verify, cert=cert)

        # NOTE(vish): We could save a call to keystone by
        #             having keystone return token, tenant,
        #             user, and roles from this call.

        status_code = response.status_code
        if status_code != 200:
            msg = _('Error response from keystone: %s') % response.reason
            self._logger.debug(msg)
            return self._ec2_error_response("AuthFailure", msg)
        try:
            token_id = response.headers['x-subject-token']
        except (AttributeError, KeyError):
            msg = _("Failure parsing response from keystone")
            self._logger.exception(msg)
            return self._ec2_error_response("AuthFailure", msg)

        # Authenticated!
        req.headers['X-Auth-Token'] = token_id
        return self._application
github openstack / keystonemiddleware / keystonemiddleware / auth_token / _identity.py View on Github external
"""
        try:
            auth_ref = self._request_strategy.verify_token(
                user_token,
                allow_expired=allow_expired)
        except ksa_exceptions.NotFound as e:
            self._LOG.info('Authorization failed for token')
            self._LOG.info('Identity response: %s', e.response.text)
            raise ksm_exceptions.InvalidToken(_('Token authorization failed'))
        except ksa_exceptions.Unauthorized as e:
            self._LOG.info('Identity server rejected authorization')
            self._LOG.warning('Identity response: %s', e.response.text)
            if retry:
                self._LOG.info('Retrying validation')
                return self.verify_token(user_token, False)
            msg = _('Identity server rejected authorization necessary to '
                    'fetch token data')
            raise ksm_exceptions.ServiceError(msg)
        except ksa_exceptions.HttpError as e:
            self._LOG.error(
                'Bad response code while validating token: %s %s',
                e.http_status, e.message)
            if hasattr(e.response, 'text'):
                self._LOG.warning('Identity response: %s', e.response.text)
            msg = _('Failed to fetch token data from identity server')
            raise ksm_exceptions.ServiceError(msg)
        else:
            return auth_ref
github openstack / keystonemiddleware / keystonemiddleware / auth_token / _identity.py View on Github external
response is received. Optional.
        :param allow_expired: Allow retrieving an expired token.
        :returns: access info received from identity server on success
        :rtype: :py:class:`keystoneauth1.access.AccessInfo`
        :raises exc.InvalidToken: if token is rejected
        :raises exc.ServiceError: if unable to authenticate token

        """
        try:
            auth_ref = self._request_strategy.verify_token(
                user_token,
                allow_expired=allow_expired)
        except ksa_exceptions.NotFound as e:
            self._LOG.info('Authorization failed for token')
            self._LOG.info('Identity response: %s', e.response.text)
            raise ksm_exceptions.InvalidToken(_('Token authorization failed'))
        except ksa_exceptions.Unauthorized as e:
            self._LOG.info('Identity server rejected authorization')
            self._LOG.warning('Identity response: %s', e.response.text)
            if retry:
                self._LOG.info('Retrying validation')
                return self.verify_token(user_token, False)
            msg = _('Identity server rejected authorization necessary to '
                    'fetch token data')
            raise ksm_exceptions.ServiceError(msg)
        except ksa_exceptions.HttpError as e:
            self._LOG.error(
                'Bad response code while validating token: %s %s',
                e.http_status, e.message)
            if hasattr(e.response, 'text'):
                self._LOG.warning('Identity response: %s', e.response.text)
            msg = _('Failed to fetch token data from identity server')
github openstack / keystonemiddleware / keystonemiddleware / auth_token / _cache.py View on Github external
def __init__(self, log, security_strategy, secret_key, **kwargs):
        super(SecureTokenCache, self).__init__(log, **kwargs)

        if not secret_key:
            msg = _('memcache_secret_key must be defined when a '
                    'memcache_security_strategy is defined')
            raise exc.ConfigurationError(msg)

        if isinstance(security_strategy, six.string_types):
            security_strategy = security_strategy.encode('utf-8')
        if isinstance(secret_key, six.string_types):
            secret_key = secret_key.encode('utf-8')

        self._security_strategy = security_strategy
        self._secret_key = secret_key