Exemplo n.º 1
0
class TestResetScreen(unittest.TestCase):
    def setUp(self) -> None:
        """Pre-test actions."""
        self.cmd_data = nick_to_pub_key("Alice")
        self.window_list = WindowList()
        self.window_list.windows = [
            RxWindow(uid=nick_to_pub_key("Alice"), name='Alice'),
            RxWindow(uid=nick_to_pub_key("Bob"), name='Bob')
        ]
        self.window = self.window_list.get_window(nick_to_pub_key("Alice"))
        self.window.message_log = [(datetime.now(), 'Hi Bob',
                                    nick_to_pub_key("Alice"),
                                    ORIGIN_CONTACT_HEADER)]

    @mock.patch('os.system', return_value=None, create_autospec=True)
    def test_screen_reset(self, reset) -> None:
        # Ensure there is a message to be removed from the ephemeral message log
        self.assertEqual(len(self.window.message_log), 1)

        reset_screen(self.cmd_data, self.window_list)

        # Test that screen is reset by the command
        reset.assert_called_with(RESET)

        # Test that the ephemeral message log is empty after the command
        self.assertEqual(len(self.window.message_log), 0)
Exemplo n.º 2
0
class TestChNick(TFCTestCase):

    def setUp(self):
        self.ts           = datetime.now()
        self.contact_list = ContactList(nicks=['Alice'])
        self.window_list  = WindowList(contact_list=self.contact_list)
        self.group_list   = GroupList()
        self.args         = self.ts, self.window_list, self.contact_list
        self.window       = self.window_list.get_window(nick_to_pub_key("Alice"))
        self.window.type  = WIN_TYPE_CONTACT

    def test_unknown_account_raises_fr(self):
        # Setup
        cmd_data = nick_to_pub_key("Bob") + b'Bob_'

        # Test
        trunc_addr = nick_to_short_address('Bob')
        self.assert_fr(f"Error: Receiver has no contact '{trunc_addr}' to rename.", ch_nick, cmd_data, *self.args)

    def test_nick_change(self):
        # Setup
        cmd_data = nick_to_pub_key("Alice") + b'Alice_'

        # Test
        self.assertIsNone(ch_nick(cmd_data, *self.args))
        self.assertEqual(self.contact_list.get_contact_by_pub_key(nick_to_pub_key("Alice")).nick, 'Alice_')
        self.assertEqual(self.window.name, 'Alice_')
Exemplo n.º 3
0
class TestLocalKeyRdy(TFCTestCase):
    def setUp(self):
        self.ts = datetime.fromtimestamp(1502750000)

    @mock.patch('time.sleep', return_value=None)
    def test_local_key_installed_no_contacts(self, _):
        # Setup
        self.window_list = WindowList(nicks=[LOCAL_ID])
        self.contact_list = ContactList(nicks=[LOCAL_ID])

        # Test
        self.assert_prints(
            f"""\
{BOLD_ON}                  Successfully completed the local key setup.                   {NORMAL_TEXT}
{CLEAR_ENTIRE_SCREEN+CURSOR_LEFT_UP_CORNER}
{BOLD_ON}                            Waiting for new contacts                            {NORMAL_TEXT}

""", local_key_rdy, self.ts, self.window_list, self.contact_list)

    @mock.patch('time.sleep', return_value=None)
    def test_local_key_installed_existing_contact(self, _):
        # Setup
        self.window_list = WindowList(nicks=[LOCAL_ID, 'Alice'])
        self.contact_list = ContactList(nicks=[LOCAL_ID, 'Alice'])
        self.window_list.active_win = self.window_list.get_window(
            nick_to_pub_key('Alice'))
        self.window_list.active_win.type = WIN_TYPE_CONTACT

        # Test
        self.assertIsNone(
            local_key_rdy(self.ts, self.window_list, self.contact_list))
Exemplo n.º 4
0
class TestLogCommand(TFCTestCase):

    def setUp(self) -> None:
        """Pre-test actions."""
        self.unit_test_dir     = cd_unit_test()
        self.cmd_data          = int_to_bytes(1) + nick_to_pub_key("Bob")
        self.ts                = datetime.now()
        self.window_list       = WindowList(nicks=['Alice', 'Bob'])
        self.window            = self.window_list.get_window(nick_to_pub_key("Bob"))
        self.window.type_print = WIN_TYPE_CONTACT
        self.window.name       = 'Bob'
        self.window.type       = WIN_TYPE_CONTACT
        self.contact_list      = ContactList(nicks=['Alice', 'Bob'])
        self.group_list        = GroupList()
        self.settings          = Settings(software_operation=RX)
        self.master_key        = MasterKey(operation=RX, local_test=True)
        self.args              = (self.ts, self.window_list, self.contact_list,
                                  self.group_list, self.settings, self.master_key)
        self.log_file          = f'{DIR_USER_DATA}{self.settings.software_operation}_logs'
        self.tfc_log_database  = MessageLog(self.log_file, self.master_key.master_key)

        time_float = struct.unpack('<L', bytes.fromhex('08ceae02'))[0]
        self.time  = datetime.fromtimestamp(time_float).strftime("%H:%M:%S.%f")[:-4]

    def tearDown(self) -> None:
        """Post-test actions."""
        cleanup(self.unit_test_dir)
        with ignored(OSError):
            os.remove('Receiver - Plaintext log (None)')

    def test_print(self) -> None:
        # Setup
        os.remove(self.log_file)

        # Test
        self.assert_se(f"No log database available.", log_command, self.cmd_data, *self.args)

    @mock.patch('struct.pack', return_value=bytes.fromhex('08ceae02'))
    def test_export(self, _) -> None:
        # Setup
        for p in assembly_packet_creator(MESSAGE, 'A short message'):
            write_log_entry(p, nick_to_pub_key("Bob"), self.tfc_log_database, origin=ORIGIN_CONTACT_HEADER)

        # Test
        self.assertIsNone(log_command(self.cmd_data, *self.args))

        with open('Receiver - Plaintext log (Bob)') as f:
            data = f.read()

        self.assertEqual(data, f"""\
Log file of 1 most recent message(s) to/from contact Bob
════════════════════════════════════════════════════════════════════════════════
{self.time} Bob: A short message
<End of log file>

""")
Exemplo n.º 5
0
class TestLogCommand(TFCTestCase):
    def setUp(self):
        self.cmd_data = b'*****@*****.**' + US_BYTE + int_to_bytes(1)
        self.ts = datetime.now()
        self.window_list = WindowList(nicks=['Alice', 'Bob'])
        self.window = self.window_list.get_window('*****@*****.**')
        self.window.type_print = 'contact'
        self.contact_list = ContactList(nicks=['Alice', 'Bob'])
        self.group_list = GroupList()
        self.settings = Settings()
        self.master_key = MasterKey()

        self.time = datetime.fromtimestamp(
            struct.unpack('<L',
                          binascii.unhexlify('08ceae02'))[0]).strftime('%H:%M')
        self.o_struct_pack = struct.pack
        struct.pack = lambda *_: binascii.unhexlify('08ceae02')

    def tearDown(self):
        struct.pack = self.o_struct_pack
        cleanup()
        with ignored(OSError):
            os.remove('UtM - Plaintext log (None)')

    def test_print(self):
        self.assertFR(f"Error: Could not find log database.", log_command,
                      self.cmd_data, None, self.window_list, self.contact_list,
                      self.group_list, self.settings, self.master_key)

    def test_export(self):
        # Setup
        for p in assembly_packet_creator(MESSAGE, b'A short message'):
            write_log_entry(p,
                            '*****@*****.**',
                            self.settings,
                            self.master_key,
                            origin=ORIGIN_CONTACT_HEADER)

        # Test
        self.assertIsNone(
            log_command(self.cmd_data, self.ts, self.window_list,
                        self.contact_list, self.group_list, self.settings,
                        self.master_key))

        with open('UtM - Plaintext log (None)') as f:
            data = f.read()

        self.assertEqual(
            data, f"""\
Logfile of 1 most recent message to/from None
════════════════════════════════════════════════════════════════════════════════
{self.time}   Bob: A short message
<End of logfile>

""")
Exemplo n.º 6
0
class TestResetActiveWindow(unittest.TestCase):
    def setUp(self):
        self.cmd_data = b'*****@*****.**'
        self.window_list = WindowList()
        self.window_list.windows = [
            RxWindow(uid='*****@*****.**', name='Alice'),
            RxWindow(uid='*****@*****.**', name='Bob')
        ]
        self.window = self.window_list.get_window('*****@*****.**')
        self.window.message_log = [(datetime.now(), 'Hi Bob',
                                    '*****@*****.**', ORIGIN_CONTACT_HEADER)]

    def test_screen_reset(self):
        self.assertEqual(len(self.window.message_log), 1)
        self.assertIsNone(reset_active_window(self.cmd_data, self.window_list))
        self.assertEqual(len(self.window.message_log), 0)
Exemplo n.º 7
0
class TestChangeNick(TFCTestCase):
    def setUp(self):
        self.ts = datetime.now()
        self.contact_list = ContactList(nicks=['Alice'])
        self.window_list = WindowList(contact_list=self.contact_list)
        self.group_list = GroupList()

    def test_nick_change(self):
        # Setup
        cmd_data = b'*****@*****.**' + US_BYTE + b'Alice_'

        # Test
        self.assertIsNone(
            change_nick(cmd_data, self.ts, self.window_list,
                        self.contact_list))
        self.assertEqual(
            self.contact_list.get_contact('*****@*****.**').nick, 'Alice_')
        self.assertEqual(
            self.window_list.get_window('*****@*****.**').name, 'Alice_')
Exemplo n.º 8
0
class TestChContactSetting(TFCTestCase):

    def setUp(self):
        self.ts           = datetime.fromtimestamp(1502750000)
        self.contact_list = ContactList(nicks=['Alice', 'Bob'])
        self.group_list   = GroupList(groups=['test_group', 'test_group2'])
        self.window_list  = WindowList(contact_list=self.contact_list,
                                       group_list=self.group_list)
        self.args         = self.ts, self.window_list, self.contact_list, self.group_list

    def test_invalid_window_raises_fr(self):
        # Setup
        cmd_data          = ENABLE + nick_to_pub_key("Bob")
        header            = CH_LOGGING
        self.contact_list = ContactList(nicks=['Alice'])
        self.window_list  = WindowList(contact_list=self.contact_list,
                                       group_list=self.group_list)
        # Test
        self.assert_fr(f"Error: Found no window for '{nick_to_short_address('Bob')}'.",
                       ch_contact_s, cmd_data, *self.args, header)

    def test_setting_change_contact(self):
        # Setup
        self.window                 = self.window_list.get_window(nick_to_pub_key("Bob"))
        self.window.type            = WIN_TYPE_CONTACT
        self.window.type_print      = 'contact'
        self.window.window_contacts = self.contact_list.contacts
        bob                         = self.contact_list.get_contact_by_address_or_nick("Bob")

        # Test
        for attr, header in [('log_messages', CH_LOGGING),
                             ('notifications', CH_NOTIFY),
                             ('file_reception', CH_FILE_RECV)]:
            for s in [ENABLE, ENABLE, DISABLE, DISABLE]:
                cmd_data = s + nick_to_pub_key("Bob")
                self.assertIsNone(ch_contact_s(cmd_data, *self.args, header))
                self.assertEqual(bob.__getattribute__(attr), (s == ENABLE))

    def test_setting_change_group(self):
        # Setup
        self.window                 = self.window_list.get_window(group_name_to_group_id('test_group'))
        self.window.type            = WIN_TYPE_GROUP
        self.window.type_print      = 'group'
        self.window.window_contacts = self.group_list.get_group('test_group').members

        # Test
        for attr, header in [('log_messages', CH_LOGGING),
                             ('notifications', CH_NOTIFY),
                             ('file_reception', CH_FILE_RECV)]:
            for s in [ENABLE, ENABLE, DISABLE, DISABLE]:
                cmd_data = s + group_name_to_group_id('test_group')
                self.assertIsNone(ch_contact_s(cmd_data, *self.args, header))

                if header in [CH_LOGGING, CH_NOTIFY]:
                    self.assertEqual(self.group_list.get_group('test_group').__getattribute__(attr), (s == ENABLE))

                if header == CH_FILE_RECV:
                    for m in self.group_list.get_group('test_group').members:
                        self.assertEqual(m.file_reception, (s == ENABLE))

    def test_setting_change_all(self):
        # Setup
        self.window                 = self.window_list.get_window(nick_to_pub_key("Bob"))
        self.window.type            = WIN_TYPE_CONTACT
        self.window.type_print      = 'contact'
        self.window.window_contacts = self.contact_list.contacts

        # Test
        for attr, header in [('log_messages', CH_LOGGING),
                             ('notifications', CH_NOTIFY),
                             ('file_reception', CH_FILE_RECV)]:
            for s in [ENABLE, ENABLE, DISABLE, DISABLE]:
                cmd_data = s.upper() + US_BYTE
                self.assertIsNone(ch_contact_s(cmd_data, *self.args, header))

                if header in [CH_LOGGING, CH_NOTIFY]:
                    for c in self.contact_list.get_list_of_contacts():
                        self.assertEqual(c.__getattribute__(attr), (s == ENABLE))
                    for g in self.group_list.groups:
                        self.assertEqual(g.__getattribute__(attr), (s == ENABLE))

                if header == CH_FILE_RECV:
                    for c in self.contact_list.get_list_of_contacts():
                        self.assertEqual(c.__getattribute__(attr), (s == ENABLE))
Exemplo n.º 9
0
class ProcessAssembledFile(TFCTestCase):

    def setUp(self) -> None:
        """Pre-test actions."""
        self.unit_test_dir = cd_unit_test()
        self.ts            = datetime.now()
        self.onion_pub_key = nick_to_pub_key('Alice')
        self.nick          = 'Alice'
        self.settings      = Settings()
        self.window_list   = WindowList(nick=['Alice', 'Bob'])
        self.key           = os.urandom(SYMMETRIC_KEY_LENGTH)
        self.args          = self.onion_pub_key, self.nick, self.settings, self.window_list

    def tearDown(self) -> None:
        """Post-test actions."""
        cleanup(self.unit_test_dir)

    def test_invalid_structure_raises_soft_error(self) -> None:
        # Setup
        payload = b'testfile.txt'

        # Test
        self.assert_se("Error: Received file had an invalid structure.",
                       process_assembled_file, self.ts, payload, *self.args)

    def test_invalid_encoding_raises_soft_error(self) -> None:
        # Setup
        payload = UNDECODABLE_UNICODE + US_BYTE + b'file_data'

        # Test
        self.assert_se("Error: Received file name had an invalid encoding.",
                       process_assembled_file, self.ts, payload, *self.args)

    def test_invalid_name_raises_soft_error(self) -> None:
        # Setup
        payload = b'\x01filename' + US_BYTE + b'file_data'

        # Test
        self.assert_se("Error: Received file had an invalid name.",
                       process_assembled_file, self.ts, payload, *self.args)

    def test_slash_in_file_name_raises_soft_error(self) -> None:
        # Setup
        payload = b'file/name' + US_BYTE + b'file_data'

        # Test
        self.assert_se("Error: Received file had an invalid name.",
                       process_assembled_file, self.ts, payload, *self.args)

    def test_invalid_key_raises_soft_error(self) -> None:
        # Setup
        payload = b'testfile.txt' + US_BYTE + b'file_data'

        # Test
        self.assert_se("Error: Received file had an invalid key.",
                       process_assembled_file, self.ts, payload, *self.args)

    def test_decryption_fail_raises_soft_error(self) -> None:
        # Setup
        file_data = encrypt_and_sign(b'file_data', self.key)[::-1]
        payload   = b'testfile.txt' + US_BYTE + file_data

        # Test
        self.assert_se("Error: Decryption of file data failed.",
                       process_assembled_file, self.ts, payload, *self.args)

    def test_invalid_compression_raises_soft_error(self) -> None:
        # Setup
        compressed = zlib.compress(b'file_data', level=COMPRESSION_LEVEL)[::-1]
        file_data  = encrypt_and_sign(compressed, self.key) + self.key
        payload    = b'testfile.txt' + US_BYTE + file_data

        # Test
        self.assert_se("Error: Decompression of file data failed.",
                       process_assembled_file, self.ts, payload, *self.args)

    def test_successful_reception(self) -> None:
        # Setup
        compressed = zlib.compress(b'file_data', level=COMPRESSION_LEVEL)
        file_data  = encrypt_and_sign(compressed, self.key) + self.key
        payload    = b'testfile.txt' + US_BYTE + file_data

        # Test
        self.assertIsNone(process_assembled_file(self.ts, payload, *self.args))
        self.assertTrue(os.path.isfile(f'{DIR_RECV_FILES}Alice/testfile.txt'))

    def test_successful_reception_during_traffic_masking(self) -> None:
        # Setup
        self.settings.traffic_masking = True
        self.window_list.active_win   = self.window_list.get_window(nick_to_pub_key('Bob'))

        compressed = zlib.compress(b'file_data', level=COMPRESSION_LEVEL)
        file_data  = encrypt_and_sign(compressed, self.key) + self.key
        payload    = b'testfile.txt' + US_BYTE + file_data

        # Test
        self.assertIsNone(process_assembled_file(self.ts, payload, *self.args))
        self.assertEqual(self.window_list.get_window(nick_to_pub_key('Bob')).message_log[0][1],
                         "Stored file from Alice as 'testfile.txt'.")
        self.assertTrue(os.path.isfile(f'{DIR_RECV_FILES}Alice/testfile.txt'))
Exemplo n.º 10
0
class TestProcessFile(TFCTestCase):

    def setUp(self) -> None:
        """Pre-test actions."""
        self.unit_test_dir = cd_unit_test()
        self.ts            = datetime.now()
        self.account       = nick_to_pub_key('Alice')
        self.file_key      = SYMMETRIC_KEY_LENGTH*b'a'
        self.file_ct       = encrypt_and_sign(50 * b'a', key=self.file_key)
        self.contact_list  = ContactList(nicks=['Alice'])
        self.window_list   = WindowList()
        self.settings      = Settings()
        self.args          = self.file_key, self.contact_list, self.window_list, self.settings

    def tearDown(self) -> None:
        """Post-test actions."""
        cleanup(self.unit_test_dir)

    def test_invalid_key_raises_soft_error(self) -> None:
        self.file_key = SYMMETRIC_KEY_LENGTH * b'f'
        self.args     = self.file_key, self.contact_list, self.window_list, self.settings

        self.assert_se("Error: Decryption key for file from Alice was invalid.",
                       process_file, self.ts, self.account, self.file_ct, *self.args)

    def test_invalid_compression_raises_soft_error(self) -> None:
        compressed = zlib.compress(b'file_data', level=COMPRESSION_LEVEL)[::-1]
        file_data  = encrypt_and_sign(compressed, self.file_key)

        self.assert_se("Error: Failed to decompress file from Alice.",
                       process_file, self.ts, self.account, file_data, *self.args)

    @mock.patch('time.sleep', return_value=None)
    def test_invalid_file_name_raises_soft_error(self, _: Any) -> None:
        compressed = zlib.compress(UNDECODABLE_UNICODE + b'file_data', level=COMPRESSION_LEVEL)
        file_data  = encrypt_and_sign(compressed, self.file_key)

        self.assert_se("Error: Name of file from Alice had an invalid encoding.",
                       process_file, self.ts, self.account, file_data, *self.args)

    @mock.patch('time.sleep', return_value=None)
    def test_non_printable_name_raises_soft_error(self, _: Any) -> None:
        compressed = zlib.compress(str_to_bytes("file\x01") + b'file_data', level=COMPRESSION_LEVEL)
        file_data  = encrypt_and_sign(compressed, self.file_key)

        self.assert_se("Error: Name of file from Alice was invalid.",
                       process_file, self.ts, self.account, file_data, *self.args)

    @mock.patch('time.sleep', return_value=None)
    def test_slash_in_name_raises_soft_error(self, _: Any) -> None:
        compressed = zlib.compress(str_to_bytes("Alice/file.txt") + b'file_data', level=COMPRESSION_LEVEL)
        file_data  = encrypt_and_sign(compressed, self.file_key)

        self.assert_se("Error: Name of file from Alice was invalid.",
                       process_file, self.ts, self.account, file_data, *self.args)

    @mock.patch('time.sleep', return_value=None)
    def test_successful_storage_of_file(self, _: Any) -> None:
        compressed = zlib.compress(str_to_bytes("test_file.txt") + b'file_data', level=COMPRESSION_LEVEL)
        file_data  = encrypt_and_sign(compressed, self.file_key)

        self.assertIsNone(process_file(self.ts, self.account, file_data, *self.args))

    @mock.patch('time.sleep', return_value=None)
    def test_successful_storage_during_traffic_masking(self, _: Any) -> None:
        # Setup
        self.settings.traffic_masking = True
        self.window_list.active_win   = self.window_list.get_window(nick_to_pub_key('Bob'))

        compressed = zlib.compress(str_to_bytes("testfile.txt") + b'file_data', level=COMPRESSION_LEVEL)
        file_data  = encrypt_and_sign(compressed, self.file_key)

        self.assertIsNone(process_file(self.ts, self.account, file_data, *self.args))

        self.assertEqual(self.window_list.get_window(nick_to_pub_key('Bob')).message_log[0][1],
                         "Stored file from Alice as 'testfile.txt'.")

        self.assertTrue(os.path.isfile(f'{DIR_RECV_FILES}Alice/testfile.txt'))
Exemplo n.º 11
0
class TestProcessLocalKey(TFCTestCase):

    kek = os.urandom(SYMMETRIC_KEY_LENGTH)
    new_kek = os.urandom(SYMMETRIC_KEY_LENGTH)

    def setUp(self):
        self.contact_list = ContactList(nicks=[LOCAL_ID, 'Alice'])
        self.key_list = KeyList(nicks=[LOCAL_ID, 'Alice'])
        self.window_list = WindowList(nicks=[LOCAL_ID, 'Alice'])
        self.settings = Settings()
        self.ts = datetime.now()
        self.kdk_hashes = list()
        self.packet_hashes = list()
        self.l_queue = Queue()
        self.key = os.urandom(SYMMETRIC_KEY_LENGTH)
        self.hek = os.urandom(SYMMETRIC_KEY_LENGTH)
        self.conf_code = os.urandom(CONFIRM_CODE_LENGTH)
        self.packet = encrypt_and_sign(self.key + self.hek + self.conf_code,
                                       key=self.kek)
        self.args = (self.window_list, self.contact_list, self.key_list,
                     self.settings, self.kdk_hashes, self.packet_hashes,
                     self.l_queue)

    def tearDown(self):
        tear_queue(self.l_queue)

    @mock.patch('tkinter.Tk', return_value=MagicMock())
    @mock.patch('time.sleep', return_value=None)
    @mock.patch(
        'builtins.input',
        return_value='5KfgdgUvseWfNkoUPWSvxMPNStu5wBBxyjz1zpZtLEjk7ZvwEAT')
    def test_invalid_decryption_key_raises_fr(self, *_):
        # Setup
        packet = b''
        self.key_list.keysets = []

        # Test
        self.assert_fr("Error: Incorrect key decryption key.",
                       process_local_key, self.ts, packet, *self.args)

    @mock.patch('tkinter.Tk', return_value=MagicMock())
    @mock.patch('time.sleep', return_value=None)
    @mock.patch('builtins.input',
                side_effect=[
                    '5KfgdgUvseWfNkoUPWSvxMPNStu5wBBxyjz1zpZtLEjk7ZvwEAT',
                    b58encode(kek)
                ])
    def test_successful_local_key_processing_with_existing_local_key(self, *_):
        self.assert_fr("Error: Incorrect key decryption key.",
                       process_local_key, self.ts, self.packet, *self.args)
        self.assertIsNone(process_local_key(self.ts, self.packet, *self.args))

    @mock.patch('tkinter.Tk', return_value=MagicMock())
    @mock.patch('time.sleep', return_value=None)
    @mock.patch('builtins.input', return_value=b58encode(kek))
    def test_successful_local_key_processing_existing_bootstrap(self, *_):
        # Setup
        self.key_list.keysets = []

        # Test
        self.assertIsNone(process_local_key(self.ts, self.packet, *self.args))
        self.assertEqual(self.window_list.active_win.uid, WIN_UID_LOCAL)

    @mock.patch('tkinter.Tk', return_value=MagicMock())
    @mock.patch('time.sleep', return_value=None)
    @mock.patch('builtins.input', side_effect=KeyboardInterrupt)
    def test_keyboard_interrupt_raises_fr(self, *_):
        # Setup
        self.window_list.active_win = self.window_list.get_window(
            nick_to_pub_key('Alice'))

        # Test
        self.assert_fr("Local key setup aborted.", process_local_key, self.ts,
                       bytes(SYMMETRIC_KEY_LENGTH), *self.args)

    @mock.patch('tkinter.Tk', return_value=MagicMock())
    @mock.patch('os.system', return_value=None)
    @mock.patch('time.sleep', return_value=None)
    @mock.patch('builtins.input',
                side_effect=[
                    b58encode(kek),
                    b58encode(kek),
                    b58encode(kek),
                    b58encode(new_kek)
                ])
    def test_old_local_key_packet_raises_fr(self, *_):
        # Setup
        self.key_list.keysets = []
        new_key = os.urandom(SYMMETRIC_KEY_LENGTH)
        new_hek = os.urandom(SYMMETRIC_KEY_LENGTH)
        new_conf_code = os.urandom(CONFIRM_CODE_LENGTH)
        new_packet = encrypt_and_sign(new_key + new_hek + new_conf_code,
                                      key=self.new_kek)

        # Test
        self.assertIsNone(process_local_key(self.ts, self.packet, *self.args))
        self.assert_fr("Error: Received old local key packet.",
                       process_local_key, self.ts, self.packet, *self.args)
        self.assertIsNone(process_local_key(self.ts, new_packet, *self.args))

    @mock.patch(
        'tkinter.Tk',
        side_effect=[
            MagicMock(
                clipboard_get=MagicMock(return_value=b58encode(new_kek)),
                clipboard_clear=MagicMock(side_effect=[tkinter.TclError]))
        ])
    @mock.patch('os.system', return_value=None)
    @mock.patch('time.sleep', return_value=None)
    @mock.patch('builtins.input', side_effect=[b58encode(new_kek)])
    def test_loading_local_key_from_queue(self, *_):
        # Setup
        self.key_list.keysets = []
        new_key = os.urandom(SYMMETRIC_KEY_LENGTH)
        new_hek = os.urandom(SYMMETRIC_KEY_LENGTH)
        new_conf_code = os.urandom(CONFIRM_CODE_LENGTH)
        new_packet = encrypt_and_sign(new_key + new_hek + new_conf_code,
                                      key=self.new_kek)
        next_packet = os.urandom(len(new_packet))
        first_packet = os.urandom(len(new_packet))
        self.l_queue.put((datetime.now(), first_packet))
        self.l_queue.put((datetime.now(), new_packet))
        self.l_queue.put((datetime.now(), next_packet))

        # Test
        self.assertEqual(self.l_queue.qsize(), 3)
        self.assertIsNone(process_local_key(self.ts, self.packet, *self.args))
        self.assertEqual(self.l_queue.qsize(), 1)
Exemplo n.º 12
0
class TestContactSetting(TFCTestCase):
    def setUp(self):
        self.ts = datetime.fromtimestamp(1502750000)
        self.contact_list = ContactList(nicks=['Alice', 'Bob'])
        self.group_list = GroupList(groups=['test_group', 'test_group2'])
        self.window_list = WindowList(contact_list=self.contact_list,
                                      group_list=self.group_list)

    def test_invalid_window_raises_fr(self):
        # Setup
        cmd_data = ENABLE + US_BYTE + b'*****@*****.**'
        header = CHANGE_LOGGING_HEADER
        self.contact_list = ContactList(nicks=['Alice'])
        self.window_list = WindowList(contact_list=self.contact_list,
                                      group_list=self.group_list)
        # Test
        self.assertFR("Error: Found no window for '*****@*****.**'",
                      contact_setting, cmd_data, self.ts, self.window_list,
                      self.contact_list, self.group_list, header)

    def test_setting_change_contact(self):
        # Setup
        self.window = self.window_list.get_window('*****@*****.**')
        self.window.type = WIN_TYPE_CONTACT
        self.window.type_print = 'contact'
        self.window.window_contacts = self.contact_list.contacts

        # Test
        for attr, header in [('log_messages', CHANGE_LOGGING_HEADER),
                             ('notifications', CHANGE_NOTIFY_HEADER),
                             ('file_reception', CHANGE_FILE_R_HEADER)]:
            for s in [ENABLE, ENABLE, DISABLE, DISABLE]:
                cmd_data = s + US_BYTE + b'*****@*****.**'
                self.assertIsNone(
                    contact_setting(cmd_data, self.ts, self.window_list,
                                    self.contact_list, self.group_list,
                                    header))
                self.assertEqual(
                    self.contact_list.get_contact(
                        '*****@*****.**').__getattribute__(attr),
                    (s == ENABLE))

    def test_setting_change_group(self):
        # Setup
        self.window = self.window_list.get_window('test_group')
        self.window.type = WIN_TYPE_GROUP
        self.window.type_print = 'group'
        self.window.window_contacts = self.group_list.get_group(
            'test_group').members

        # Test
        for attr, header in [('log_messages', CHANGE_LOGGING_HEADER),
                             ('notifications', CHANGE_NOTIFY_HEADER),
                             ('file_reception', CHANGE_FILE_R_HEADER)]:
            for s in [ENABLE, ENABLE, DISABLE, DISABLE]:
                cmd_data = s + US_BYTE + b'test_group'
                self.assertIsNone(
                    contact_setting(cmd_data, self.ts, self.window_list,
                                    self.contact_list, self.group_list,
                                    header))

                if header in [CHANGE_LOGGING_HEADER, CHANGE_NOTIFY_HEADER]:
                    self.assertEqual(
                        self.group_list.get_group(
                            'test_group').__getattribute__(attr),
                        (s == ENABLE))

                if header == CHANGE_FILE_R_HEADER:
                    for m in self.group_list.get_group('test_group').members:
                        self.assertEqual(m.file_reception, (s == ENABLE))

    def test_setting_change_all(self):
        # Setup
        self.window = self.window_list.get_window('*****@*****.**')
        self.window.type = WIN_TYPE_CONTACT
        self.window.type_print = 'contact'
        self.window.window_contacts = self.contact_list.contacts

        # Test
        for attr, header in [('log_messages', CHANGE_LOGGING_HEADER),
                             ('notifications', CHANGE_NOTIFY_HEADER),
                             ('file_reception', CHANGE_FILE_R_HEADER)]:
            for s in [ENABLE, ENABLE, DISABLE, DISABLE]:
                cmd_data = s.upper() + US_BYTE
                self.assertIsNone(
                    contact_setting(cmd_data, self.ts, self.window_list,
                                    self.contact_list, self.group_list,
                                    header))

                if header in [CHANGE_LOGGING_HEADER, CHANGE_NOTIFY_HEADER]:
                    for c in self.contact_list.get_list_of_contacts():
                        self.assertEqual(c.__getattribute__(attr),
                                         (s == ENABLE))
                    for g in self.group_list.groups:
                        self.assertEqual(g.__getattribute__(attr),
                                         (s == ENABLE))

                if header == CHANGE_FILE_R_HEADER:
                    for c in self.contact_list.get_list_of_contacts():
                        self.assertEqual(c.__getattribute__(attr),
                                         (s == ENABLE))