Пример #1
0
    def __init__(self, application, request, **kwargs):
        RequestHandler.__init__(self, application, request, **kwargs)

        self.name = type(self).__name__

        self.handler_time_analysis_begin()
        self.handler_request_logging_begin()

        self.req_id = GLSettings.requests_counter
        GLSettings.requests_counter += 1

        self.request.start_time = datetime_now()

        self.request.request_type = None
        if 'import' in self.request.arguments:
            self.request.request_type = 'import'
        elif 'export' in self.request.arguments:
            self.request.request_type = 'export'

        language = self.request.headers.get('GL-Language')

        if language is None:
            for l in self.parse_accept_language_header():
                if l in GLSettings.memory_copy.languages_enabled:
                    language = l
                    break

        if language is None or language not in GLSettings.memory_copy.languages_enabled:
            language = GLSettings.memory_copy.default_language

        self.request.language = language
        self.set_header("Content-Language", language)
Пример #2
0
 def write_error(self, error, **kw):
     if hasattr(error, 'http_status'):
         self.set_status(error.http_status)
         self.write({'error_message': error.error_message,
             'error_code' : error.error_code})
     else:
         RequestHandler.write_error(self, error, **kw)
Пример #3
0
    def flush(self, include_footers=False):
        """
        This method is used internally by Cyclone,
        Cyclone specify the function on_finish but in that time the request is already flushed,
        so overwrite flush() was the easiest way to achieve our collection.

        It's here implemented to supports the I/O logging if requested
        with the command line options --io $number_of_request_recorded
        """
        if hasattr(self, 'globaleaks_io_debug'):
            try:
                content = ("<" * 15)
                content += (" Response %d " % self.globaleaks_io_debug)
                content += ("<" * 15) + "\n\n"
                content += "status code: " + str(self._status_code) + "\n\n"

                content += "headers:\n"
                for k, v in self._headers.iteritems():
                    content += "%s: %s\n" % (k, v)

                if self._write_buffer is not None:
                    content += "\nbody: " + str(self._write_buffer) + "\n"

                self.do_verbose_log(content)
            except Exception as excep:
                log.err("JSON logging fail (flush): %s" % excep.message)
                return

        RequestHandler.flush(self, include_footers)
Пример #4
0
    def write(self, chunk):
        """
        This is a monkey patch to RequestHandler to allow us to serialize also
        json list objects.
        """
        if isinstance(chunk, types.ListType):
            self.set_header("Content-Type", "application/json")
            chunk = escape.json_encode(chunk)

        RequestHandler.write(self, chunk)
Пример #5
0
    def __init__(self, application, request, **kwargs):
        RequestHandler.__init__(self, application, request, **kwargs)

        self.name = type(self).__name__

        self.handler_time_analysis_begin()
        self.handler_request_logging_begin()

        self.req_id = GLSettings.requests_counter
        GLSettings.requests_counter += 1
Пример #6
0
    def __init__(self, application, request, **kwargs):
        RequestHandler.__init__(self, application, request, **kwargs)

        self.name = type(self).__name__

        self.handler_time_analysis_begin()
        self.handler_request_logging_begin()

        self.req_id = GLSettings.requests_counter
        GLSettings.requests_counter += 1

        self.request.language = GLSettings.memory_copy.default_language
        self.request.import_export = None
Пример #7
0
    def write_error(self, status_code, **kw):
        exception = kw.get("exception")
        if exception and hasattr(exception, "error_code"):
            error_dict = {"error_message": exception.reason, "error_code": exception.error_code}

            if hasattr(exception, "arguments"):
                error_dict.update({"arguments": exception.arguments})
            else:
                error_dict.update({"arguments": []})

            self.set_status(status_code)
            self.finish(error_dict)
        else:
            RequestHandler.write_error(self, status_code, **kw)
Пример #8
0
    def flush(self, include_footers=False):
        """
        This method is used internally by Cyclone,
        Cyclone specify the function on_finish but in that time the request is already flushed,
        so overwrite flush() was the easiest way to achieve our collection.

        It's here implemented to supports the I/O logging if requested
        with the command line options --io $number_of_request_recorded
        """
        from globaleaks.event import outcoming_event_monitored, EventTrack


        # This is the event tracker, used to keep track of the
        # outcome of the events.
        if not hasattr(self, '_status_code'):
            if GLSetting.devel_mode:
                log.debug("Developer, check this out")
                import pdb; pdb.set_trace()
            else:
                raise Exception("Missing _status_code in some place!")

        for event in outcoming_event_monitored:
            if event['handler_check'](self.request.uri) and \
                    event['method'] == self.request.method and \
                    event['status_checker'](self._status_code):
                EventTrack(event, self.request.request_time())
                # if event['anomaly_management']:
                #    event['anomaly_management'](self.request)

        if hasattr(self, 'globaleaks_io_debug'):
            try:
                content = ("<" * 15)
                content += (" Response %d " % self.globaleaks_io_debug)
                content += ("<" * 15) + "\n\n"
                content += "status code: " + str(self._status_code) + "\n\n"

                content += "headers:\n"
                for k, v in self._headers.iteritems():
                    content += "%s: %s\n" % (k, v)

                if self._write_buffer is not None:
                    content += "\nbody: " + str(self._write_buffer) + "\n"

                self.do_verbose_log(content)
            except Exception as excep:
                log.err("JSON logging fail (flush): %s" % excep.message)
                return

        RequestHandler.flush(self, include_footers)
Пример #9
0
    def write_error(self, status_code, **kw):
        exception = kw.get('exception')
        if exception and hasattr(exception, 'error_code'):

            error_dict = {}
            error_dict.update({'error_message': exception.reason, 'error_code': exception.error_code})
            if hasattr(exception, 'arguments'):
                error_dict.update({'arguments': exception.arguments})
            else:
                error_dict.update({'arguments': []})

            self.set_status(status_code)
            self.finish(error_dict)
        else:
            RequestHandler.write_error(self, status_code, **kw)
Пример #10
0
    def __init__(self, application, request, **kwargs):
        RequestHandler.__init__(self, application, request, **kwargs)

        self.name = type(self).__name__

        self.handler_time_analysis_begin()
        self.handler_request_logging_begin()

        self.req_id = GLSettings.requests_counter
        GLSettings.requests_counter += 1

        self.request.start_time = datetime_now()

        self.request.request_type = None
        if 'import' in self.request.arguments:
            self.request.request_type = 'import'
        elif 'export' in self.request.arguments:
            self.request.request_type = 'export'

        self.request.language = self.request.headers.get('GL-Language', GLSettings.memory_copy.default_language)
Пример #11
0
    def _handle_request_exception(self, e):
        ret = RequestHandler._handle_request_exception(self, e)

        if isinstance(e, Failure):
            exc_type, exc_value, exc_tb = [e.type, e.value, e.getTracebackObject()]
            e = e.value
        else:
            exc_type, exc_value, exc_tb = sys.exc_info()

        if not isinstance(e, (template.TemplateError,
                              HTTPError, HTTPAuthenticationRequired)):
            mail_exception_handler(exc_type, exc_value, exc_tb)

        return ret
Пример #12
0
    def _handle_request_exception(self, e):
        ret = RequestHandler._handle_request_exception(self, e)

        if isinstance(e, Failure):
            exc_type, exc_value, exc_tb = [
                e.type, e.value, e.getTracebackObject()
            ]
            e = e.value
        else:
            exc_type, exc_value, exc_tb = sys.exc_info()

        if not isinstance(
                e,
            (template.TemplateError, HTTPError, HTTPAuthenticationRequired)):
            mail_exception_handler(exc_type, exc_value, exc_tb)

        return ret
Пример #13
0
 def __init__(self, application, request, **kwargs):
     RequestHandler.__init__(self, application, request, **kwargs)
     self.transport = request.connection.transport
     self._auto_finish = False
Пример #14
0
 def __init__(self, application, request, **kwargs):
     RequestHandler.__init__(self, application, request, **kwargs)
     self.transport = request.connection.transport
     self._auto_finish = False
Пример #15
0
 def setUp(self):
     self.app = Application(some_setting="foo")
     self.request = Mock()
     self.rh = RequestHandler(self.app, self.request)
Пример #16
0
class RequestHandlerTest(unittest.TestCase):
    def assertHasAttr(self, obj, attr_name):
        assert hasattr(obj, attr_name)

    def setUp(self):
        self.app = Application(some_setting="foo")
        self.request = Mock()
        self.rh = RequestHandler(self.app, self.request)

    def test_init(self):
        self.assertHasAttr(self.rh, "application")
        self.assertHasAttr(self.rh, "request")
        self.assertHasAttr(self.rh, "path_args")
        self.assertHasAttr(self.rh, "path_kwargs")
        self.assertHasAttr(self.rh, "ui")

    def test_settings(self):
        self.assertEqual(self.rh.settings, {"some_setting": "foo"})

    def test_default(self):
        self.assertRaises(HTTPError, self.rh.default)

    def test_prepare(self):
        self.assertEqual(self.rh.prepare(), None)

    def test_on_finish(self):
        self.assertEqual(self.rh.on_finish(), None)

    def test_on_connection_close(self):
        self.assertEqual(self.rh.on_connection_close(), None)

    def test_clear(self):
        self.request.headers = {
            "Connection": "Keep-Alive"
        }
        self.request.supports_http_1_1.return_value = False
        self.rh.clear()
        self.assertEqual(
            set(self.rh._headers.keys()),
            {"Server", "Content-Type", "Date", "Connection"},
        )
        self.assertEqual(self.rh._list_headers, [])

    def test_set_status(self):
        self.rh.set_status(200)
        self.assertEqual(self.rh._status_code, 200)

    def test_set_status_with_reason(self):
        self.rh.set_status(200, "reason")
        self.assertEqual(self.rh._status_code, 200)
        self.assertEqual(self.rh._reason, "reason")

    def test_set_status_with_invalid_code(self):
        self.assertRaises(ValueError, self.rh.set_status, 9999)

    def test_get_status(self):
        self.rh.set_status(200)
        self.assertEqual(self.rh.get_status(), 200)

    def test_add_header(self):
        self.rh.add_header("X-Header", "something")
        self.assertEqual(
            self.rh._list_headers,
            [("X-Header", "something")]
        )
        self.rh.add_header("X-Header", "something")
        self.assertEqual(
            self.rh._list_headers,
            [("X-Header", "something"), ("X-Header", "something")]
        )

    def test_clear_header(self):
        self.rh.set_header("X-Header", "something")
        self.assertTrue("X-Header" in self.rh._headers)
        self.rh.clear_header("X-Header")
        self.assertTrue("X-Header" not in self.rh._headers)

    def test_convert_header_value(self):
        value = self.rh._convert_header_value("Value")
        self.assertEqual(value, "Value")

    def test_convert_unicode_header_value(self):
        value = self.rh._convert_header_value(u"Value")
        self.assertEqual(value, "Value")
        self.assertTrue(type(value) != unicode_type)

    def test_convert_unicode_datetime_header_value(self):
        now = datetime(2014, 4, 4)
        result = self.rh._convert_header_value(now)
        self.assertEqual(
            result,
            "Fri, 04 Apr 2014 00:00:00 GMT"
        )

    def test_convert_invalid_value(self):

        class Nothing:
            pass

        self.assertRaises(TypeError, self.rh._convert_header_value, Nothing())

    def test_convert_long_value(self):
        self.assertRaises(
            ValueError, self.rh._convert_header_value, "a" * 5000)

    def test_get_argument(self):
        self.rh.get_arguments = Mock()
        self.rh.get_arguments.return_value = ["a"]
        self.rh.get_argument("test")
        self.rh.get_arguments.assert_called_with("test", strip=True)
        self.rh.get_arguments.return_value = None
        self.assertEqual(
            self.rh.get_argument("arg", "something"),
            "something"
        )
        self.assertRaises(HTTPError, self.rh.get_argument, "arg")

    def test_get_arguments(self):
        self.rh.request.arguments = {"arg": ["something"]}
        val = self.rh.get_arguments("arg")
        self.assertEqual(val, ["something"])

    def test_cookies(self):
        self.rh.request.cookies = "rawr"
        self.assertEqual(self.rh.cookies, "rawr")

    def test_decode_argument(self):
        self.assertEqual(
            self.rh.decode_argument("somearg"),
            "somearg"
        )

    def test_get_cookie(self):
        morsel = Mock()
        morsel.value = "value"
        self.rh.request.cookies = {"testcookie": morsel}
        val = self.rh.get_cookie("testcookie")
        self.assertEqual(val, "value")
        val = self.rh.get_cookie("non_existent")
        self.assertEqual(val, None)

    def test_set_cookie(self):
        self.rh.set_cookie("mycookie", "cookievalue")
        self.assertEqual(
            self.rh._new_cookie["mycookie"].value,
            "cookievalue"
        )

    def test_set_invalid_cookie(self):
        self.assertRaises(
            ValueError, self.rh.set_cookie, "\x00bbb", "badcookie")

    def test_set_cookie_already_exists(self):
        self.rh._new_cookie = Cookie.SimpleCookie()
        self.rh._new_cookie["name"] = "value"
        self.rh.set_cookie("name", "value")

    def test_set_cookie_domain(self):
        self.rh.set_cookie("name", "value", domain="foo.com")
        self.assertEqual(
            self.rh._new_cookie["name"]['domain'],
            "foo.com"
        )

    def test_set_cookie_expires_days(self):
        self.rh.set_cookie("name", "value", expires_days=5, max_age=55)
        expires = self.rh._new_cookie["name"]['expires']
        self.assertTrue(
            email.utils.parsedate(expires) >
            time.gmtime(),
        )

    def test_clear_cookie(self):
        morsel = Mock()
        self.rh.request.cookies = {"testcookie": morsel}
        self.rh.set_cookie("name", "value")
        self.rh.clear_cookie("name")
        self.assertEqual(None, self.rh.get_cookie("name"))

    def test_clear_all_cookies(self):
        self.rh.clear_cookie = Mock()
        self.rh.request.cookies = {"foo": None}
        self.rh.clear_all_cookies()
        self.rh.clear_cookie.assert_called_with("foo")

    def test_redirect_too_late(self):
        self.rh._headers_written = True
        self.assertRaises(Exception, self.rh.redirect, "/")

    def test_redirect_with_perm(self):
        self.rh.flush = Mock()
        self.rh._log = Mock()
        self.rh.redirect("/", permanent=True)

    def test_redirect_with_slashes(self):
        self.rh.flush = Mock()
        self.rh._log = Mock()
        self.assertRaises(
            AssertionError,
            self.rh.redirect,
            "//example.com",
            status=400)

    def test_redirect_bad_url(self):
        self.rh.flush = Mock()
        self.rh._log = Mock()
        self.rh.request.uri = "foo"
        self.rh.redirect("http://foo.com", permanent=True)

    def test_write_when_finished(self):
        self.rh._finished = True
        self.assertRaises(RuntimeError, self.rh.write, "foo")

    def test_write_dict(self):
        self.rh.write({"foo": "bar"})
        self.assertEqual(
            self.rh._write_buffer,
            ['{"foo": "bar"}']
        )

    def test_create_template_loader(self):
        self.rh.application.settings = {"autoescape": True}
        res = self.rh.create_template_loader("/foo")
        self.assertTrue(res)

    def test_finish_already_finished(self):
        self.rh._finished = True
        self.assertRaises(RuntimeError, self.rh.finish)

    def test_finish_304_with_body(self):
        self.rh._status_code = 304
        self.rh._write_buffer = ""
        self.rh.flush = Mock()
        self.rh._log = Mock()
        self.rh.finish()

    def test_send_error(self):
        self.rh.flush = Mock()
        self.rh._log = Mock()
        self.rh.write_error = Mock()
        self.rh.send_error()
        self.rh.write_error.assert_called_with(500)

    def test_write_error(self):
        self.rh.flush = Mock()
        self.rh._log = Mock()
        self.rh.get_error_html = Mock()
        exc = [Mock(), Mock()]
        self.rh.finish = Mock()
        self.rh.write_error(500, exc_info=exc)

    def test_locale(self):
        self.request.headers = {
            "Accept-Language": "en"
        }
        self.rh.locale

    def test_get_user_locale(self):
        self.rh.get_user_locale()

    def test_get_browser_locale(self):
        self.request.headers = {
            "Accept-Language": "en"
        }
        self.rh.get_browser_locale()

    def test_current_user(self):
        self.rh.current_user

    def test_xsrf_token(self):
        self.request.cookies = {}
        self.rh.xsrf_token

    def test_check_xsrf_cookie(self):
        self.request.arguments = {self.rh.xsrf_cookie_name: "foo"}
        self.request.cookies = {}
        self.assertRaises(HTTPError, self.rh.check_xsrf_cookie)

    def test_xsrf_form_html(self):
        self.request.arguments = {self.rh.xsrf_cookie_name: "foo"}
        self.request.cookies = {}
        self.rh.xsrf_form_html()

    def test_static_url(self):
        self.rh.application.settings = {"static_path": "."}
        self.rh.static_url("/")