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 prevoiusly 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 = self._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)
def _get_eipconfig(self, fromfile=True, data=sample_config, api_ver='1'): """ Helper that returns an EIPConfig object using the data parameter or a sample data. :param fromfile: sets if we should use a file or a string :type fromfile: bool :param data: sets the data to be used to load in the EIPConfig object :type data: dict (valid json) :param api_ver: the api_version schema to use. :type api_ver: str :rtype: EIPConfig """ config = EIPConfig() config.set_api_version(api_ver) loaded = False if fromfile: self._write_config(data) loaded = config.load(self.configfile, relative=False) else: json_string = json.dumps(data) loaded = config.load(data=json_string) if not loaded: return None return config
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
def _download_config(self, *args): """ Downloads the EIP config for the given provider """ leap_assert(self._provider_config, "We need a provider configuration!") logger.debug("Downloading EIP config for %s" % (self._provider_config.get_domain(), )) self._eip_config = EIPConfig() download_service_config(self._provider_config, self._eip_config, self._session, self._download_if_needed)
def _download_config(self, *args): """ Downloads the EIP config for the given provider """ leap_assert(self._provider_config, "We need a provider configuration!") logger.debug("Downloading EIP config for %s" % (self._provider_config.get_domain(),)) api_version = self._provider_config.get_api_version() self._eip_config = EIPConfig() self._eip_config.set_api_version(api_version) headers = {} mtime = get_mtime(os.path.join(self._eip_config .get_path_prefix(), "leap", "providers", self._provider_config.get_domain(), "eip-service.json")) if self._download_if_needed and mtime: headers['if-modified-since'] = mtime # there is some confusion with this uri, # it's in 1/config/eip, config/eip and config/1/eip... config_uri = "%s/%s/config/eip-service.json" % ( self._provider_config.get_api_uri(), api_version) logger.debug('Downloading eip config from: %s' % config_uri) res = self._session.get(config_uri, verify=self._provider_config .get_ca_cert_path(), headers=headers, timeout=REQUEST_TIMEOUT) res.raise_for_status() # Not modified if res.status_code == 304: logger.debug("EIP definition has not been modified") else: eip_definition, mtime = get_content(res) self._eip_config.load(data=eip_definition, mtime=mtime) self._eip_config.save(["leap", "providers", self._provider_config.get_domain(), "eip-service.json"])
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() EIPConfig.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(EIPConfig.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))
def setUp(self): self.eipconfig = EIPConfig() self.eipconfig.get_gateways = Mock(return_value=sample_gateways) self.eipconfig.get_locations = Mock(return_value=sample_locations)
def test_fails_without_api_set(self): config = EIPConfig() with self.assertRaises(AssertionError): config.load('non-relevant-path')
:type providerconfig: ProviderConfig :rtype: dict """ return {} if __name__ == "__main__": logger = logging.getLogger(name="leap") logger.setLevel(logging.DEBUG) console = logging.StreamHandler() console.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s " "- %(name)s - %(levelname)s - %(message)s") console.setFormatter(formatter) logger.addHandler(console) try: abs_launcher = VPNLauncher() except Exception as e: assert isinstance(e, TypeError), "Something went wrong" print "Abstract Prefixer class is working as expected" vpnlauncher = get_platform_launcher() eipconfig = EIPConfig() eipconfig.set_api_version("1") if eipconfig.load("leap/providers/bitmask.net/eip-service.json"): provider = ProviderConfig() if provider.load("leap/providers/bitmask.net/provider.json"): vpnlauncher.get_vpn_command(eipconfig=eipconfig, providerconfig=provider, socket_host="/blah")
class EIPBootstrapper(AbstractBootstrapper): """ Sets up EIP for a provider a series of checks and emits signals after they are passed. If a check fails, the subsequent checks are not executed """ # All dicts returned are of the form # {"passed": bool, "error": str} download_config = QtCore.Signal(dict) download_client_certificate = QtCore.Signal(dict) def __init__(self): AbstractBootstrapper.__init__(self) self._provider_config = None self._eip_config = None self._download_if_needed = False def _download_config(self, *args): """ Downloads the EIP config for the given provider """ leap_assert(self._provider_config, "We need a provider configuration!") logger.debug("Downloading EIP config for %s" % (self._provider_config.get_domain(),)) api_version = self._provider_config.get_api_version() self._eip_config = EIPConfig() self._eip_config.set_api_version(api_version) headers = {} mtime = get_mtime(os.path.join(self._eip_config .get_path_prefix(), "leap", "providers", self._provider_config.get_domain(), "eip-service.json")) if self._download_if_needed and mtime: headers['if-modified-since'] = mtime # there is some confusion with this uri, # it's in 1/config/eip, config/eip and config/1/eip... config_uri = "%s/%s/config/eip-service.json" % ( self._provider_config.get_api_uri(), api_version) logger.debug('Downloading eip config from: %s' % config_uri) res = self._session.get(config_uri, verify=self._provider_config .get_ca_cert_path(), headers=headers, timeout=REQUEST_TIMEOUT) res.raise_for_status() # Not modified if res.status_code == 304: logger.debug("EIP definition has not been modified") else: eip_definition, mtime = get_content(res) self._eip_config.load(data=eip_definition, mtime=mtime) self._eip_config.save(["leap", "providers", self._provider_config.get_domain(), "eip-service.json"]) def _download_client_certificates(self, *args): """ Downloads the EIP client certificate for the given provider """ leap_assert(self._provider_config, "We need a provider configuration!") leap_assert(self._eip_config, "We need an eip configuration!") logger.debug("Downloading EIP client certificate for %s" % (self._provider_config.get_domain(),)) client_cert_path = self._eip_config.\ get_client_cert_path(self._provider_config, about_to_download=True) # For re-download if something is wrong with the cert self._download_if_needed = self._download_if_needed and \ not certs.should_redownload(client_cert_path) if self._download_if_needed and \ os.path.exists(client_cert_path): check_and_fix_urw_only(client_cert_path) return srp_auth = SRPAuth(self._provider_config) session_id = srp_auth.get_session_id() cookies = None if session_id: cookies = {"_session_id": session_id} cert_uri = "%s/%s/cert" % ( self._provider_config.get_api_uri(), self._provider_config.get_api_version()) logger.debug('getting cert from uri: %s' % cert_uri) res = self._session.get(cert_uri, verify=self._provider_config .get_ca_cert_path(), cookies=cookies, timeout=REQUEST_TIMEOUT) res.raise_for_status() client_cert = res.content if not certs.is_valid_pemfile(client_cert): raise Exception(self.tr("The downloaded certificate is not a " "valid PEM file")) mkdir_p(os.path.dirname(client_cert_path)) with open(client_cert_path, "w") as f: f.write(client_cert) check_and_fix_urw_only(client_cert_path) def run_eip_setup_checks(self, provider_config, download_if_needed=False): """ Starts the checks needed for a new eip setup :param provider_config: Provider configuration :type provider_config: ProviderConfig """ leap_assert(provider_config, "We need a provider config!") leap_assert_type(provider_config, ProviderConfig) self._provider_config = provider_config self._download_if_needed = download_if_needed cb_chain = [ (self._download_config, self.download_config), (self._download_client_certificates, self.download_client_certificate) ] return self.addCallbackChain(cb_chain)