Пример #1
0
    def __call__(self, environ, start_response):
        request = Request(environ)
        session = environ['beaker.session']
        session.save()

        if request.method == 'POST':
            # check to see if we want to process the post at all
            if (self.unprotected_path is not None
                and request.path_info.startswith(self.unprotected_path)):
                resp = request.get_response(self.app)
                return resp(environ, start_response)

            csrf_token = session.id
            # check incoming token
            try:
                request_csrf_token = request.POST['csrfmiddlewaretoken']
                if request_csrf_token != csrf_token:
                    resp = HTTPForbidden(_ERROR_MSG)
                else:
                    resp = request.get_response(self.app)
            except KeyError:
                resp = HTTPForbidden(_ERROR_MSG)
        # if we're a get, we don't do any checking
        else:
            resp = request.get_response(self.app)

        if resp.status_int != 200:
            return resp(environ, start_response)

        session = environ['beaker.session']
        csrf_token = session.id

        if resp.content_type.split(';')[0] in _HTML_TYPES:
            # ensure we don't add the 'id' attribute twice (HTML validity)
            idattributes = itertools.chain(('id="csrfmiddlewaretoken"',), 
                                            itertools.repeat(''))
            def add_csrf_field(match):
                """Returns the matched <form> tag plus the added <input> element"""
                return match.group() + '<div style="display:none;">' + \
                '<input type="hidden" ' + idattributes.next() + \
                ' name="csrfmiddlewaretoken" value="' + csrf_token + \
                '" /></div>'

            # Modify any POST forms and fix content-length
            resp.body = _POST_FORM_RE.sub(add_csrf_field, resp.body)

        return resp(environ, start_response)
Пример #2
0
    def __call__(self, environ, start_response):
        request = Request(environ)
        session = environ['beaker.session']
        csrf_token = session.get('csrf')
        if not csrf_token:
            csrf_token = session['csrf'] = str(random.getrandbits(128))
            session.save()

        if request.method == 'POST':
            # check to see if we want to process the post at all
            if (self.unprotected_path is not None
                and request.path_info.startswith(self.unprotected_path)):
                resp = request.get_response(self.app)
                resp.headers['X-Frame-Options'] = 'SAMEORIGIN'
                resp.set_cookie('csrf', csrf_token, max_age=3600)
                return resp(environ, start_response)

            # check incoming token
            try:
                account_data = request.POST.get('account', None)
                request_csrf_token = environ.get('HTTP_X_CSRF', request.POST.get('csrftoken'))
                if account_data is None and request_csrf_token != csrf_token:
                    resp = HTTPForbidden(_ERROR_MSG)
                    metrics.track(request, 'invalid-session')
                    resp.headers['X-Error'] = 'CSRF'
                else:
                    resp = request.get_response(self.app)
            except KeyError:
                resp = HTTPForbidden(_ERROR_MSG)
                resp.headers['X-Error'] = 'CSRF'
        # if we're a get, we don't do any checking
        else:
            resp = request.get_response(self.app)

        if resp.status_int != 200:
            return resp(environ, start_response)

        resp.headers['X-Frame-Options'] = 'SAMEORIGIN'
        resp.set_cookie('csrf', csrf_token, max_age=3600)

        if resp.content_type.split(';')[0] in _HTML_TYPES:
            # ensure we don't add the 'id' attribute twice (HTML validity)
            idattributes = itertools.chain(('id="csrfmiddlewaretoken"',),
                                            itertools.repeat(''))
            def add_csrf_field(match):
                """Returns the matched <form> tag plus the added <input> element"""
                return match.group() + '<div style="display:none;">' + \
                '<input type="hidden" ' + idattributes.next() + \
                ' name="csrftoken" value="' + csrf_token + \
                '" /></div>'

            # Modify any POST forms and fix content-length
            resp.body = _POST_FORM_RE.sub(add_csrf_field, resp.body)

        return resp(environ, start_response)
Пример #3
0
 def _check_nova_lv_size(self, req, nova_lv_size, role_name):
     if role_name != "COMPUTER":
         msg = _("The role is not COMPUTER, it can't set logic "
                 "volume disk for nova.")
         raise HTTPForbidden(explanation=msg,
                             request=req,
                             content_type="text/plain")
     try:
         if int(nova_lv_size) < 0 and int(nova_lv_size) != -1:
             msg = _("The nova_lv_size must be -1 or [0, N).")
             raise HTTPForbidden(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
     except:
         msg = _("The nova_lv_size must be -1 or [0, N).")
         raise HTTPForbidden(explanation=msg,
                             request=req,
                             content_type="text/plain")
Пример #4
0
    def _reserve(self, req, image_meta):
        """
        Adds the image metadata to the registry and assigns
        an image identifier if one is not supplied in the request
        headers. Sets the image's status to `queued`.

        :param req: The WSGI/Webob Request object
        :param id: The opaque image identifier
        :param image_meta: The image metadata

        :raises HTTPConflict if image already exists
        :raises HTTPBadRequest if image metadata is not valid
        """
        location = self._external_source(image_meta, req)

        image_meta['status'] = ('active'
                                if image_meta.get('size') == 0 else 'queued')

        if location:
            store = get_store_from_location(location)
            # check the store exists before we hit the registry, but we
            # don't actually care what it is at this point
            self.get_store_or_400(req, store)

            # retrieve the image size from remote store (if not provided)
            image_meta['size'] = self._get_size(req.context, image_meta,
                                                location)
        else:
            # Ensure that the size attribute is set to zero for directly
            # uploadable images (if not provided). The size will be set
            # to a non-zero value during upload
            image_meta['size'] = image_meta.get('size', 0)

        try:
            image_meta = registry.add_image_metadata(req.context, image_meta)
            self.notifier.info("image.create", redact_loc(image_meta))
            return image_meta
        except exception.Duplicate:
            msg = (_("An image with identifier %s already exists") %
                   image_meta['id'])
            LOG.debug(msg)
            raise HTTPConflict(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Invalid as e:
            msg = (_("Failed to reserve image. Got error: %(e)s") % locals())
            for line in msg.split('\n'):
                LOG.debug(line)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.Forbidden:
            msg = _("Forbidden to reserve image.")
            LOG.debug(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
Пример #5
0
 def denied_response(self, req):
     """
     Returns a standard WSGI response callable with the status of 403 or 401
     depending on whether the REMOTE_USER is set or not.
     """
     if req.remote_user:
         return HTTPForbidden(request=req)
     else:
         return HTTPUnauthorized(request=req)
Пример #6
0
def login(self, request):
    credentials = request.json
    if Users.check(credentials['username'], credentials['password']):
        session = Users.createSession(credentials['username'])
        return {
            'username': credentials['username'],
            'sessionId': session.sessionId
        }
    raise HTTPForbidden()
Пример #7
0
 def delete(self, repo_name, pull_request_id):
     pull_request = PullRequest.get_or_404(pull_request_id)
     # only owner can delete it !
     if pull_request.owner_id == request.authuser.user_id:
         PullRequestModel().delete(pull_request)
         Session().commit()
         h.flash(_('Successfully deleted pull request'), category='success')
         raise HTTPFound(location=url('my_pullrequests'))
     raise HTTPForbidden()
Пример #8
0
def edit_account_view(context, request):
    confirmed = request.registry.queryAdapter(context,
                                              IRegistrations,
                                              name='confirmed')
    if confirmed is None:  #pragma NO COVERAGE
        confirmed = ConfirmedRegistrations(context)

    identity = request.environ.get('repoze.who.identity')
    if identity is None:
        return HTTPUnauthorized()

    userid = identity['repoze.who.userid']
    account_info = confirmed.get(userid)
    if account_info is None:
        return HTTPForbidden()

    appstruct = {
        'login_name': account_info.login,
        'email': account_info.email,
        'security': {
            'question': account_info.security_question or '',
            'answer': account_info.security_answer or '',
        },
    }
    schema = EditAccount().bind(current_login_name=account_info.login,
                                confirmed=confirmed,
                                old_password=account_info.password)
    form = Form(schema, buttons=('update', ))
    rendered_form = form.render(appstruct)

    if 'update' in request.POST:
        try:
            appstruct = form.validate(request.POST.items())
        except ValidationFailure, e:
            rendered_form = e.render()
        else:
            login = appstruct['login_name']
            email = appstruct['email']
            pwd_mgr = SSHAPasswordManager()
            password = pwd_mgr.encodePassword(appstruct['password'])
            security_question = appstruct['security']['question']
            security_answer = appstruct['security']['answer']
            confirmed.set(
                userid,
                email=email,
                login=login,
                password=password,
                security_question=security_question,
                security_answer=security_answer,
            )
            return HTTPFound(location=view_url(
                context,
                request,
                'after_edit_url',
                request.view_name,
            ))
Пример #9
0
    def request(self, dlg_id, start_response):
        """
        First step of the delegation process: get a certificate request

        The returned certificate request must be signed with the user's original
        credentials.
        """
        user = request.environ['fts3.User.Credentials']

        if dlg_id != user.delegation_id:
            raise HTTPForbidden(
                'The requested ID and the credentials ID do not match')

        credential_cache = Session.query(CredentialCache)\
            .get((user.delegation_id, user.user_dn))

        user_cert = self.certificate()

        request_key_len = 2048
        if user_cert:
            user_key = X509.load_cert_string(user_cert)
            request_key_len = user_key.get_pubkey().size() * 8

        cached = credential_cache is not None and credential_cache.cert_request is not None
        if cached:
            cached_key_len = X509.load_request_string(
                credential_cache.cert_request).get_pubkey().size() * 8
            if cached_key_len != request_key_len:
                cached = False
                log.debug(
                    "Invalidating cache due to key length missmatch between client and cached certificates"
                )

        if not cached:
            (x509_request,
             private_key) = _generate_proxy_request(request_key_len)
            credential_cache = CredentialCache(
                dlg_id=user.delegation_id,
                dn=user.user_dn,
                cert_request=x509_request.as_pem(),
                priv_key=private_key.as_pem(cipher=None),
                voms_attrs=' '.join(user.voms_cred))
            try:
                Session.merge(credential_cache)
                Session.commit()
            except Exception:
                Session.rollback()
                raise
            log.debug("Generated new credential request for %s" % dlg_id)
        else:
            log.debug("Using cached request for %s" % dlg_id)

        start_response('200 Ok',
                       [('X-Delegation-ID', str(credential_cache.dlg_id)),
                        ('Content-Type', 'text/plain')])
        return [credential_cache.cert_request]
Пример #10
0
    def create(self, req, image_meta, image_data):
        """
        Adds a new image to Glance. Three scenarios exist when creating an
        image:

        1. If the image data is available for upload, create can be passed the
           image data as the request body and the metadata as the request
           headers. The image will initially be 'queued', during upload it
           will be in the 'saving' status, and then 'killed' or 'active'
           depending on whether the upload completed successfully.

        2. If the image data exists somewhere else, you can pass in the source
           using the x-image-meta-location header

        3. If the image data is not available yet, but you'd like reserve a
           spot for it, you can omit the data and a record will be created in
           the 'queued' state. This exists primarily to maintain backwards
           compatibility with OpenStack/Rackspace API semantics.

        The request body *must* be encoded as application/octet-stream,
        otherwise an HTTPBadRequest is returned.

        Upon a successful save of the image data and metadata, a response
        containing metadata about the image is returned, including its
        opaque identifier.

        :param req: The WSGI/Webob Request object
        :param image_meta: Mapping of metadata about image
        :param image_data: Actual image data that is to be stored

        :raises HTTPBadRequest if x-image-meta-location is missing
                and the request body is not application/octet-stream
                image data.
        """
        self._enforce(req, 'add_image')
        if req.context.read_only:
            msg = _("Read-only access")
            logger.debug(msg)
            raise HTTPForbidden(msg, request=req,
                                content_type="text/plain")

        image_meta = self._reserve(req, image_meta)
        image_id = image_meta['id']

        if image_data is not None:
            image_meta = self._upload_and_activate(req, image_meta)
        else:
            location = image_meta.get('location')
            if location:
                image_meta = self._activate(req, image_id, location)

        # Prevent client from learning the location, as it
        # could contain security credentials
        image_meta.pop('location', None)

        return {'image_meta': image_meta}
Пример #11
0
class FTS3AuthMiddleware(object):
    """
    Pylons middleware to wrap the authentication as part of the request
    process.
    """

    def __init__(self, wrap_app, config):
        self.app    = wrap_app
        self.config = config

    def _trusted_origin(self, environ, parsed):
        allow_origin = environ.get('ACCESS_CONTROL_ORIGIN', None)
        if not allow_origin:
            return False
        return parsed.scheme + "://" + parsed.netloc == allow_origin

    def _validate_origin(self, environ):
        origin = environ.get('HTTP_ORIGIN', None)
        if not origin:
            log.debug('No Origin header found')
            return
        parsed = urlparse(origin)
        if parsed.netloc != environ.get('HTTP_HOST'):
            if not self._trusted_origin(environ, parsed):
                raise HTTPForbidden('Host and Origin do not match')
            log.info('Trusted Origin: %s://%s' % (parsed.scheme, parsed.netloc))

    def _get_credentials(self, environ):
        try:
            credentials = UserCredentials(environ, self.config['fts3.Roles'], self.config)
        except InvalidCredentials, e:
            raise HTTPForbidden('Invalid credentials (%s)' % str(e))

        if not credentials.user_dn:
            raise HTTPUnauthorized('A valid X509 certificate or proxy is needed')

        if not self._has_authorized_vo(credentials):
            raise HTTPForbidden('The user does not belong to any authorized vo')

        if self._is_banned(credentials):
            raise HTTPForbidden('The user has been banned')

        return credentials
Пример #12
0
    def __wrapper(self, func, *fargs, **fkwargs):
        controller = fargs[0]
        user = request.authuser
        loc = "%s:%s" % (controller.__class__.__name__, func.__name__)
        log.debug('Checking access for user %s @ %s', user, loc)

        if not AuthUser.check_ip_allowed(user, request.ip_addr):
            raise _redirect_to_login(_('IP %s not allowed') % request.ip_addr)

        # Check if we used an API key to authenticate.
        api_key = user.authenticating_api_key
        if api_key is not None:
            # Check that controller is enabled for API key usage.
            if not self.api_access and not allowed_api_access(loc,
                                                              api_key=api_key):
                # controller does not allow API access
                log.warning('API access to %s is not allowed', loc)
                raise HTTPForbidden()

            log.info('user %s authenticated with API key ****%s @ %s', user,
                     api_key[-4:], loc)
            return func(*fargs, **fkwargs)

        # CSRF protection: Whenever a request has ambient authority (whether
        # through a session cookie or its origin IP address), it must include
        # the correct token, unless the HTTP method is GET or HEAD (and thus
        # guaranteed to be side effect free. In practice, the only situation
        # where we allow side effects without ambient authority is when the
        # authority comes from an API key; and that is handled above.
        if request.method not in ['GET', 'HEAD']:
            token = request.POST.get(secure_form.token_key)
            if not token or token != secure_form.authentication_token():
                log.error('CSRF check failed')
                raise HTTPForbidden()

        # regular user authentication
        if user.is_authenticated or user.is_default_user:
            log.info('user %s authenticated with regular auth @ %s', user, loc)
            return func(*fargs, **fkwargs)
        else:
            log.warning('user %s NOT authenticated with regular auth @ %s',
                        user, loc)
            raise _redirect_to_login()
Пример #13
0
 def _validate_origin(self, environ):
     origin = environ.get('HTTP_ORIGIN', None)
     if not origin:
         log.debug('No Origin header found')
         return
     parsed = urlparse(origin)
     if parsed.netloc != environ.get('HTTP_HOST'):
         if not self._trusted_origin(environ, parsed):
             raise HTTPForbidden('Host and Origin do not match')
         log.info('Trusted Origin: %s://%s' % (parsed.scheme, parsed.netloc))
Пример #14
0
    def _check_security(self):
        require_authenticated()

        enable_editing = config.get('trovecategories.enableediting', 'false')
        if enable_editing == 'admin':
            with h.push_context(config.get('site_admin_project', 'allura'),
                                neighborhood=config.get('site_admin_project_nbhd', 'Projects')):
                require_access(c.project, 'admin')
        elif enable_editing != 'true':
            raise HTTPForbidden()
Пример #15
0
 def delete(self, repo_name, pull_request_id):
     pull_request = PullRequest.get_or_404(pull_request_id)
     #only owner can delete it !
     if pull_request.author.user_id == c.rhodecode_user.user_id:
         PullRequestModel().delete(pull_request)
         Session().commit()
         h.flash(_('Successfully deleted pull request'), category='success')
         return redirect(
             url('admin_settings_my_account', anchor='pullrequests'))
     raise HTTPForbidden()
Пример #16
0
 def delete_comment(self, repo_name, comment_id):
     comment = ChangesetComment.get(comment_id)
     owner = (comment.author.user_id == c.rhodecode_user.user_id)
     is_repo_admin = h.HasRepoPermissionAny('repository.admin')(c.repo_name)
     if h.HasPermissionAny('hg.admin')() or is_repo_admin or owner:
         ChangesetCommentsModel().delete(comment=comment)
         Session().commit()
         return True
     else:
         raise HTTPForbidden()
Пример #17
0
    def __call__(self, environ, start_response):
        request = Request(environ)
        self.session = environ['beaker.session']
        self.session.save()
        if self.is_valid(request):
            resp = request.get_response(self.app)
        else:
            resp = HTTPForbidden(CSRF_ERR)
            return resp(environ, start_response)
        if 'text/html' in resp.headers.get('Content-type', ''):
            token = anti_csrf.get_response_token(request, resp)

            new_response = anti_csrf.apply_token(resp.unicode_body, token)
            resp.unicode_body = new_response
            return resp(environ, start_response)

        else:
            response_value = resp(environ, start_response)
            return response_value
Пример #18
0
def auth_required(env, data, next_handler):
    if getattr(env, 'user', None) is not None:
        return next_handler(env, data)

    if (env.request.method not in ('GET', 'HEAD') or \
           env.request.is_xhr or \
           '__ajax' in env.request.GET):
        raise HTTPForbidden()
    form = LoginForm(env)
    return env.render_to_response('login.html', dict(form=form))
Пример #19
0
    def update(self, req, id, image_meta, image_data):
        """
        Updates an existing image with the registry.

        :param request: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :retval Returns the updated image information as a mapping
        """
        self._enforce(req, 'modify_image')
        if req.context.read_only:
            msg = _("Read-only access")
            logger.debug(msg)
            raise HTTPForbidden(msg, request=req,
                                content_type="text/plain")

        orig_image_meta = self.get_image_meta_or_404(req, id)
        orig_status = orig_image_meta['status']

        # The default behaviour for a PUT /images/<IMAGE_ID> is to
        # override any properties that were previously set. This, however,
        # leads to a number of issues for the common use case where a caller
        # registers an image with some properties and then almost immediately
        # uploads an image file along with some more properties. Here, we
        # check for a special header value to be false in order to force
        # properties NOT to be purged. However we also disable purging of
        # properties if an image file is being uploaded...
        purge_props = req.headers.get('x-glance-registry-purge-props', True)
        purge_props = (utils.bool_from_string(purge_props) and
                       image_data is None)

        if image_data is not None and orig_status != 'queued':
            raise HTTPConflict(_("Cannot upload to an unqueued image"))

        # Only allow the Location fields to be modified if the image is
        # in queued status, which indicates that the user called POST /images
        # but did not supply either a Location field OR image data
        if not orig_status == 'queued' and 'location' in image_meta:
            msg = _("Attempted to update Location field for an image "
                    "not in queued status.")
            raise HTTPBadRequest(msg, request=req, content_type="text/plain")

        try:
            image_meta = registry.update_image_metadata(req.context, id,
                                                        image_meta,
                                                        purge_props)
            if image_data is not None:
                image_meta = self._upload_and_activate(req, image_meta)
        except exception.Invalid, e:
            msg = (_("Failed to update image metadata. Got error: %(e)s")
                   % locals())
            for line in msg.split('\n'):
                logger.error(line)
            self.notifier.error('image.update', msg)
            raise HTTPBadRequest(msg, request=req, content_type="text/plain")
Пример #20
0
 def check_template_role_name_repetition(self, req, role_name):
     all_roles = registry.get_roles_detail(req.context)
     template_roles = [
         role for role in all_roles if role['cluster_id'] is None
     ]
     template_roles_name = [role['name'].lower() for role in template_roles]
     if role_name.lower() in template_roles_name:
         msg = _("The role %s has already been in the the template role." %
                 role_name)
         LOG.debug(msg)
         raise HTTPForbidden(msg)
Пример #21
0
    def __call__(self, environ, start_response):
        credentials = UserCredentials(environ, self.config['fts3.Roles'])

        if not credentials.user_dn:
            return HTTPForbidden(
                'A valid X509 certificate or proxy is needed')(environ,
                                                               start_response)

        if not self._hasAuthorizedVo(credentials):
            return HTTPForbidden(
                'The user does not belong to any authorized vo')(
                    environ, start_response)

        if self._isBanned(credentials):
            return HTTPForbidden('The user has been banned')(environ,
                                                             start_response)

        environ['fts3.User.Credentials'] = credentials

        return self.app(environ, start_response)
Пример #22
0
 def check_cluster_role_name_repetition(self, req, role_name, cluster_id):
     all_roles = registry.get_roles_detail(req.context)
     cluster_roles = [
         role for role in all_roles if role['cluster_id'] == cluster_id
     ]
     cluster_roles_name = [role['name'].lower() for role in cluster_roles]
     if role_name.lower() in cluster_roles_name:
         msg = _("The role %s has already been in the cluster %s!" %
                 (role_name, cluster_id))
         LOG.debug(msg)
         raise HTTPForbidden(msg)
Пример #23
0
    def _delete_comment(self, comment_id):
        comment_id = safe_int(comment_id)
        co = ChangesetComment.get_or_404(comment_id)
        if co.pull_request.is_closed():
            # don't allow deleting comments on closed pull request
            raise HTTPForbidden()

        is_owner = co.author.user_id == c.rhodecode_user.user_id
        is_repo_admin = h.HasRepoPermissionAny('repository.admin')(c.repo_name)
        if h.HasPermissionAny('hg.admin')() or is_repo_admin or is_owner:
            old_calculated_status = co.pull_request.calculated_review_status()
            ChangesetCommentsModel().delete(comment=co)
            Session().commit()
            calculated_status = co.pull_request.calculated_review_status()
            if old_calculated_status != calculated_status:
                PullRequestModel()._trigger_pull_request_hook(
                    co.pull_request, c.rhodecode_user, 'review_status_change')
            return True
        else:
            raise HTTPForbidden()
Пример #24
0
    def __call__(self, environ, start_response):
        request = Request(environ)
        self.session = environ['beaker.session']
        self.session.save()

        resp = request.get_response(
            self.app) if self.is_valid(request) else HTTPForbidden(CSRF_ERR)
        # Avoid updating the CSRF token with every static file served
        if 'text/html' in resp.headers['Content-type']:
            resp = self.add_new_token(resp)
        return resp(environ, start_response)
Пример #25
0
    def delete(self, req, id):
        """
        Deletes the image and all its chunks from the Glance

        :param req: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :raises HttpBadRequest if image registry is invalid
        :raises HttpNotFound if image or any chunk is not available
        :raises HttpNotAuthorized if image or any chunk is not
                deleteable by the requesting user
        """
        self._enforce(req, 'delete_image')
        if req.context.read_only:
            msg = _("Read-only access")
            logger.debug(msg)
            raise HTTPForbidden(msg, request=req,
                                content_type="text/plain")

        image = self.get_image_meta_or_404(req, id)
        if image['protected']:
            msg = _("Image is protected")
            logger.debug(msg)
            raise HTTPForbidden(msg, request=req,
                                content_type="text/plain")

        # The image's location field may be None in the case
        # of a saving or queued image, therefore don't ask a backend
        # to delete the image if the backend doesn't yet store it.
        # See https://bugs.launchpad.net/glance/+bug/747799
        try:
            if image['location']:
                schedule_delete_from_backend(image['location'], self.conf,
                                             req.context, id)
            registry.delete_image_metadata(req.context, id)
        except exception.NotFound, e:
            msg = ("Failed to find image to delete: %(e)s" % locals())
            for line in msg.split('\n'):
                logger.info(line)
            self.notifier.info('image.delete', msg)
            raise HTTPNotFound(msg, request=req, content_type="text/plain")
Пример #26
0
 def delete_comment(self, repo_name, comment_id):
     co = ChangesetComment.get(comment_id)
     if not co:
         raise HTTPBadRequest()
     owner = co.author.user_id == c.authuser.user_id
     repo_admin = h.HasRepoPermissionAny('repository.admin')
     if h.HasPermissionAny('hg.admin')() or repo_admin or owner:
         ChangesetCommentsModel().delete(comment=co)
         Session().commit()
         return True
     else:
         raise HTTPForbidden()
Пример #27
0
    def delete(self, gist_id):
        gist = GistModel().get_gist(gist_id)
        owner = gist.owner_id == request.authuser.user_id
        if h.HasPermissionAny('hg.admin')() or owner:
            GistModel().delete(gist)
            Session().commit()
            h.flash(_('Deleted gist %s') % gist.gist_access_id,
                    category='success')
        else:
            raise HTTPForbidden()

        raise HTTPFound(location=url('gists'))
Пример #28
0
 def delete_comment(self, repo_name, comment_id):
     co = ChangesetComment.get_or_404(comment_id)
     if co.repo.repo_name != repo_name:
         raise HTTPNotFound()
     owner = co.author_id == request.authuser.user_id
     repo_admin = h.HasRepoPermissionLevel('admin')(repo_name)
     if h.HasPermissionAny('hg.admin')() or repo_admin or owner:
         ChangesetCommentsModel().delete(comment=co)
         Session().commit()
         return True
     else:
         raise HTTPForbidden()
Пример #29
0
    def update_host_template(self, req, template_id, host_template):
        """
        Updates an existing Template with the registry.

        :param request: The WSGI/Webob Request object
        :param id: The opaque image identifier

        :retval Returns the updated image information as a mapping
        """
        self._enforce(req, 'update_host_template')
        # orig_Template_meta = self.get_Template_meta_or_404(req, id)
        '''
        if orig_Template_meta['deleted']:
            msg = _("Forbidden to update deleted Template.")
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        '''
        try:
            host_template = registry.update_host_template_metadata(
                req.context, template_id, host_template)

        except exception.Invalid as e:
            msg = (_("Failed to update template metadata. Got error: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPBadRequest(explanation=msg,
                                 request=req,
                                 content_type="text/plain")
        except exception.NotFound as e:
            msg = (_("Failed to find host_template to update: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPNotFound(explanation=msg,
                               request=req,
                               content_type="text/plain")
        except exception.Forbidden as e:
            msg = (_("Forbidden to update host_template: %s") %
                   utils.exception_to_str(e))
            LOG.warning(msg)
            raise HTTPForbidden(explanation=msg,
                                request=req,
                                content_type="text/plain")
        except (exception.Conflict, exception.Duplicate) as e:
            LOG.warning(utils.exception_to_str(e))
            raise HTTPConflict(body=_('host_template operation conflicts'),
                               request=req,
                               content_type='text/plain')
        else:
            self.notifier.info('host_template.update', host_template)

        return {'host_template': host_template}
Пример #30
0
def register_request(ticket, request_id, request):
    """
    Context manager registring a request with a ticket, so requests can be
    canceled when a ticket is revoked or expired.
    """
    requests = ticket.setdefault("requests", {})
    if request_id in requests:
        raise HTTPForbidden("Request id %r exists" % request_id)
    requests[request_id] = request
    try:
        yield
    finally:
        del requests[request_id]
Пример #31
0
def view_reset_database(self, request):
    """Restaura la base de datos a una lista de problemas y profesores de ejemplo"""
    # A pesar de la respuesta, en realidad no ha borrado nada
    # Esta respuesta es la señal para que el tween que envuelve a todas las llamadas, lo haga
    if getattr(request.app.settings, "reset_database", None) is None:
        allow = True
    else:
        allow = request.app.settings.reset_database.allow
        print("Atributo:", allow)
    if allow:
        return "OK. Base de datos restaurada"
    else:
        raise HTTPForbidden("Opción inhabilitada")
Пример #32
0
 def _check_all_lv_size_with_role_in_role_add(self, req, role_meta):
     cluster_id = role_meta.get('cluster_id', None)
     if not cluster_id:  # without cluster id, raise Error
         msg = _("The cluster_id parameter can not be None!")
         LOG.debug(msg)
         raise HTTPForbidden(msg)
     argws = dict()
     db_lv_size = role_meta.get('db_lv_size', 0)
     glance_lv_size = role_meta.get('glance_lv_size', 0)
     nova_lv_size = role_meta.get('nova_lv_size', 0)
     host_id_list = list(role_meta['nodes'])
     self._check_all_lv_size(req, db_lv_size, glance_lv_size, nova_lv_size,
                             host_id_list, cluster_id, argws)
Пример #33
0
    def __call__(self, environ, start_response):
        request = Request(environ)
        session = environ["beaker.session"]
        csrftoken = session.get("csrftoken")
        if not csrftoken:
            csrftoken = session["csrftoken"] = str(random.getrandbits(128))
            session.save()

        if request.method == "POST":
            if self.unprotected_path is not None and request.path_info.startswith(self.unprotected_path):
                resp = request.get_response(self.app)
                resp.headers["X-Frame-Options"] = "SAMEORIGIN"
                resp.set_cookie("csrftoken", csrftoken, max_age=3600)
                return resp(environ, start_response)

            # check for incoming csrf token
            try:
                request_csrf_token = environ.get("HTTP_X_CSRFTOKEN", request.POST.get("csrftoken"))
                if request_csrf_token != csrftoken:
                    resp = HTTPForbidden("CSRF - Aborted.")
                else:
                    resp = request.get_response(self.app)
            except KeyError:
                resp = HTTPForbidden("Forbidden: Administrator has been notified.")
        else:
            resp = request.get_response(self.app)

        if resp.status_int != 200:
            return resp(environ, start_response)

        resp.headers["X-Frame-Options"] = "SAMEORIGIN"
        resp.set_cookie("csrftoken", csrftoken, max_age=3600)

        if resp.content_type.split(";")[0] in ["text/html", "application/xhtml+xml"]:
            # ensure we don't add the 'id' attribute twice (HTML validity)
            id_attr = itertools.chain(('id="csrftoken"',), itertools.repeat(""))

            def add_csrf_field(match):
                """Returns the matched <form> tag and adds the <input> element"""
                return match.group() + (
                    '<input type="hidden" ' + id_attr.next() + ' name="csrftoken" value="' + csrftoken + '" />'
                )

            # Modify any POST forms and fix content-length
            body = re.compile(r"(<form\W.*)", re.IGNORECASE)
            resp.body = body.sub(add_csrf_field, resp.body)

        return resp(environ, start_response)
Пример #34
0
 def __init__(self, error_name):
     HTTPForbidden.__init__(self)
     self.explanation = error_list[error_name]