Esempio n. 1
0
    def _do_process(self):
        try:
            args_result = self._process_args()
            if isinstance(args_result, (current_app.response_class, Response)):
                return args_result
        except NoResultFound:  # sqlalchemy .one() not finding anything
            raise NotFound(_('The specified item could not be found.'))

        rv = self.normalize_url()
        if rv is not None:
            return rv

        self._check_access()
        if self.CHECK_HTML:
            Sanitization.sanitizationCheck(create_flat_args(),
                                           self.NOT_SANITIZED_FIELDS)

        if config.PROFILE:
            result = [None]
            profile_path = os.path.join(
                config.TEMP_DIR,
                '{}-{}.prof'.format(type(self).__name__, time.time()))
            cProfile.runctx('result[0] = self._process()', globals(), locals(),
                            profile_path)
            return result[0]
        else:
            return self._process()
Esempio n. 2
0
def process():

    responseBody = {'version': '1.1', 'error': None, 'result': None}
    requestBody = None
    try:
        # init/clear fossil cache
        clearCache()

        # read request
        try:
            requestBody = request.get_json()
            Logger.get('rpc').info(
                'json rpc request. request: {0}'.format(requestBody))
        except BadRequest:
            raise RequestError('ERR-R1', 'Invalid mime-type.')
        if not requestBody:
            raise RequestError('ERR-R2', 'Empty request.')
        if 'id' in requestBody:
            responseBody['id'] = requestBody['id']

        # run request
        responseBody['result'] = ServiceRunner().invokeMethod(
            str(requestBody['method']), requestBody.get('params', []))
    except CausedError as e:
        try:
            errorInfo = fossilize(e)
        except NonFossilizableException as e2:
            # catch Exceptions that are not registered as Fossils
            # and log them
            errorInfo = {'code': '', 'message': str(e2)}
            Logger.get('dev').exception('Exception not registered as fossil')

        # NoReport errors (i.e. not logged in) shouldn't be logged
        if not isinstance(e, NoReportError) and not getattr(
                e, '_disallow_report', False):
            Logger.get('rpc').exception(
                'Service request failed. '
                'Request text:\r\n{0}\r\n\r\n'.format(requestBody))

            if requestBody:
                params = requestBody.get('params', [])
                Sanitization._escapeHTML(params)
                errorInfo["requestInfo"] = {
                    'method': str(requestBody['method']),
                    'params': params,
                    'origin': str(requestBody.get('origin', 'unknown'))
                }
                Logger.get('rpc').debug('Arguments: {0}'.format(
                    errorInfo['requestInfo']))
        responseBody['error'] = errorInfo

    try:
        jsonResponse = dumps(responseBody, ensure_ascii=True)
    except UnicodeError:
        Logger.get('rpc').exception('Problem encoding JSON response')
        # This is to avoid exceptions due to old data encodings (based on iso-8859-1)
        responseBody['result'] = fix_broken_obj(responseBody['result'])
        jsonResponse = encode(responseBody)

    return app.response_class(jsonResponse, mimetype='application/json')
Esempio n. 3
0
    def _do_process(self, profile):
        profile_name = res = ''
        try:
            cp_result = self._process_args()
            if isinstance(cp_result, (current_app.response_class, Response)):
                return '', cp_result
        except NoResultFound:  # sqlalchemy .one() not finding anything
            raise NotFoundError(_('The specified item could not be found.'),
                                title=_('Item not found'))

        rv = self.normalize_url()
        if rv is not None:
            return '', rv

        self._check_access()
        Sanitization.sanitizationCheck(create_flat_args(),
                                       self.NOT_SANITIZED_FIELDS)

        if self._doProcess:
            if profile:
                profile_name = os.path.join(
                    config.TEMP_DIR, 'stone{}.prof'.format(random.random()))
                result = [None]
                cProfile.runctx('result[0] = self._process()', globals(),
                                locals(), profile_name)
                res = result[0]
            else:
                res = self._process()
        return profile_name, res
Esempio n. 4
0
    def process(self):
        """
        Processes the request, analyzing the parameters, and feeding them to the
        _getAnswer() method (implemented by derived classes)
        """

        g.rh = self
        sentry_set_tags({'rh': self.__class__.__name__})

        self._process_args()
        self._check_access()

        if self.CHECK_HTML:
            Sanitization.sanitizationCheck(self._params)
        return self._getAnswer()
Esempio n. 5
0
    def process(self):
        """
        Processes the request, analyzing the parameters, and feeding them to the
        _getAnswer() method (implemented by derived classes)
        """

        g.rh = self
        sentry_set_tags({'rh': self.__class__.__name__})

        self._process_args()
        self._check_access()

        if self.CHECK_HTML:
            Sanitization.sanitizationCheck(self._params)
        return self._getAnswer()
Esempio n. 6
0
    def _do_process(self, profile):
        profile_name = res = ''
        try:
            # old code gets parameters from call
            # new code utilizes of flask.request
            if len(inspect.getargspec(self._checkParams).args) < 2:
                cp_result = self._checkParams()
            else:
                cp_result = self._checkParams(self._reqParams)

            if isinstance(cp_result, (current_app.response_class, Response)):
                return '', cp_result

            func = getattr(self, '_checkParams_' + request.method, None)
            if func:
                cp_result = func()
                if isinstance(cp_result,
                              (current_app.response_class, Response)):
                    return '', cp_result

        except NoResultFound:  # sqlalchemy .one() not finding anything
            raise NotFoundError(_('The specified item could not be found.'),
                                title=_('Item not found'))

        rv = self.normalize_url()
        if rv is not None:
            return '', rv

        self._checkProtection()
        func = getattr(self, '_checkProtection_' + request.method, None)
        if func:
            func()

        Sanitization.sanitizationCheck(self._target, self._reqParams, self._aw,
                                       self._doNotSanitizeFields)

        if self._doProcess:
            if profile:
                profile_name = os.path.join(
                    Config.getInstance().getTempDir(),
                    'stone{}.prof'.format(random.random()))
                result = [None]
                cProfile.runctx('result[0] = self._process()', globals(),
                                locals(), profile_name)
                res = result[0]
            else:
                res = self._process()
        return profile_name, res
Esempio n. 7
0
    def _do_process(self):
        try:
            args_result = self._process_args()
            signals.rh.process_args.send(type(self), rh=self, result=args_result)
            if isinstance(args_result, (current_app.response_class, Response)):
                return args_result
        except NoResultFound:  # sqlalchemy .one() not finding anything
            raise NotFound(_('The specified item could not be found.'))

        rv = self.normalize_url()
        if rv is not None:
            return rv

        self._check_access()
        signals.rh.check_access.send(type(self), rh=self)
        if self.CHECK_HTML:
            Sanitization.sanitizationCheck(create_flat_args(), self.NOT_SANITIZED_FIELDS)

        signal_rv = values_from_signal(signals.rh.before_process.send(type(self), rh=self),
                                       single_value=True, as_list=True)
        if signal_rv and len(signal_rv) != 1:
            raise Exception('More than one signal handler returned custom RH result')
        elif signal_rv:
            return signal_rv[0]

        if config.PROFILE:
            result = [None]
            profile_path = os.path.join(config.TEMP_DIR, '{}-{}.prof'.format(type(self).__name__, time.time()))
            cProfile.runctx('result[0] = self._process()', globals(), locals(), profile_path)
            rv = result[0]
        else:
            rv = self._process()

        signal_rv = values_from_signal(signals.rh.process.send(type(self), rh=self, result=rv),
                                       single_value=True, as_list=True)
        if signal_rv and len(signal_rv) != 1:
            raise Exception('More than one signal handler returned new RH result')
        elif signal_rv:
            return signal_rv[0]
        else:
            return rv
Esempio n. 8
0
    def _do_process(self):
        try:
            args_result = self._process_args()
            if isinstance(args_result, (current_app.response_class, Response)):
                return args_result
        except NoResultFound:  # sqlalchemy .one() not finding anything
            raise NotFound(_('The specified item could not be found.'))

        rv = self.normalize_url()
        if rv is not None:
            return rv

        self._check_access()
        if self.CHECK_HTML:
            Sanitization.sanitizationCheck(create_flat_args(), self.NOT_SANITIZED_FIELDS)

        if config.PROFILE:
            result = [None]
            profile_path = os.path.join(config.TEMP_DIR, '{}-{}.prof'.format(type(self).__name__, time.time()))
            cProfile.runctx('result[0] = self._process()', globals(), locals(), profile_path)
            return result[0]
        else:
            return self._process()