def setUpClass(cls):
        """
        Sets up this TestCase with a simple and faked provider instance:

        * runs a threaded reactor
        * loads a mocked ProviderConfig that points to the certs in the
          leap.common.testing module.
        """
        factory = fake_provider.get_provider_factory()
        http = reactor.listenTCP(8001, factory)
        https = reactor.listenSSL(0, factory,
                                  fake_provider.OpenSSLServerContextFactory())
        get_port = lambda p: p.getHost().port
        cls.http_port = get_port(http)
        cls.https_port = get_port(https)

        provider = ProviderConfig()
        provider.get_ca_cert_path = MagicMock()
        provider.get_ca_cert_path.return_value = _get_capath()

        provider.get_api_uri = MagicMock()
        provider.get_api_uri.return_value = cls._get_https_uri()

        loaded = provider.load(path=os.path.join(_here, "test_provider.json"))
        if not loaded:
            raise ImproperlyConfiguredError(
                "Could not load test provider config")
        cls.register = srpregister.SRPRegister(provider_config=provider)

        cls.auth = srpauth.SRPAuth(provider)
    def test_correct_http_uri(self):
        """
        Checks that registration autocorrect http uris to https ones.
        """
        HTTP_URI = "http://localhost:%s" % (self.https_port, )
        HTTPS_URI = "https://localhost:%s/1/users" % (self.https_port, )
        provider = ProviderConfig()
        provider.get_ca_cert_path = MagicMock()
        provider.get_ca_cert_path.return_value = _get_capath()
        provider.get_api_uri = MagicMock()

        # we introduce a http uri in the config file...
        provider.get_api_uri.return_value = HTTP_URI
        loaded = provider.load(path=os.path.join(_here, "test_provider.json"))
        if not loaded:
            raise ImproperlyConfiguredError(
                "Could not load test provider config")

        register = srpregister.SRPRegister(provider_config=provider)

        # ... and we check that we're correctly taking the HTTPS protocol
        # instead
        reg_uri = register._get_registration_uri()
        self.assertEquals(reg_uri, HTTPS_URI)
        register._get_registration_uri = MagicMock(return_value=HTTPS_URI)
        d = threads.deferToThread(register.register_user, "test_failhttp",
                                  "barpass")
        d.addCallback(self.assertTrue)

        return d
Ejemplo n.º 3
0
    def test_correct_http_uri(self):
        """
        Checks that registration autocorrect http uris to https ones.
        """
        HTTP_URI = "http://localhost:%s" % (self.https_port, )
        HTTPS_URI = "https://localhost:%s/1/users" % (self.https_port, )
        provider = ProviderConfig()
        provider.get_ca_cert_path = MagicMock()
        provider.get_ca_cert_path.return_value = _get_capath()
        provider.get_api_uri = MagicMock()

        # we introduce a http uri in the config file...
        provider.get_api_uri.return_value = HTTP_URI
        loaded = provider.load(path=os.path.join(
            _here, "test_provider.json"))
        if not loaded:
            raise ImproperlyConfiguredError(
                "Could not load test provider config")

        register = srpregister.SRPRegister(provider_config=provider)

        # ... and we check that we're correctly taking the HTTPS protocol
        # instead
        reg_uri = register._get_registration_uri()
        self.assertEquals(reg_uri, HTTPS_URI)
        register._get_registration_uri = MagicMock(return_value=HTTPS_URI)
        d = threads.deferToThread(register.register_user, "test_failhttp",
                                  "barpass")
        d.addCallback(self.assertTrue)

        return d
Ejemplo n.º 4
0
    def setUpClass(cls):
        """
        Sets up this TestCase with a simple and faked provider instance:

        * runs a threaded reactor
        * loads a mocked ProviderConfig that points to the certs in the
          leap.common.testing module.
        """
        factory = fake_provider.get_provider_factory()
        http = reactor.listenTCP(8001, factory)
        https = reactor.listenSSL(
            0, factory,
            fake_provider.OpenSSLServerContextFactory())
        get_port = lambda p: p.getHost().port
        cls.http_port = get_port(http)
        cls.https_port = get_port(https)

        provider = ProviderConfig()
        provider.get_ca_cert_path = MagicMock()
        provider.get_ca_cert_path.return_value = _get_capath()

        provider.get_api_uri = MagicMock()
        provider.get_api_uri.return_value = cls._get_https_uri()

        loaded = provider.load(path=os.path.join(
            _here, "test_provider.json"))
        if not loaded:
            raise ImproperlyConfiguredError(
                "Could not load test provider config")
        cls.register = srpregister.SRPRegister(provider_config=provider)

        cls.auth = srpauth.SRPAuth(provider)
Ejemplo n.º 5
0
    def __init__(self, userid, passwd, mdir=None):
        """
        Initialize the plumber with all that's needed to authenticate
        against the provider.

        :param userid: user identifier, foo@bar
        :type userid: basestring
        :param passwd: the soledad passphrase
        :type passwd: basestring
        :param mdir: a path to a maildir to import
        :type mdir: str or None
        """
        self.userid = userid
        self.passwd = passwd
        user, provider = userid.split('@')
        self.user = user
        self.mdir = mdir
        self.sol = None
        self._settings = Settings()

        provider_config_path = os.path.join(get_path_prefix(),
                                            get_provider_path(provider))
        provider_config = ProviderConfig()
        loaded = provider_config.load(provider_config_path)
        if not loaded:
            print "could not load provider config!"
            return self.exit()
Ejemplo n.º 6
0
    def __init__(self, userid, passwd, mdir=None):
        """
        Initialize the plumber with all that's needed to authenticate
        against the provider.

        :param userid: user identifier, foo@bar
        :type userid: basestring
        :param passwd: the soledad passphrase
        :type passwd: basestring
        :param mdir: a path to a maildir to import
        :type mdir: str or None
        """
        self.userid = userid
        self.passwd = passwd
        user, provider = userid.split('@')
        self.user = user
        self.mdir = mdir
        self.sol = None
        self._settings = Settings()

        provider_config_path = os.path.join(get_path_prefix(),
                                            get_provider_path(provider))
        provider_config = ProviderConfig()
        loaded = provider_config.load(provider_config_path)
        if not loaded:
            print "could not load provider config!"
            return self.exit()
Ejemplo n.º 7
0
    def test_get_client_cert_path_fails(self):
        config = self._get_eipconfig()
        provider_config = ProviderConfig()

        # mock 'get_domain' so we don't need to load a config
        provider_domain = 'test.provider.com'
        provider_config.get_domain = Mock(return_value=provider_domain)

        with self.assertRaises(AssertionError):
            config.get_client_cert_path(provider_config)
Ejemplo n.º 8
0
    def test_get_client_cert_path_fails(self):
        config = self._get_eipconfig()
        provider_config = ProviderConfig()

        # mock 'get_domain' so we don't need to load a config
        provider_domain = 'test.provider.com'
        provider_config.get_domain = Mock(return_value=provider_domain)

        with self.assertRaises(AssertionError):
            config.get_client_cert_path(provider_config)
Ejemplo n.º 9
0
    def setUp(self):
        """
        Sets up this TestCase with a simple and faked provider instance:

        * runs a threaded reactor
        * loads a mocked ProviderConfig that points to the certs in the
          leap.common.testing module.
        """
        factory = fake_provider.get_provider_factory()
        http = reactor.listenTCP(0, factory)
        https = reactor.listenSSL(0, factory,
                                  fake_provider.OpenSSLServerContextFactory())
        get_port = lambda p: p.getHost().port
        self.http_port = get_port(http)
        self.https_port = get_port(https)

        provider = ProviderConfig()
        provider.get_ca_cert_path = mock.create_autospec(
            provider.get_ca_cert_path)
        provider.get_ca_cert_path.return_value = _get_capath()

        provider.get_api_uri = mock.create_autospec(provider.get_api_uri)
        provider.get_api_uri.return_value = self._get_https_uri()

        loaded = provider.load(path=os.path.join(_here, "test_provider.json"))
        if not loaded:
            raise ImproperlyConfiguredError(
                "Could not load test provider config")
        self.register = srpregister.SRPRegister(provider_config=provider)
        self.provider = provider
        self.TEST_USER = "******"
        self.TEST_PASS = "******"

        # Reset the singleton
        srpauth.SRPAuth._SRPAuth__instance = None
        self.auth = srpauth.SRPAuth(self.provider)
        self.auth_backend = self.auth._SRPAuth__instance

        self.old_post = self.auth_backend._session.post
        self.old_put = self.auth_backend._session.put
        self.old_delete = self.auth_backend._session.delete

        self.old_start_auth = self.auth_backend._start_authentication
        self.old_proc_challenge = self.auth_backend._process_challenge
        self.old_extract_data = self.auth_backend._extract_data
        self.old_verify_session = self.auth_backend._verify_session
        self.old_auth_preproc = self.auth_backend._authentication_preprocessing
        self.old_get_sid = self.auth_backend.get_session_id
        self.old_cookie_get = self.auth_backend._session.cookies.get
        self.old_auth = self.auth_backend.authenticate

        # HACK: this is needed since it seems that the backend settings path is
        # not using the right path
        mkdir_p('config/leap')
    def test_none_port(self):
        provider = ProviderConfig()
        provider.get_api_uri = MagicMock()
        provider.get_api_uri.return_value = "http://localhost/"
        loaded = provider.load(path=os.path.join(_here, "test_provider.json"))
        if not loaded:
            raise ImproperlyConfiguredError(
                "Could not load test provider config")

        register = srpregister.SRPRegister(provider_config=provider)
        self.assertEquals(register._port, "443")
Ejemplo n.º 11
0
    def setUp(self):
        self._provider_config = ProviderConfig()
        json_string = json.dumps(sample_config)
        self._provider_config.load(data=json_string)

        # At certain points we are going to be replacing these method
        # to avoid creating a file.
        # We need to save the old implementation and restore it in
        # tearDown so we are sure everything is as expected for each
        # test. If we do it inside each specific test, a failure in
        # the test will leave the implementation with the mock.
        self._old_ospath_exists = os.path.exists
Ejemplo n.º 12
0
    def setUp(self):
        """
        Sets up this TestCase with a simple and faked provider instance:

        * runs a threaded reactor
        * loads a mocked ProviderConfig that points to the certs in the
          leap.common.testing module.
        """
        factory = fake_provider.get_provider_factory()
        http = reactor.listenTCP(0, factory)
        https = reactor.listenSSL(
            0, factory,
            fake_provider.OpenSSLServerContextFactory())
        get_port = lambda p: p.getHost().port
        self.http_port = get_port(http)
        self.https_port = get_port(https)

        provider = ProviderConfig()
        provider.get_ca_cert_path = mock.create_autospec(
            provider.get_ca_cert_path)
        provider.get_ca_cert_path.return_value = _get_capath()

        provider.get_api_uri = mock.create_autospec(
            provider.get_api_uri)
        provider.get_api_uri.return_value = self._get_https_uri()

        loaded = provider.load(path=os.path.join(
            _here, "test_provider.json"))
        if not loaded:
            raise ImproperlyConfiguredError(
                "Could not load test provider config")
        self.register = srpregister.SRPRegister(provider_config=provider)
        self.provider = provider
        self.TEST_USER = "******"
        self.TEST_PASS = "******"

        # Reset the singleton
        srpauth.SRPAuth._SRPAuth__instance = None
        self.auth = srpauth.SRPAuth(self.provider)
        self.auth_backend = self.auth._SRPAuth__instance

        self.old_post = self.auth_backend._session.post
        self.old_put = self.auth_backend._session.put
        self.old_delete = self.auth_backend._session.delete

        self.old_start_auth = self.auth_backend._start_authentication
        self.old_proc_challenge = self.auth_backend._process_challenge
        self.old_extract_data = self.auth_backend._extract_data
        self.old_verify_session = self.auth_backend._verify_session
        self.old_auth_preproc = self.auth_backend._authentication_preprocessing
        self.old_get_sid = self.auth_backend.get_session_id
        self.old_cookie_get = self.auth_backend._session.cookies.get
        self.old_auth = self.auth_backend.authenticate
Ejemplo n.º 13
0
    def test_none_port(self):
        provider = ProviderConfig()
        provider.get_api_uri = MagicMock()
        provider.get_api_uri.return_value = "http://localhost/"
        loaded = provider.load(path=os.path.join(
            _here, "test_provider.json"))
        if not loaded:
            raise ImproperlyConfiguredError(
                "Could not load test provider config")

        register = srpregister.SRPRegister(provider_config=provider)
        self.assertEquals(register._port, "443")
Ejemplo n.º 14
0
class Register(object):
    """
    Interfaces with setup and bootstrapping operations for a provider
    """

    zope.interface.implements(ILEAPComponent)

    def __init__(self, signaler=None):
        """
        Constructor for the Register component

        :param signaler: Object in charge of handling communication
                         back to the frontend
        :type signaler: Signaler
        """
        object.__init__(self)
        self.key = "register"
        self._signaler = signaler
        self._provider_config = ProviderConfig()

    def register_user(self, domain, username, password):
        """
        Register a user using the domain and password given as parameters.

        :param domain: the domain we need to register the user.
        :type domain: unicode
        :param username: the user name
        :type username: unicode
        :param password: the password for the username
        :type password: unicode

        :returns: the defer for the operation running in a thread.
        :rtype: twisted.internet.defer.Deferred
        """
        # If there's no loaded provider or
        # we want to connect to other provider...
        if (not self._provider_config.loaded() or
                self._provider_config.get_domain() != domain):
            self._provider_config.load(get_provider_path(domain))

        if self._provider_config.loaded():
            srpregister = SRPRegister(signaler=self._signaler,
                                      provider_config=self._provider_config)
            return threads.deferToThread(
                partial(srpregister.register_user, username, password))
        else:
            if self._signaler is not None:
                self._signaler.signal(self._signaler.srp_registration_failed)
            logger.error("Could not load provider configuration.")
Ejemplo n.º 15
0
    def test_get_client_cert_path_about_to_download(self):
        config = self._get_eipconfig()
        provider_config = ProviderConfig()

        # mock 'get_domain' so we don't need to load a config
        provider_domain = 'test.provider.com'
        provider_config.get_domain = Mock(return_value=provider_domain)

        expected_path = os.path.join('leap', 'providers', provider_domain,
                                     'keys', 'client', 'openvpn.pem')

        cert_path = config.get_client_cert_path(provider_config,
                                                about_to_download=True)

        self.assertTrue(cert_path.endswith(expected_path))
Ejemplo n.º 16
0
    def __init__(self, signaler=None):
        """
        Constructor for the EIP component

        :param signaler: Object in charge of handling communication
                         back to the frontend
        :type signaler: Signaler
        """
        self.key = "eip"
        self._signaler = signaler
        self._eip_bootstrapper = EIPBootstrapper(signaler)
        self._eip_setup_defer = None
        self._provider_config = ProviderConfig()

        self._vpn = vpnprocess.VPN(signaler=signaler)
Ejemplo n.º 17
0
    def bootstrap(self, username, domain, password):
        """
        Bootstrap Soledad with the user credentials.

        Signals:
            soledad_download_config
            soledad_gen_key

        :param user: user's login
        :type user: unicode
        :param domain: the domain that we are using.
        :type domain: unicode
        :param password: user's password
        :type password: unicode
        """
        provider_config = ProviderConfig.get_provider_config(domain)
        if provider_config is not None:
            self._soledad_defer = threads.deferToThread(
                self._soledad_bootstrapper.run_soledad_setup_checks,
                provider_config, username, password,
                download_if_needed=True)
            self._soledad_defer.addCallback(self._set_proxies_cb)
        else:
            if self._signaler is not None:
                self._signaler.signal(self._signaler.SOLEDAD_BOOTSTRAP_FAILED)
            logger.error("Could not load provider configuration.")

        return self._soledad_defer
Ejemplo n.º 18
0
    def bootstrap(self, username, domain, password):
        """
        Bootstrap Soledad with the user credentials.

        Signals:
            soledad_download_config
            soledad_gen_key

        :param user: user's login
        :type user: unicode
        :param domain: the domain that we are using.
        :type domain: unicode
        :param password: user's password
        :type password: unicode
        """
        provider_config = ProviderConfig.get_provider_config(domain)
        if provider_config is not None:
            sb = self._soledad_bootstrapper
            self._soledad_defer = sb.run_soledad_setup_checks(
                provider_config, username, password, download_if_needed=True)
            self._soledad_defer.addCallback(self._set_proxies_cb)
        else:
            if self._signaler is not None:
                self._signaler.signal(self._signaler.soledad_bootstrap_failed)
            logger.error("Could not load provider configuration.")

        return self._soledad_defer
Ejemplo n.º 19
0
    def start_smtp_service(self, keymanager, userid, download_if_needed=False):
        """
        Starts the SMTP service.

        :param keymanager: a transparent proxy that eventually will point to a
                           Keymanager Instance.
        :type keymanager: zope.proxy.ProxyBase
        :param userid: the user id, in the form "user@provider"
        :type userid: str
        :param download_if_needed: True if it should check for mtime
                                   for the file
        :type download_if_needed: bool
        """
        try:
            username, domain = userid.split('@')
        except ValueError:
            logger.critical("Malformed userid parameter!")
            raise MalformedUserId()

        self._provider_config = ProviderConfig.get_provider_config(domain)
        self._keymanager = keymanager
        self._smtp_config = SMTPConfig()
        self._userid = userid
        self._download_if_needed = download_if_needed

        try:
            self._download_config_and_cert()
            logger.debug("Starting SMTP service.")
            self._start_smtp_service()
        except NoSMTPHosts:
            logger.warning("There is no SMTP host to use.")
        except Exception as e:
            # TODO: we should handle more specific exceptions in here
            logger.exception("Error while bootstrapping SMTP: %r" % (e, ))
Ejemplo n.º 20
0
    def run_provider_select_checks(self, domain, download_if_needed=False):
        """
        Populates the check queue.

        :param domain: domain to check
        :type domain: unicode

        :param download_if_needed: if True, makes the checks do not
                                   overwrite already downloaded data
        :type download_if_needed: bool
        """
        leap_assert(domain and len(domain) > 0, "We need a domain!")

        self._domain = ProviderConfig.sanitize_path_component(domain)
        self._download_if_needed = download_if_needed

        cb_chain = [
            (self._check_name_resolution,
             self._signaler.prov_name_resolution),
            (self._check_https, self._signaler.prov_https_connection),
            (self._download_provider_info,
             self._signaler.prov_download_provider_info)
        ]

        return self.addCallbackChain(cb_chain)
Ejemplo n.º 21
0
    def test_get_client_cert_path_about_to_download(self):
        config = self._get_eipconfig()
        provider_config = ProviderConfig()

        # mock 'get_domain' so we don't need to load a config
        provider_domain = 'test.provider.com'
        provider_config.get_domain = Mock(return_value=provider_domain)

        expected_path = os.path.join('leap', 'providers',
                                     provider_domain, 'keys', 'client',
                                     'openvpn.pem')

        cert_path = config.get_client_cert_path(
            provider_config, about_to_download=True)

        self.assertTrue(cert_path.endswith(expected_path))
Ejemplo n.º 22
0
    def _populate_gateways(self, domain):
        """
        SLOT
        TRIGGERS:
            self.ui.cbProvidersGateway.currentIndexChanged[unicode]

        Loads the gateways that the provider provides into the UI for
        the user to select.

        :param domain: the domain of the provider to load gateways from.
        :type domain: str
        """
        # We hide the maybe-visible status label after a change
        self.ui.lblProvidersGatewayStatus.setVisible(False)

        if not domain:
            return

        try:
            # disconnect previously connected save method
            self.ui.pbSaveGateway.clicked.disconnect()
        except RuntimeError:
            pass  # Signal was not connected

        # set the proper connection for the 'save' button
        save_gateway = partial(self._save_selected_gateway, domain)
        self.ui.pbSaveGateway.clicked.connect(save_gateway)

        eip_config = EIPConfig()
        provider_config = ProviderConfig.get_provider_config(domain)

        eip_config_path = os.path.join("leap", "providers",
                                       domain, "eip-service.json")
        api_version = provider_config.get_api_version()
        eip_config.set_api_version(api_version)
        eip_loaded = eip_config.load(eip_config_path)

        if not eip_loaded or provider_config is None:
            self._set_providers_gateway_status(
                self.tr("There was a problem with configuration files."),
                error=True)
            return

        gateways = VPNGatewaySelector(eip_config).get_gateways_list()
        logger.debug(gateways)

        self.ui.cbGateways.clear()
        self.ui.cbGateways.addItem(self.AUTOMATIC_GATEWAY_LABEL)

        # Add the available gateways and
        # select the one stored in configuration file.
        selected_gateway = self._settings.get_selected_gateway(domain)
        index = 0
        for idx, (gw_name, gw_ip) in enumerate(gateways):
            gateway = "{0} ({1})".format(gw_name, gw_ip)
            self.ui.cbGateways.addItem(gateway, gw_ip)
            if gw_ip == selected_gateway:
                index = idx + 1

        self.ui.cbGateways.setCurrentIndex(index)
Ejemplo n.º 23
0
    def setup_eip(self, domain, skip_network=False):
        """
        Initiate the setup for a provider

        :param domain: URL for the provider
        :type domain: unicode
        :param skip_network: Whether checks that involve network should be done
                             or not
        :type skip_network: bool

        :returns: the defer for the operation running in a thread.
        :rtype: twisted.internet.defer.Deferred
        """
        config = ProviderConfig.get_provider_config(domain)
        self._provider_config = config
        if config is not None:
            if skip_network:
                return defer.Deferred()
            eb = self._eip_bootstrapper
            d = eb.run_eip_setup_checks(self._provider_config,
                                        download_if_needed=True)
            self._eip_setup_defer = d
            return d
        else:
            raise Exception("No provider setup loaded")
Ejemplo n.º 24
0
    def register_user(self, domain, username, password):
        """
        Register a user using the domain and password given as parameters.

        :param domain: the domain we need to register the user.
        :type domain: unicode
        :param username: the user name
        :type username: unicode
        :param password: the password for the username
        :type password: unicode

        :returns: the defer for the operation running in a thread.
        :rtype: twisted.internet.defer.Deferred
        """
        config = ProviderConfig.get_provider_config(domain)
        self._provider_config = config
        if config is not None:
            srpregister = SRPRegister(signaler=self._signaler,
                                      provider_config=config)
            return threads.deferToThread(
                partial(srpregister.register_user, username, password))
        else:
            if self._signaler is not None:
                self._signaler.signal(self._signaler.srp_registration_failed)
            logger.error("Could not load provider configuration.")
Ejemplo n.º 25
0
    def nextId(self):
        """
        Sets the next page id for the wizard based on wether the user
        wants to register a new identity or uses an existing one
        """
        if self.currentPage() == self.page(self.INTRO_PAGE):
            self._show_register = self.ui.rdoRegister.isChecked()

        if self.currentPage() == self.page(self.SETUP_PROVIDER_PAGE):
            if self._show_register:
                return self.REGISTER_USER_PAGE
            else:
                return self.SERVICES_PAGE

        if self.currentPage() == self.page(self.SELECT_PROVIDER_PAGE):
            if self._use_existing_provider:
                self._domain = self.ui.cbProviders.currentText()
                self._provider_config = ProviderConfig.get_provider_config(
                    self._domain)
                if self._show_register:
                    return self.REGISTER_USER_PAGE
                else:
                    return self.SERVICES_PAGE

        return QtGui.QWizard.nextId(self)
Ejemplo n.º 26
0
    def bootstrap(self, provider):
        """
        Second stage of bootstrapping for a provider.

        :param provider: URL for the provider
        :type provider: unicode

        :returns: the defer for the operation running in a thread.
        :rtype: twisted.internet.defer.Deferred
        """
        d = None

        config = ProviderConfig.get_provider_config(provider)
        self._provider_config = config
        if config is not None:
            d = self._provider_bootstrapper.run_provider_setup_checks(
                config, download_if_needed=True)
        else:
            if self._signaler is not None:
                self._signaler.signal(
                    self._signaler.prov_problem_with_provider)
            logger.error("Could not load provider configuration.")
            self._login_widget.set_enabled(True)

        if d is None:
            d = defer.Deferred()
        return d
Ejemplo n.º 27
0
    def test_wrong_cert(self):
        provider = ProviderConfig()
        loaded = provider.load(path=os.path.join(_here, "test_provider.json"))
        provider.get_ca_cert_path = MagicMock()
        provider.get_ca_cert_path.return_value = os.path.join(
            _here, "wrongcert.pem")
        provider.get_api_uri = MagicMock()
        provider.get_api_uri.return_value = self._get_https_uri()
        if not loaded:
            raise ImproperlyConfiguredError(
                "Could not load test provider config")

        register = srpregister.SRPRegister(provider_config=provider,
                                           register_path="users")
        ok = register.register_user("foouser_firsttime", "barpass")
        self.assertFalse(ok)
Ejemplo n.º 28
0
    def run_provider_select_checks(self, domain, download_if_needed=False):
        """
        Populates the check queue.

        :param domain: domain to check
        :type domain: unicode

        :param download_if_needed: if True, makes the checks do not
                                   overwrite already downloaded data
        :type download_if_needed: bool
        """
        leap_assert(domain and len(domain) > 0, "We need a domain!")

        self._domain = ProviderConfig.sanitize_path_component(domain)
        self._download_if_needed = download_if_needed

        name_resolution = None
        https_connection = None
        down_provider_info = None
        if self._signaler is not None:
            name_resolution = self._signaler.prov_name_resolution
            https_connection = self._signaler.prov_https_connection
            down_provider_info = self._signaler.prov_download_provider_info

        cb_chain = [(self._check_name_resolution, name_resolution),
                    (self._check_https, https_connection),
                    (self._download_provider_info, down_provider_info)]

        return self.addCallbackChain(cb_chain)
Ejemplo n.º 29
0
    def start_smtp_service(self, keymanager, userid, download_if_needed=False):
        """
        Starts the SMTP service.

        :param keymanager: a transparent proxy that eventually will point to a
                           Keymanager Instance.
        :type keymanager: zope.proxy.ProxyBase
        :param userid: the user id, in the form "user@provider"
        :type userid: str
        :param download_if_needed: True if it should check for mtime
                                   for the file
        :type download_if_needed: bool
        """
        try:
            username, domain = userid.split('@')
        except ValueError:
            logger.critical("Malformed userid parameter!")
            raise MalformedUserId()

        self._provider_config = ProviderConfig.get_provider_config(domain)
        self._keymanager = keymanager
        self._smtp_config = SMTPConfig()
        self._userid = userid
        self._download_if_needed = download_if_needed

        try:
            self._download_config_and_cert()
            logger.debug("Starting SMTP service.")
            self._start_smtp_service()
        except NoSMTPHosts:
            logger.warning("There is no SMTP host to use.")
        except Exception as e:
            # TODO: we should handle more specific exceptions in here
            logger.exception("Error while bootstrapping SMTP: %r" % (e, ))
Ejemplo n.º 30
0
    def register_user(self, domain, username, password):
        """
        Register a user using the domain and password given as parameters.

        :param domain: the domain we need to register the user.
        :type domain: unicode
        :param username: the user name
        :type username: unicode
        :param password: the password for the username
        :type password: unicode

        :returns: the defer for the operation running in a thread.
        :rtype: twisted.internet.defer.Deferred
        """
        config = ProviderConfig.get_provider_config(domain)
        self._provider_config = config
        if config is not None:
            srpregister = SRPRegister(signaler=self._signaler,
                                      provider_config=config)
            return threads.deferToThread(
                partial(srpregister.register_user, username, password))
        else:
            if self._signaler is not None:
                self._signaler.signal(self._signaler.srp_registration_failed)
            logger.error("Could not load provider configuration.")
Ejemplo n.º 31
0
    def test_check_api_certificate_skips(self):
        self.pb._provider_config = ProviderConfig()
        self.pb._session.get = mock.MagicMock(return_value=Response())

        self.pb._should_proceed_cert = mock.MagicMock(return_value=False)
        self.pb._check_api_certificate()
        self.assertFalse(self.pb._session.get.called)
Ejemplo n.º 32
0
    def bootstrap(self, username, domain, password):
        """
        Bootstrap Soledad with the user credentials.

        Signals:
            soledad_download_config
            soledad_gen_key

        :param user: user's login
        :type user: unicode
        :param domain: the domain that we are using.
        :type domain: unicode
        :param password: user's password
        :type password: unicode
        """
        provider_config = ProviderConfig.get_provider_config(domain)
        if provider_config is not None:
            sb = self._soledad_bootstrapper
            self._soledad_defer = sb.run_soledad_setup_checks(
                provider_config, username, password,
                download_if_needed=True)
            self._soledad_defer.addCallback(self._set_proxies_cb)
            self._soledad_defer.addCallback(self._set_service_tokens_cb)
            self._soledad_defer.addCallback(self._write_tokens_file,
                                            username, domain)
        else:
            if self._signaler is not None:
                self._signaler.signal(self._signaler.soledad_bootstrap_failed)
            logger.error("Could not load provider configuration.")

        return self._soledad_defer
Ejemplo n.º 33
0
    def test_get_client_cert_path_as_expected(self):
        config = self._get_eipconfig()
        provider_config = ProviderConfig()

        # mock 'get_domain' so we don't need to load a config
        provider_domain = 'test.provider.com'
        provider_config.get_domain = Mock(return_value=provider_domain)

        expected_path = os.path.join('leap', 'providers', provider_domain,
                                     'keys', 'client', 'openvpn.pem')

        # mock 'os.path.exists' so we don't get an error for unexisting file
        os.path.exists = Mock(return_value=True)
        cert_path = config.get_client_cert_path(provider_config)

        self.assertTrue(cert_path.endswith(expected_path))
Ejemplo n.º 34
0
    def setup_eip(self, domain, skip_network=False):
        """
        Initiate the setup for a provider

        :param domain: URL for the provider
        :type domain: unicode
        :param skip_network: Whether checks that involve network should be done
                             or not
        :type skip_network: bool

        :returns: the defer for the operation running in a thread.
        :rtype: twisted.internet.defer.Deferred
        """
        config = ProviderConfig.get_provider_config(domain)
        self._provider_config = config
        if config is not None:
            if skip_network:
                return defer.Deferred()
            eb = self._eip_bootstrapper
            d = eb.run_eip_setup_checks(self._provider_config,
                                        download_if_needed=True)
            self._eip_setup_defer = d
            return d
        else:
            raise Exception("No provider setup loaded")
Ejemplo n.º 35
0
    def bootstrap(self, provider):
        """
        Second stage of bootstrapping for a provider.

        :param provider: URL for the provider
        :type provider: unicode

        :returns: the defer for the operation running in a thread.
        :rtype: twisted.internet.defer.Deferred
        """
        d = None

        config = ProviderConfig.get_provider_config(provider)
        self._provider_config = config
        if config is not None:
            d = self._provider_bootstrapper.run_provider_setup_checks(
                config, download_if_needed=True)
        else:
            if self._signaler is not None:
                self._signaler.signal(
                    self._signaler.prov_problem_with_provider)
            logger.error("Could not load provider configuration.")
            self._login_widget.set_enabled(True)

        if d is None:
            d = defer.Deferred()
        return d
Ejemplo n.º 36
0
    def _get_provider_config(self, domain):
        """
        Helper to return a valid Provider Config from the domain name.

        :param domain: the domain name of the provider.
        :type domain: str

        :rtype: ProviderConfig or None if there is a problem loading the config
        """
        provider_config = ProviderConfig()
        provider_config_path = os.path.join(
            "leap", "providers", domain, "provider.json")

        if not provider_config.load(provider_config_path):
            provider_config = None

        return provider_config
Ejemplo n.º 37
0
    def test_get_client_cert_path_as_expected(self):
        config = self._get_eipconfig()
        provider_config = ProviderConfig()

        # mock 'get_domain' so we don't need to load a config
        provider_domain = 'test.provider.com'
        provider_config.get_domain = Mock(return_value=provider_domain)

        expected_path = os.path.join('leap', 'providers',
                                     provider_domain, 'keys', 'client',
                                     'openvpn.pem')

        # mock 'os.path.exists' so we don't get an error for unexisting file
        os.path.exists = Mock(return_value=True)
        cert_path = config.get_client_cert_path(provider_config)

        self.assertTrue(cert_path.endswith(expected_path))
Ejemplo n.º 38
0
    def test_authenticate_runs_cleanly(self):
        auth = srpauth.SRPAuth(ProviderConfig())
        auth._SRPAuth__instance.authenticate = mock.create_autospec(
            auth._SRPAuth__instance.authenticate,
            return_value=threads.deferToThread(MagicMock()))

        d = auth.authenticate("", "")

        return d
    def test_wrong_cert(self):
        provider = ProviderConfig()
        loaded = provider.load(path=os.path.join(
            _here, "test_provider.json"))
        provider.get_ca_cert_path = MagicMock()
        provider.get_ca_cert_path.return_value = os.path.join(
            _here,
            "wrongcert.pem")
        provider.get_api_uri = MagicMock()
        provider.get_api_uri.return_value = self._get_https_uri()
        if not loaded:
            raise ImproperlyConfiguredError(
                "Could not load test provider config")

        register = srpregister.SRPRegister(provider_config=provider,
                                           register_path="users")
        ok = register.register_user("foouser_firsttime", "barpass")
        self.assertFalse(ok)
Ejemplo n.º 40
0
    def __init__(self, signaler=None, bypass_checks=False):
        """
        Constructor for the Provider component

        :param signaler: Object in charge of handling communication
                         back to the frontend
        :type signaler: Signaler
        :param bypass_checks: Set to true if the app should bypass
                              first round of checks for CA
                              certificates at bootstrap
        :type bypass_checks: bool
        """
        self.key = "provider"
        self._signaler = signaler
        self._provider_bootstrapper = ProviderBootstrapper(
            signaler, bypass_checks)
        self._download_provider_defer = None
        self._provider_config = ProviderConfig()
Ejemplo n.º 41
0
    def test_run_eip_setup_checks(self):
        self.eb._download_config = mock.MagicMock()
        self.eb._download_client_certificates = mock.MagicMock()

        d = self.eb.run_eip_setup_checks(ProviderConfig())

        def check(*args):
            self.eb._download_config.assert_called_once_with()
            self.eb._download_client_certificates.assert_called_once_with(None)
        d.addCallback(check)
        return d
Ejemplo n.º 42
0
    def __init__(self, signaler=None):
        """
        Constructor for the Authenticate component

        :param signaler: Object in charge of handling communication
                         back to the frontend
        :type signaler: Signaler
        """
        self.key = "authenticate"
        self._signaler = signaler
        self._login_defer = None
        self._srp_auth = SRPAuth(ProviderConfig(), self._signaler)
    def setUp(self):
        self._provider_config = ProviderConfig()
        json_string = json.dumps(sample_config)
        self._provider_config.load(data=json_string)

        # At certain points we are going to be replacing these method
        # to avoid creating a file.
        # We need to save the old implementation and restore it in
        # tearDown so we are sure everything is as expected for each
        # test. If we do it inside each specific test, a failure in
        # the test will leave the implementation with the mock.
        self._old_ospath_exists = os.path.exists
Ejemplo n.º 44
0
    def __init__(self, signaler=None):
        """
        Constructor for the Register component

        :param signaler: Object in charge of handling communication
                         back to the frontend
        :type signaler: Signaler
        """
        object.__init__(self)
        self.key = "register"
        self._signaler = signaler
        self._provider_config = ProviderConfig()
Ejemplo n.º 45
0
    def _download_config_test_template(self, ifneeded, new):
        """
        All download config tests have the same structure, so this is
        a parametrized test for that.

        :param ifneeded: sets _download_if_needed
        :type ifneeded: bool
        :param new: if True uses time.time() as mtime for the mocked
                    eip-service file, otherwise it uses 100 (a really
                    old mtime)
        :type new: float or int (will be coersed)
        """
        pc = ProviderConfig()
        pc.get_domain = mock.MagicMock(
            return_value="localhost:%s" % (self.https_port))
        self.eb._provider_config = pc

        pc.get_api_uri = mock.MagicMock(
            return_value="https://%s" % (pc.get_domain()))
        pc.get_api_version = mock.MagicMock(return_value="1")

        # This is to ignore https checking, since it's not the point
        # of this test
        pc.get_ca_cert_path = mock.MagicMock(return_value=False)

        path_prefix = tempfile.mkdtemp()
        util.get_path_prefix = mock.MagicMock(return_value=path_prefix)
        EIPConfig.save = mock.MagicMock()
        EIPConfig.load = mock.MagicMock()

        self.eb._download_if_needed = ifneeded

        provider_dir = os.path.join(util.get_path_prefix(),
                                    "leap",
                                    "providers",
                                    pc.get_domain())
        mkdir_p(provider_dir)
        eip_config_path = os.path.join(provider_dir,
                                       "eip-service.json")

        with open(eip_config_path, "w") as ec:
            ec.write("A")

        # set mtime to something really new
        if new:
            os.utime(eip_config_path, (-1, time.time()))
        else:
            os.utime(eip_config_path, (-1, 100))
Ejemplo n.º 46
0
    def test_run_provider_setup_checks(self):
        self.pb._download_ca_cert = mock.MagicMock()
        self.pb._check_ca_fingerprint = mock.MagicMock()
        self.pb._check_api_certificate = mock.MagicMock()

        d = self.pb.run_provider_setup_checks(ProviderConfig())

        def check(*args):
            self.pb._download_ca_cert.assert_called_once_with()
            self.pb._check_ca_fingerprint.assert_called_once_with(None)
            self.pb._check_api_certificate.assert_called_once_with(None)

        d.addCallback(check)
        return d
Ejemplo n.º 47
0
    def _get_services(self, domain):
        """
        Returns a list of services provided by the given provider.

        :param domain: the provider to get the services from.
        :type domain: str

        :rtype: list of str
        """
        services = []
        provider_config = ProviderConfig.get_provider_config(domain)
        if provider_config is not None:
            services = provider_config.get_services()

        return services
Ejemplo n.º 48
0
    def _get_services(self, domain):
        """
        Returns a list of services provided by the given provider.

        :param domain: the provider to get the services from.
        :type domain: str

        :rtype: list of str
        """
        services = []
        provider_config = ProviderConfig.get_provider_config(domain)
        if provider_config is not None:
            services = provider_config.get_services()

        return services
Ejemplo n.º 49
0
    def __init__(self, signaler=None):
        """
        Constructor for the EIP component

        :param signaler: Object in charge of handling communication
                         back to the frontend
        :type signaler: Signaler
        """
        self.key = "eip"
        self._signaler = signaler
        self._eip_bootstrapper = EIPBootstrapper(signaler)
        self._eip_setup_defer = None
        self._provider_config = ProviderConfig()

        self._vpn = vpnprocess.VPN(signaler=signaler)
Ejemplo n.º 50
0
    def _download_certificate_test_template(self, ifneeded, createcert):
        """
        All download client certificate tests have the same structure,
        so this is a parametrized test for that.

        :param ifneeded: sets _download_if_needed
        :type ifneeded: bool
        :param createcert: if True it creates a dummy file to play the
                           part of a downloaded certificate
        :type createcert: bool

        :returns: the temp eip cert path and the dummy cert contents
        :rtype: tuple of str, str
        """
        pc = ProviderConfig()
        ec = EIPConfig()
        self.eb._provider_config = pc
        self.eb._eip_config = ec

        pc.get_domain = mock.MagicMock(
            return_value="localhost:%s" % (self.https_port))
        pc.get_api_uri = mock.MagicMock(
            return_value="https://%s" % (pc.get_domain()))
        pc.get_api_version = mock.MagicMock(return_value="1")
        pc.get_ca_cert_path = mock.MagicMock(return_value=False)

        path_prefix = tempfile.mkdtemp()
        util.get_path_prefix = mock.MagicMock(return_value=path_prefix)
        EIPConfig.save = mock.MagicMock()
        EIPConfig.load = mock.MagicMock()

        self.eb._download_if_needed = ifneeded

        provider_dir = os.path.join(util.get_path_prefix(),
                                    "leap",
                                    "providers",
                                    "somedomain")
        mkdir_p(provider_dir)
        eip_cert_path = os.path.join(provider_dir,
                                     "cert")

        ec.get_client_cert_path = mock.MagicMock(
            return_value=eip_cert_path)

        cert_content = "A"
        if createcert:
            with open(eip_cert_path, "w") as ec:
                ec.write(cert_content)

        return eip_cert_path, cert_content
Ejemplo n.º 51
0
    def test_check_api_certificate_succeeds(self):
        self.pb._provider_config = ProviderConfig()
        self.pb._provider_config.get_api_uri = mock.MagicMock(
            return_value="https://localhost:%s" % (self.https_port, ))
        self.pb._provider_config.get_ca_cert_path = mock.MagicMock(
            return_value=where('cacert.pem'))
        self.pb._provider_config.get_api_version = mock.MagicMock(
            return_value="1")

        self.pb._should_proceed_cert = mock.MagicMock(return_value=True)

        def check(*args):
            self.pb._check_api_certificate()

        d = threads.deferToThread(check)
        return d
Ejemplo n.º 52
0
    def _can_start(self, domain):
        """
        Returns True if it has everything that is needed to run EIP,
        False otherwise

        :param domain: the domain for the provider to check
        :type domain: str
        """
        if IS_LINUX and not LinuxPolicyChecker.is_up():
            logger.error("No polkit agent running.")
            return False

        provider_config = ProviderConfig.get_provider_config(domain)
        if EIP_SERVICE not in provider_config.get_services():
            return False
        eip_config = eipconfig.EIPConfig()

        api_version = provider_config.get_api_version()
        eip_config.set_api_version(api_version)
        eip_loaded = eip_config.load(eipconfig.get_eipconfig_path(domain))

        launcher = get_vpn_launcher()
        ovpn_path = force_eval(launcher.OPENVPN_BIN_PATH)
        if not os.path.isfile(ovpn_path):
            logger.error("Cannot start OpenVPN, binary not found: %s" %
                         (ovpn_path,))
            return False

        # check for other problems
        if not eip_loaded or provider_config is None:
            logger.error("Cannot load provider and eip config, cannot "
                         "autostart")
            return False

        client_cert_path = eip_config.\
            get_client_cert_path(provider_config, about_to_download=True)

        if leap_certs.should_redownload(client_cert_path):
            logger.error("The client should redownload the certificate,"
                         " cannot autostart")
            return False

        if not os.path.isfile(client_cert_path):
            logger.error("Can't find the certificate, cannot autostart")
            return False

        return True
    def _download_config_test_template(self, ifneeded, new):
        """
        All download config tests have the same structure, so this is
        a parametrized test for that.

        :param ifneeded: sets _download_if_needed
        :type ifneeded: bool
        :param new: if True uses time.time() as mtime for the mocked
                    eip-service file, otherwise it uses 100 (a really
                    old mtime)
        :type new: float or int (will be coersed)
        """
        pc = ProviderConfig()
        pc.get_domain = mock.MagicMock(
            return_value="localhost:%s" % (self.https_port))
        self.eb._provider_config = pc

        pc.get_api_uri = mock.MagicMock(
            return_value="https://%s" % (pc.get_domain()))
        pc.get_api_version = mock.MagicMock(return_value="1")

        # This is to ignore https checking, since it's not the point
        # of this test
        pc.get_ca_cert_path = mock.MagicMock(return_value=False)

        path_prefix = tempfile.mkdtemp()
        util.get_path_prefix = mock.MagicMock(return_value=path_prefix)
        EIPConfig.save = mock.MagicMock()
        EIPConfig.load = mock.MagicMock()

        self.eb._download_if_needed = ifneeded

        provider_dir = os.path.join(util.get_path_prefix(),
                                    "leap",
                                    "providers",
                                    pc.get_domain())
        mkdir_p(provider_dir)
        eip_config_path = os.path.join(provider_dir,
                                       "eip-service.json")

        with open(eip_config_path, "w") as ec:
            ec.write("A")

        # set mtime to something really new
        if new:
            os.utime(eip_config_path, (-1, time.time()))
        else:
            os.utime(eip_config_path, (-1, 100))
Ejemplo n.º 54
0
    def _can_start(self, domain):
        """
        Returns True if it has everything that is needed to run EIP,
        False otherwise

        :param domain: the domain for the provider to check
        :type domain: str
        """
        if not LinuxPolicyChecker.is_up():
            logger.error("No polkit agent running.")
            return False

        eip_config = eipconfig.EIPConfig()
        provider_config = ProviderConfig.get_provider_config(domain)

        api_version = provider_config.get_api_version()
        eip_config.set_api_version(api_version)
        eip_loaded = eip_config.load(eipconfig.get_eipconfig_path(domain))

        launcher = get_vpn_launcher()
        ovpn_path = force_eval(launcher.OPENVPN_BIN_PATH)
        if not os.path.isfile(ovpn_path):
            logger.error("Cannot start OpenVPN, binary not found: %s" %
                         (ovpn_path, ))
            return False

        # check for other problems
        if not eip_loaded or provider_config is None:
            logger.error("Cannot load provider and eip config, cannot "
                         "autostart")
            return False

        client_cert_path = eip_config.\
            get_client_cert_path(provider_config, about_to_download=True)

        if leap_certs.should_redownload(client_cert_path):
            logger.error("The client should redownload the certificate,"
                         " cannot autostart")
            return False

        if not os.path.isfile(client_cert_path):
            logger.error("Can't find the certificate, cannot autostart")
            return False

        return True
Ejemplo n.º 55
0
    def test_check_api_certificate_fails(self):
        self.pb._provider_config = ProviderConfig()
        self.pb._provider_config.get_api_uri = mock.MagicMock(
            return_value="https://localhost:%s" % (self.https_port, ))
        self.pb._provider_config.get_ca_cert_path = mock.MagicMock(
            return_value=os.path.join(
                os.path.split(__file__)[0], "wrongcert.pem"))
        self.pb._provider_config.get_api_version = mock.MagicMock(
            return_value="1")

        self.pb._should_proceed_cert = mock.MagicMock(return_value=True)

        def check(*args):
            with self.assertRaises(requests.exceptions.SSLError):
                self.pb._check_api_certificate()

        d = threads.deferToThread(check)
        return d
Ejemplo n.º 56
0
    def __init__(self, signaler=None, bypass_checks=False):
        """
        Constructor for the Provider component

        :param signaler: Object in charge of handling communication
                         back to the frontend
        :type signaler: Signaler
        :param bypass_checks: Set to true if the app should bypass
                              first round of checks for CA
                              certificates at bootstrap
        :type bypass_checks: bool
        """
        object.__init__(self)
        self.key = "provider"
        self._provider_bootstrapper = ProviderBootstrapper(signaler,
                                                           bypass_checks)
        self._download_provider_defer = None
        self._provider_config = ProviderConfig()
    def _download_certificate_test_template(self, ifneeded, createcert):
        """
        All download client certificate tests have the same structure,
        so this is a parametrized test for that.

        :param ifneeded: sets _download_if_needed
        :type ifneeded: bool
        :param createcert: if True it creates a dummy file to play the
                           part of a downloaded certificate
        :type createcert: bool

        :returns: the temp eip cert path and the dummy cert contents
        :rtype: tuple of str, str
        """
        pc = ProviderConfig()
        ec = EIPConfig()
        self.eb._provider_config = pc
        self.eb._eip_config = ec

        pc.get_domain = mock.MagicMock(
            return_value="localhost:%s" % (self.https_port))
        pc.get_api_uri = mock.MagicMock(
            return_value="https://%s" % (pc.get_domain()))
        pc.get_api_version = mock.MagicMock(return_value="1")
        pc.get_ca_cert_path = mock.MagicMock(return_value=False)

        path_prefix = tempfile.mkdtemp()
        util.get_path_prefix = mock.MagicMock(return_value=path_prefix)
        EIPConfig.save = mock.MagicMock()
        EIPConfig.load = mock.MagicMock()

        self.eb._download_if_needed = ifneeded

        provider_dir = os.path.join(util.get_path_prefix(),
                                    "leap",
                                    "providers",
                                    "somedomain")
        mkdir_p(provider_dir)
        eip_cert_path = os.path.join(provider_dir,
                                     "cert")

        ec.get_client_cert_path = mock.MagicMock(
            return_value=eip_cert_path)

        cert_content = "A"
        if createcert:
            with open(eip_cert_path, "w") as ec:
                ec.write(cert_content)

        return eip_cert_path, cert_content
Ejemplo n.º 58
0
    def get_gateway_country_code(self, domain):
        """
        Signal the country code for the currently used gateway for the given
        provider.

        :param domain: the domain to get country code.
        :type domain: str

        Signals:
            eip_get_gateway_country_code -> str
            eip_no_gateway
        """
        settings = Settings()

        eip_config = eipconfig.EIPConfig()
        provider_config = ProviderConfig.get_provider_config(domain)

        api_version = provider_config.get_api_version()
        eip_config.set_api_version(api_version)
        eip_config.load(eipconfig.get_eipconfig_path(domain))

        gateway_selector = eipconfig.VPNGatewaySelector(eip_config)
        gateway_conf = settings.get_selected_gateway(domain)

        if gateway_conf == GATEWAY_AUTOMATIC:
            gateways = gateway_selector.get_gateways()
        else:
            gateways = [gateway_conf]

        if not gateways:
            self._signaler.signal(self._signaler.eip_no_gateway)
            return

        # this only works for selecting the first gateway, as we're
        # currently doing.
        ccodes = gateway_selector.get_gateways_country_code()
        gateway_ccode = ''  # '' instead of None due to needed signal argument
        if ccodes is not None:
            gateway_ccode = ccodes[gateways[0]]

        self._signaler.signal(self._signaler.eip_get_gateway_country_code,
                              gateway_ccode)
Ejemplo n.º 59
0
    def get_gateway_country_code(self, domain):
        """
        Signal the country code for the currently used gateway for the given
        provider.

        :param domain: the domain to get country code.
        :type domain: str

        Signals:
            eip_get_gateway_country_code -> str
            eip_no_gateway
        """
        settings = Settings()

        eip_config = eipconfig.EIPConfig()
        provider_config = ProviderConfig.get_provider_config(domain)

        api_version = provider_config.get_api_version()
        eip_config.set_api_version(api_version)
        eip_config.load(eipconfig.get_eipconfig_path(domain))

        gateway_selector = eipconfig.VPNGatewaySelector(eip_config)
        gateway_conf = settings.get_selected_gateway(domain)

        if gateway_conf == GATEWAY_AUTOMATIC:
            gateways = gateway_selector.get_gateways()
        else:
            gateways = [gateway_conf]

        if not gateways:
            self._signaler.signal(self._signaler.eip_no_gateway)
            return

        # this only works for selecting the first gateway, as we're
        # currently doing.
        ccodes = gateway_selector.get_gateways_country_code()
        gateway_ccode = ''  # '' instead of None due to needed signal argument
        if ccodes is not None:
            gateway_ccode = ccodes[gateways[0]]

        self._signaler.signal(self._signaler.eip_get_gateway_country_code,
                              gateway_ccode)
Ejemplo n.º 60
0
    def get_gateways_list(self, domain):
        """
        Signal a list of gateways for the given provider.

        :param domain: the domain to get the gateways.
        :type domain: str

        Signals:
            eip_get_gateways_list -> list of unicode
            eip_get_gateways_list_error
            eip_uninitialized_provider
        """
        if not self._provider_is_initialized(domain):
            if self._signaler is not None:
                self._signaler.signal(
                    self._signaler.eip_uninitialized_provider)
            return

        provider_config = ProviderConfig.get_provider_config(domain)
        if EIP_SERVICE not in provider_config.get_services():
            return
        eip_config = eipconfig.EIPConfig()

        api_version = provider_config.get_api_version()
        eip_config.set_api_version(api_version)
        eip_loaded = eip_config.load(eipconfig.get_eipconfig_path(domain))

        # check for other problems
        if not eip_loaded or provider_config is None:
            if self._signaler is not None:
                self._signaler.signal(
                    self._signaler.eip_get_gateways_list_error)
            return

        gateways = eipconfig.VPNGatewaySelector(eip_config).get_gateways_list()

        if self._signaler is not None:
            self._signaler.signal(
                self._signaler.eip_get_gateways_list, gateways)