def test_missing_certs_raises_exception(self, read_data):
     with patch.object(builtins, 'open',
                       return_value=io.BytesIO(
                           dedent(read_data).encode())), \
          patch.object(os.path, 'isfile', return_value=True):
         with self.assertRaises(ValueError):
             DxlClientConfig.create_dxl_config_from_file("mock_file.cfg")
Beispiel #2
0
    def test_get_fastest_broker_gets_the_fastest(self):
        semaphore = threading.Semaphore(0)
        # Mock brokers connect speed
        fast_broker = Mock()
        slow_broker = Mock()

        def connect_to_broker_slow():
            import time

            semaphore.acquire()
            time.sleep(0.1)
            return

        def connect_to_broker_fast():
            semaphore.release()
            return

        slow_broker._connect_to_broker = connect_to_broker_slow
        fast_broker._connect_to_broker = connect_to_broker_fast
        # Create config and add brokers
        config = DxlClientConfig(broker_ca_bundle=get_ca_bundle_pem(),
                                 cert_file=get_cert_file_pem(),
                                 private_key=get_dxl_private_key(),
                                 brokers=[])
        config.brokers.append(fast_broker)
        config.brokers.append(slow_broker)
        # Check that the returned is the fastest
        self.assertEqual(config._get_fastest_broker(), fast_broker)
    def execute(self, args):
        # Prompt the user for any require server credential arguments which
        # were not specified on the command line.
        _prompt_server_args(args)

        pk_filename = _private_key_filename(args.file_prefix)
        csr_as_string = self._process_csr_and_private_key(
            os.path.join(args.config_dir, pk_filename), args)

        svc = ManagementService(args.host, args.port, args.user, args.password,
                                verify=args.truststore)
        data_responses = svc.invoke_command(
            self._PROVISION_COMMAND,
            {"csrString": csr_as_string}).split(",")

        if len(data_responses) < 3:
            raise Exception("{} Expected {}, Received {}. Value: {}".format(
                "Did not receive expected number of response elements.",
                3, len(data_responses), data_responses))

        brokers = self._brokers_for_config(data_responses[2].splitlines())
        config_file = os.path.join(args.config_dir, _DXL_CONFIG_FILE_NAME)
        logger.info("Saving DXL config file to %s", config_file)
        dxlconfig = DxlClientConfig(_CA_BUNDLE_FILE_NAME,
                                    _cert_filename(args.file_prefix),
                                    pk_filename,
                                    brokers)
        dxlconfig.write(config_file)

        self._save_pem(data_responses[0], "ca bundle",
                       os.path.join(args.config_dir,
                                    dxlconfig.broker_ca_bundle))
        self._save_pem(data_responses[1], "client certificate",
                       os.path.join(args.config_dir, dxlconfig.cert_file))
 def test_get_brokers_raises_exception_from_invalid_json(self, policy):
     config = DxlClientConfig(broker_ca_bundle=get_ca_bundle_pem(),
                              cert_file=get_cert_file_pem(),
                              private_key=get_dxl_private_key(),
                              brokers=[])
     with self.assertRaises(BrokerListError):
         config._set_brokers_from_json(policy)
    def test_set_config_from_file_generates_dxl_config(self):
        read_data = """
        [Certs]
        BrokerCertChain=certchain.pem
        CertFile=certfile.pem
        PrivateKey=privatekey.pk

        [Brokers]
        22cdcace-6e8f-11e5-29c0-005056aa56de=22cdcace-6e8f-11e5-29c0-005056aa56de;8883;dxl-broker-1;10.218.73.206
        """

        with patch.object(builtins, 'open',
                          return_value=io.BytesIO(
                              dedent(read_data).encode())) as mock_open, \
                patch.object(os.path, 'isfile', return_value=True):
            client_config = DxlClientConfig.create_dxl_config_from_file(
                "mock_file")
            self.assertEqual(client_config.cert_file, "certfile.pem")
            self.assertEqual(client_config.broker_ca_bundle, "certchain.pem")
            self.assertEqual(client_config.private_key, "privatekey.pk")
            broker = client_config.brokers[0]
            self.assertEqual(broker.host_name, "dxl-broker-1")
            self.assertEqual(broker.ip_address, "10.218.73.206")
            self.assertEqual(broker.port, 8883)
            self.assertEqual(broker.unique_id,
                             "22cdcace-6e8f-11e5-29c0-005056aa56de")
        mock_open.assert_called_with("mock_file", "rb")
Beispiel #6
0
 def test_missing_brokers_doesnt_raise_exceptions(self, read_data):
     with patch.object(__builtin__, 'open',
                       return_value=io.BytesIO(dedent(read_data))), \
          patch.object(os.path, 'isfile', return_value=True):
         client_config = DxlClientConfig.create_dxl_config_from_file(
             "mock_file.cfg")
         self.assertEqual(len(client_config.brokers), 0)
    def test_write_modified_config(self):
        initial_data = os.linesep.join([
            "# mycerts", "[Certs]", "BrokerCertChain = abundle.crt",
            "CertFile = acertfile.crt", "# pk file", "PrivateKey = akey.key",
            "{}[Brokers]".format(os.linesep), "# broker 7",
            "myid7 = myid7;8007;myhost7;10.10.100.7", "# broker 8",
            "myid8 = myid8;8008;myhost8;10.10.100.8{}".format(os.linesep)
        ])

        expected_data_after_mods = os.linesep.join([
            "# mycerts", "[Certs]", "BrokerCertChain = newbundle.pem",
            "CertFile = acertfile.crt", "# pk file", "PrivateKey = newkey.pem",
            "{}[Brokers]".format(os.linesep), "# broker 8",
            "myid8 = myid8;8008;myhost8;10.10.100.8",
            "myid9 = myid9;8009;myhost9;10.10.100.9{}".format(os.linesep)
        ])

        with patch.object(builtins, 'open',
                          return_value=io.BytesIO(initial_data.encode())), \
                patch.object(os.path, 'isfile', return_value=True):
            config = DxlClientConfig.create_dxl_config_from_file(
                "mock_file.cfg")
        del config.brokers[0]
        config.broker_ca_bundle = "newbundle.pem"
        config.private_key = "newkey.pem"
        config.brokers.append(Broker("myhost9", "myid9", "10.10.100.9", 8009))
        byte_stream = self.CapturedBytesIO()
        with patch.object(builtins, 'open',
                          return_value=byte_stream) as mock_open:
            config.write("newfile.txt")
        self.assertEqual(expected_data_after_mods.encode(),
                         byte_stream.bytes_captured)
        mock_open.assert_called_with("newfile.txt", "wb")
Beispiel #8
0
    def create_client(self,
                      max_retries=DEFAULT_RETRIES,
                      incoming_message_thread_pool_size=1):
        config = DxlClientConfig.create_dxl_config_from_file(
            os.path.dirname(os.path.abspath(__file__)) + "/client_config.cfg")
        config.incoming_message_thread_pool_size = incoming_message_thread_pool_size

        config.connect_retries = max_retries
        return TestDxlClient(config)
Beispiel #9
0
 def test_get_sorted_broker_list_returns_all_brokers(self):
     # Create config
     config = DxlClientConfig(broker_ca_bundle=get_ca_bundle_pem(),
                              cert_file=get_cert_file_pem(),
                              private_key=get_dxl_private_key(),
                              brokers=[])
     # Create mocked brokers
     b1 = Mock()
     b2 = Mock()
     b1._connect_to_broker = b2._connect_to_broker = Mock(return_value=True)
     # Add them to config
     config.brokers.append(b1)
     config.brokers.append(b2)
     # Get all brokers
     l = config._get_sorted_broker_list()
     # Check all brokers are in the list
     self.assertTrue(b1 in l)
     self.assertTrue(b2 in l)
 def test_write_in_memory_config(self):
     expected_data = os.linesep.join([
         "[Certs]", "BrokerCertChain = mycabundle.pem",
         "CertFile = mycertfile.pem", "PrivateKey = myprivatekey.pem",
         "{}[Brokers]".format(os.linesep),
         "myid1 = myid1;8001;myhost1;10.10.100.1",
         "myid2 = myid2;8002;myhost2;10.10.100.2{}".format(os.linesep)
     ])
     byte_stream = self.CapturedBytesIO()
     with patch.object(builtins, 'open',
                       return_value=byte_stream) as mock_open:
         config = DxlClientConfig(
             "mycabundle.pem", "mycertfile.pem", "myprivatekey.pem", [
                 Broker("myhost1", "myid1", "10.10.100.1", 8001),
                 Broker("myhost2", "myid2", "10.10.100.2", 8002)
             ])
         config.write("myfile.txt")
     self.assertEqual(expected_data.encode(), byte_stream.bytes_captured)
     mock_open.assert_called_with("myfile.txt", "wb")
Beispiel #11
0
    def setUp(self):
        mqtt_client_patch = patch('pahoproxy.client.Client')
        mqtt_client_patch.start()

        self.config = DxlClientConfig(broker_ca_bundle=get_ca_bundle_pem(),
                                      cert_file=get_cert_file_pem(),
                                      private_key=get_dxl_private_key(),
                                      brokers=[])

        self.req_callback = RequestCallback()
        self.req_callback.on_request = Mock()
Beispiel #12
0
    def setUp(self):
        self.config = DxlClientConfig(broker_ca_bundle=get_ca_bundle_pem(),
                                      cert_file=get_cert_file_pem(),
                                      private_key=get_dxl_private_key(),
                                      brokers=[])

        mqtt_client_patch = patch('paho.mqtt.client.Client')
        mqtt_client_patch.start()

        self.client = DxlClient(self.config)
        self.client._request_manager.wait_for_response = Mock(return_value=Response(request=None))

        self.test_channel = '/test/channel'
Beispiel #13
0
    def create_client(max_retries=DEFAULT_RETRIES, thread_pool_size=1):
        """
        Creates base DXL client
        """

        config = DxlClientConfig.create_dxl_config_from_file(
            str(os.path.dirname(os.path.abspath(__file__))) +
            "/dxlclient.config")

        config.incoming_message_thread_pool_size = thread_pool_size

        config.connect_retries = max_retries

        return DxlClient(config)
    def execute(self, args):
        # Prompt the user for any require server credential arguments which
        # were not specified on the command line.
        _prompt_server_args(args)

        config_file = os.path.join(args.config_dir, _DXL_CONFIG_FILE_NAME)

        if not os.path.isfile(config_file):
            raise Exception("Unable to find config file to update: {}".format(
                config_file))

        dxlconfig = DxlClientConfig.create_dxl_config_from_file(config_file)
        svc = ManagementService(args.host, args.port, args.user, args.password,
                                verify=args.truststore)

        self._update_broker_cert_chain(svc, dxlconfig.broker_ca_bundle)
        self._update_broker_config(svc, dxlconfig)

        logger.info("Updating DXL config file at %s", config_file)
        dxlconfig.write(config_file)
Beispiel #15
0
 def test_set_config_wrong_file_raises_exception(self):
     with self.assertRaises(Exception):
         DxlClientConfig.create_dxl_config_from_file("this_file_doesnt_exist.cfg")
Beispiel #16
0
 def test_get_sorted_broker_list_returns_empty_when_no_brokers(self):
     config = DxlClientConfig(broker_ca_bundle=get_ca_bundle_pem(),
                              cert_file=get_cert_file_pem(),
                              private_key=get_dxl_private_key(),
                              brokers=[])
     self.assertEqual(config._get_sorted_broker_list(), [])
 def test_missing_certs_raises_exception(self, read_data):
     with patch.object(__builtin__,
                       'open',
                       return_value=io.BytesIO(dedent(read_data))):
         with self.assertRaises(ValueError):
             DxlClientConfig.create_dxl_config_from_file("mock_file.cfg")