Exemple #1
0
    def new_tag(self, **kwargs):
        owner = kwargs.pop('owner', self.context.owner)
        if not self.context.is_admin:
            if owner is None:
                message = _("Owner must be specified to create a tag.")
                raise exception.Forbidden(message)
            elif owner != self.context.owner:
                message = _("You are not permitted to create a tag"
                            " in the namespace owned by '%s'")
                raise exception.Forbidden(message % (owner))

        return super(MetadefTagFactoryProxy, self).new_tag(**kwargs)
Exemple #2
0
    def new_image_member(self, image, member_id):
        owner = image.owner

        if not self.context.is_admin:
            if owner is None or owner != self.context.owner:
                message = _("You are not permitted to create image members "
                            "for the image.")
                raise exception.Forbidden(message)

        if image.visibility == 'public':
            message = _("Public images do not have members.")
            raise exception.Forbidden(message)

        return self.image_member_factory.new_image_member(image, member_id)
Exemple #3
0
 def add_to_backend(self,
                    conf,
                    image_id,
                    data,
                    size,
                    scheme=None,
                    context=None,
                    verifier=None):
     store_max_size = 7
     current_store_size = 2
     for location in self.data.keys():
         if image_id in location:
             raise exception.Duplicate()
     if not size:
         # 'data' is a string wrapped in a LimitingReader|CooperativeReader
         # pipeline, so peek under the hood of those objects to get at the
         # string itself.
         size = len(data.data.fd)
     if (current_store_size + size) > store_max_size:
         raise exception.StorageFull()
     if context.user == USER2:
         raise exception.Forbidden()
     if context.user == USER3:
         raise exception.StorageWriteDenied()
     self.data[image_id] = (data, size)
     checksum = 'Z'
     return (image_id, size, checksum, self.store_metadata)
Exemple #4
0
 def save(self, image_member, from_state=None):
     if (self.context.is_admin
             or self.context.owner == image_member.member_id):
         self.member_repo.save(image_member, from_state=from_state)
     else:
         message = _("You cannot update image member %s")
         raise exception.Forbidden(message % image_member.member_id)
Exemple #5
0
 def forbidden(self, *args, **kwargs):
     resource = getattr(self, 'resource_name', 'resource')
     message = _("You are not permitted to modify '%(attr)s' on this "
                 "%(resource)s.")
     raise exception.Forbidden(message % {
         'attr': attr,
         'resource': resource
     })
Exemple #6
0
 def get(self, member_id):
     if (self.context.is_admin
             or self.context.owner in (self.image.owner, member_id)):
         member = self.member_repo.get(member_id)
         return proxy_member(self.context, member)
     else:
         message = _("You cannot get image member for %s")
         raise exception.Forbidden(message % member_id)
Exemple #7
0
 def list(self, *args, **kwargs):
     members = self.member_repo.list(*args, **kwargs)
     if (self.context.is_admin or self.context.owner == self.image.owner):
         return [proxy_member(self.context, m) for m in members]
     for member in members:
         if member.member_id == self.context.owner:
             return [proxy_member(self.context, member)]
     message = _("You cannot get image member for %s")
     raise exception.Forbidden(message % self.image.image_id)
Exemple #8
0
    def new_image(self, **kwargs):
        owner = kwargs.pop('owner', self.context.owner)

        if not self.context.is_admin:
            if owner is None or owner != self.context.owner:
                message = _("You are not permitted to create images "
                            "owned by '%s'.")
                raise exception.Forbidden(message % owner)

        return super(ImageFactoryProxy, self).new_image(owner=owner, **kwargs)
Exemple #9
0
    def new_object(self, **kwargs):
        owner = kwargs.pop('owner', self.context.owner)

        if not self.context.is_admin:
            if owner is None or owner != self.context.owner:
                message = _("You are not permitted to create object "
                            "owned by '%s'")
                raise exception.Forbidden(message % (owner))

        return super(MetadefObjectFactoryProxy, self).new_object(**kwargs)
Exemple #10
0
 def reactivate(self):
     if self.status == 'deactivated':
         self.status = 'active'
     elif self.status == 'active':
         # Noop if already active
         pass
     else:
         LOG.debug("Not allowed to reactivate image in status '%s'",
                   self.status)
         msg = (_("Not allowed to reactivate image in status '%s'") %
                self.status)
         raise exception.Forbidden(message=msg)
Exemple #11
0
    def new_task(self, **kwargs):
        owner = kwargs.get('owner', self.context.owner)

        # NOTE(nikhil): Unlike Images, Tasks are expected to have owner.
        # We currently do not allow even admins to set the owner to None.
        if owner is not None and (owner == self.context.owner
                                  or self.context.is_admin):
            return super(TaskFactoryProxy, self).new_task(**kwargs)
        else:
            message = _("You are not permitted to create this task with "
                        "owner as: %s")
            raise exception.Forbidden(message % owner)
Exemple #12
0
    def download(self, req, image_id):
        image_repo = self.gateway.get_repo(req.context)
        try:
            image = image_repo.get(image_id)
            if image.status == 'deactivated' and not req.context.is_admin:
                msg = _('The requested image has been deactivated. '
                        'Image data download is forbidden.')
                raise exception.Forbidden(message=msg)
        except exception.NotFound as e:
            raise webob.exc.HTTPNotFound(explanation=e.msg)
        except exception.Forbidden as e:
            LOG.debug("User not permitted to download image '%s'", image_id)
            raise webob.exc.HTTPForbidden(explanation=e.msg)

        return image
Exemple #13
0
    def _do_remove_locations(self, image, path_pos):
        if CONF.show_multiple_locations == False:
            msg = _("It's not allowed to remove locations if locations are "
                    "invisible.")
            raise webob.exc.HTTPForbidden(explanation=msg)

        if len(image.locations) == 1:
            LOG.debug("User forbidden to remove last location of image %s",
                      image.image_id)
            msg = _("Cannot remove last location in the image.")
            raise exception.Forbidden(msg)
        pos = self._get_locations_op_pos(path_pos, len(image.locations), False)
        if pos is None:
            msg = _("Invalid position for removing a location.")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        try:
            # NOTE(zhiyan): this actually deletes the location
            # from the backend store.
            image.locations.pop(pos)
        # TODO(jokke): Fix this, we should catch what store throws and
        # provide definitely something else than IternalServerError to user.
        except Exception as e:
            raise webob.exc.HTTPInternalServerError(
                explanation=encodeutils.exception_to_unicode(e))
Exemple #14
0
    def test_catch_error_forbidden(self, mock_function):
        mock_function.side_effect = exception.Forbidden()

        self.assertEqual(cache_manage.FAILURE,
                         cache_manage.list_cached(mock.Mock(), None))
Exemple #15
0
 def data_iterator():
     self.notifier.log = []
     yield 'abcde'
     raise exception.Forbidden('Not allowed')
Exemple #16
0
 def enforce(self, _ctxt, action, target=None, **kwargs):
     """Raise Forbidden if a rule for given action is set to false."""
     if self.rules.get(action) is False:
         raise exception.Forbidden()
Exemple #17
0
 def forbidden_key(self, key, *args, **kwargs):
     message = _("You are not permitted to modify '%s' on this image.")
     raise exception.Forbidden(message % key)
Exemple #18
0
 def begin_processing(self):
     message = _("You are not permitted to set status on this task.")
     raise exception.Forbidden(message)
 def __len__(self):
     raise exception.Forbidden()
Exemple #20
0
 def save(self):
     message = _("You are not permitted to update this tag.")
     raise exception.Forbidden(message)
Exemple #21
0
 def delete(self):
     message = _("You are not permitted to delete this tag.")
     raise exception.Forbidden(message)
Exemple #22
0
 def delete(self):
     message = _("You are not permitted to delete this meta_resource_type.")
     raise exception.Forbidden(message)
Exemple #23
0
 def set_data(self, *args, **kwargs):
     message = _("You are not permitted to upload data for this image.")
     raise exception.Forbidden(message)
Exemple #24
0
 def fail(self, message):
     message = _("You are not permitted to set status on this task.")
     raise exception.Forbidden(message)
Exemple #25
0
 def succeed(self, result):
     message = _("You are not permitted to set status on this task.")
     raise exception.Forbidden(message)
Exemple #26
0
    def _do_request(self, method, url, body, headers):
        """
        Connects to the server and issues a request.  Handles converting
        any returned HTTP error status codes to OpenStack/Glance exceptions
        and closing the server connection. Returns the result data, or
        raises an appropriate exception.

        :param method: HTTP method ("GET", "POST", "PUT", etc...)
        :param url: urlparse.ParsedResult object with URL information
        :param body: data to send (as string, filelike or iterable),
                     or None (default)
        :param headers: mapping of key/value pairs to add as headers

        :note

        If the body param has a read attribute, and method is either
        POST or PUT, this method will automatically conduct a chunked-transfer
        encoding and use the body as a file object or iterable, transferring
        chunks of data using the connection's send() method. This allows large
        objects to be transferred efficiently without buffering the entire
        body in memory.
        """
        if url.query:
            path = url.path + "?" + url.query
        else:
            path = url.path

        try:
            connection_type = self.get_connection_type()
            headers = self._encode_headers(headers or {})
            headers.update(osprofiler.web.get_trace_id_headers())

            if 'x-auth-token' not in headers and self.auth_token:
                headers['x-auth-token'] = self.auth_token

            c = connection_type(url.hostname, url.port, **self.connect_kwargs)

            def _pushing(method):
                return method.lower() in ('post', 'put')

            def _simple(body):
                return body is None or isinstance(body, bytes)

            def _filelike(body):
                return hasattr(body, 'read')

            def _sendbody(connection, iter):
                connection.endheaders()
                for sent in iter:
                    # iterator has done the heavy lifting
                    pass

            def _chunkbody(connection, iter):
                connection.putheader('Transfer-Encoding', 'chunked')
                connection.endheaders()
                for chunk in iter:
                    connection.send('%x\r\n%s\r\n' % (len(chunk), chunk))
                connection.send('0\r\n\r\n')

            # Do a simple request or a chunked request, depending
            # on whether the body param is file-like or iterable and
            # the method is PUT or POST
            #
            if not _pushing(method) or _simple(body):
                # Simple request...
                c.request(method, path, body, headers)
            elif _filelike(body) or self._iterable(body):
                c.putrequest(method, path)

                use_sendfile = self._sendable(body)

                # According to HTTP/1.1, Content-Length and Transfer-Encoding
                # conflict.
                for header, value in headers.items():
                    if use_sendfile or header.lower() != 'content-length':
                        c.putheader(header, str(value))

                iter = utils.chunkreadable(body)

                if use_sendfile:
                    # send actual file without copying into userspace
                    _sendbody(c, iter)
                else:
                    # otherwise iterate and chunk
                    _chunkbody(c, iter)
            else:
                raise TypeError('Unsupported image type: %s' % body.__class__)

            res = c.getresponse()

            def _retry(res):
                return res.getheader('Retry-After')

            def read_body(res):
                body = res.read()
                if six.PY3:
                    body = body.decode('utf-8')
                return body

            status_code = self.get_status_code(res)
            if status_code in self.OK_RESPONSE_CODES:
                return res
            elif status_code in self.REDIRECT_RESPONSE_CODES:
                raise exception.RedirectException(res.getheader('Location'))
            elif status_code == http_client.UNAUTHORIZED:
                raise exception.NotAuthenticated(read_body(res))
            elif status_code == http_client.FORBIDDEN:
                raise exception.Forbidden(read_body(res))
            elif status_code == http_client.NOT_FOUND:
                raise exception.NotFound(read_body(res))
            elif status_code == http_client.CONFLICT:
                raise exception.Duplicate(read_body(res))
            elif status_code == http_client.BAD_REQUEST:
                raise exception.Invalid(read_body(res))
            elif status_code == http_client.MULTIPLE_CHOICES:
                raise exception.MultipleChoices(body=read_body(res))
            elif status_code == http_client.REQUEST_ENTITY_TOO_LARGE:
                raise exception.LimitExceeded(retry=_retry(res),
                                              body=read_body(res))
            elif status_code == http_client.INTERNAL_SERVER_ERROR:
                raise exception.ServerError()
            elif status_code == http_client.SERVICE_UNAVAILABLE:
                raise exception.ServiceUnavailable(retry=_retry(res))
            else:
                raise exception.UnexpectedStatus(status=status_code,
                                                 body=read_body(res))

        except (socket.error, IOError) as e:
            raise exception.ClientConnectionError(e)
 def test_download_forbidden(self):
     request = unit_test_utils.get_fake_request()
     self.image_repo.result = exception.Forbidden()
     self.assertRaises(webob.exc.HTTPForbidden, self.controller.download,
                       request, str(uuid.uuid4()))
Exemple #28
0
 def forbidden(self, *args, **kwargs):
     message = _("You are not permitted to modify tags on this image.")
     raise exception.Forbidden(message)
 def get_data(*args, **kwargs):
     raise exception.Forbidden()
Exemple #30
0
 def reactivate(self, *args, **kwargs):
     message = _("You are not permitted to reactivate this image.")
     raise exception.Forbidden(message)