Example #1
0
    def test_handle_request_method_raise_delugeerror(self):
        json = JSON()

        def get_session_id(s_id):
            return s_id

        self.patch(deluge.ui.web.auth, 'get_session_id', get_session_id)
        auth_conf = {'session_timeout': 10, 'sessions': {}}
        auth = Auth(auth_conf)
        request = Request(MagicMock(), False)
        request.base = ''
        auth._create_session(request)
        methods = yield json.get_remote_methods()
        # Verify the function has been registered
        self.assertTrue('testclass.test' in methods)

        request = MagicMock()
        request.getCookie = MagicMock(return_value=list(auth.config['sessions'])[0])
        json_data = {'method': 'testclass.test', 'id': 0, 'params': []}
        request.json = json_lib.dumps(json_data)
        request_id, result, error = json._handle_request(request)
        result.addCallback(self.fail)

        def on_error(error):
            self.assertEqual(error.type, DelugeError)

        result.addErrback(on_error)
        yield result
Example #2
0
    def __init__(self, options=None, daemon=True):
        """
        Setup the DelugeWeb server.

        Args:
            options (argparse.Namespace): The web server options.
            daemon (bool): If True run web server as a separate daemon process (starts a twisted
                reactor). If False shares the process and twisted reactor from WebUI plugin or tests.

        """
        component.Component.__init__(self, 'DelugeWeb', depend=['Web'])
        self.config = configmanager.ConfigManager(
            'web.conf', defaults=CONFIG_DEFAULTS, file_version=2
        )
        self.config.run_converter((0, 1), 2, self._migrate_config_1_to_2)
        self.config.register_set_function('language', self._on_language_changed)
        self.socket = None
        self.top_level = TopLevel()

        self.interface = self.config['interface']
        self.port = self.config['port']
        self.https = self.config['https']
        self.pkey = self.config['pkey']
        self.cert = self.config['cert']
        self.base = self.config['base']

        if options:
            self.interface = (
                options.interface if options.interface is not None else self.interface
            )
            self.port = options.port if options.port else self.port
            self.base = options.base if options.base else self.base
            if options.ssl:
                self.https = True
            elif options.no_ssl:
                self.https = False

        if self.base != '/':
            # Strip away slashes and serve on the base path as well as root path
            self.top_level.putChild(self.base.strip('/'), self.top_level)

        setup_translation()

        # Remove twisted version number from 'server' http-header for security reasons
        server.version = 'TwistedWeb'
        self.site = server.Site(self.top_level)
        self.web_api = WebApi()
        self.web_utils = WebUtils()

        self.auth = Auth(self.config)
        self.daemon = daemon
        # Initialize the plugins
        self.plugins = PluginManager()
Example #3
0
    def test_handle_request_auth_error(self):
        yield self.connect_client()
        json = JSON()
        auth_conf = {'session_timeout': 10, 'sessions': {}}
        Auth(auth_conf)  # Must create the component

        # Must be called to update remote methods in json object
        yield json.get_remote_methods()

        request = MagicMock()
        request.getCookie = MagicMock(return_value='bad_value')
        json_data = {'method': 'core.get_libtorrent_version', 'id': 0, 'params': []}
        request.json = json_lib.dumps(json_data)
        request_id, result, error = json._handle_request(request)
        self.assertEqual(error, {'message': 'Not authenticated', 'code': 1})
Example #4
0
    def __init__(self):
        super(DelugeWeb, self).__init__("DelugeWeb")
        self.config = configmanager.ConfigManager("web.conf", CONFIG_DEFAULTS)

        # Check to see if a configuration from the web interface prior to 1.2
        # exists and convert it over.
        if os.path.exists(configmanager.get_config_dir("webui06.conf")):
            old_config = configmanager.ConfigManager("webui06.conf")
            if old_config.config:
                # we have an old config file here to handle so we should move
                # all the values across to the new config file, and then remove
                # it.
                for key in OLD_CONFIG_KEYS:
                    if key in old_config:
                        self.config[key] = old_config[key]

                # We need to base64 encode the passwords since json can't handle
                # them otherwise.
                from base64 import encodestring
                self.config["old_pwd_md5"] = encodestring(
                    old_config["pwd_md5"])
                self.config["old_pwd_salt"] = encodestring(
                    old_config["pwd_salt"])

                # Save our config and if it saved successfully then rename the
                # old configuration file.
                if self.config.save():
                    config_dir = os.path.dirname(old_config.config_file)
                    backup_path = os.path.join(config_dir, 'web.conf.old')
                    os.rename(old_config.config_file, backup_path)
                    del old_config

        self.socket = None
        self.top_level = TopLevel()
        self.site = server.Site(self.top_level)
        self.interface = self.config["interface"]
        self.port = self.config["port"]
        self.https = self.config["https"]
        self.pkey = self.config["pkey"]
        self.cert = self.config["cert"]
        self.base = self.config["base"]
        self.web_api = WebApi()
        self.auth = Auth()

        # Initalize the plugins
        self.plugins = PluginManager()
Example #5
0
    def test_render_on_rpc_request_failed(self):
        json = JSON()

        methods = yield json.get_remote_methods()
        # Verify the function has been registered
        self.assertTrue('testclass.test' in methods)

        request = MagicMock()

        # Circumvent authentication
        auth = Auth({})
        self.mock_authentication_ignore(auth)
        self.mock_compress_body()

        def write(response_str):
            request.write_was_called = True
            response = json_lib.loads(response_str)
            self.assertEqual(response['result'], None, 'BAD RESULT')
            self.assertEqual(response['id'], 0)
            self.assertEqual(
                response['error']['message'],
                'Failure: [Failure instance: Traceback (failure with no frames):'
                " <class 'deluge.error.DelugeError'>: DelugeERROR\n]",
            )
            self.assertEqual(response['error']['code'], 4)

        request.write = write
        request.write_was_called = False
        request._disconnected = False
        request.getHeader.return_value = 'application/json'
        json_data = {'method': 'testclass.test', 'id': 0, 'params': []}
        request.json = json_lib.dumps(json_data)
        d = json._on_json_request(request)

        def on_success(arg):
            self.assertEqual(arg, server.NOT_DONE_YET)
            return True

        d.addCallbacks(on_success, self.fail)
        yield d