"""Integration tests for the chat layer: rooms, profiles and private messages.""" from __future__ import annotations import asyncio import json import os import sys import tempfile import unittest from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from dhtchat import crypto, protocol # noqa: E402 from dhtchat.chat import ( # noqa: E402 ChatService, _sign_record, decode_log, verify_record, ) from dhtchat.identity import Identity # noqa: E402 from dhtchat.node import DhtNode # noqa: E402 class Peer: """A node plus its chat service and the events both produced.""" def __init__(self, node: DhtNode, chat: ChatService, events: list[dict]) -> None: self.node = node self.chat = chat self.events = events @property def nickname(self) -> str: return self.chat.nickname def of_type(self, kind: str) -> list[dict]: return [event for event in self.events if event.get("type") == kind] def texts(self, kind: str = "direct_message") -> list[str]: return [event["text"] for event in self.of_type(kind)] class ChatServiceTests(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self) -> None: self._tmp = tempfile.TemporaryDirectory() self.tmp = Path(self._tmp.name) self.peers: list[Peer] = [] async def asyncTearDown(self) -> None: for peer in self.peers: try: await peer.chat.stop() except Exception: pass try: await peer.node.stop() except Exception: pass self._tmp.cleanup() async def make_peer(self, nickname: str, start_chat: bool = True) -> Peer: node = DhtNode(Identity.generate(), host="127.0.0.1", port=0) await node.start() events: list[dict] = [] chat = ChatService( node, node.identity, self.tmp / nickname, events.append, nickname=nickname ) peer = Peer(node, chat, events) self.peers.append(peer) if start_chat: await chat.start() return peer async def link(self, follower: Peer, anchor: Peer) -> None: self.assertEqual(await follower.node.bootstrap([anchor.node.address]), 1) await follower.chat.announce_profile() await anchor.chat.announce_profile() async def join_and_sync(self, *peers: Peer, room: str) -> None: for peer in peers: peer.chat.join_room(room) await asyncio.sleep(0) for peer in peers: await peer.chat._announce_membership(peer.chat.rooms[room]) for peer in peers: await peer.chat._sync_room(peer.chat.rooms[room]) # -- profiles ------------------------------------------------------ async def test_profile_is_published_and_verified(self) -> None: alice = await self.make_peer("alice") bob = await self.make_peer("bob") await self.link(bob, alice) profile = await bob.chat.resolve_nickname("alice") self.assertIsNotNone(profile) self.assertEqual(profile["node"], alice.node.identity.node_id_hex) self.assertEqual(profile["pub"], alice.node.identity.public_hex) self.assertEqual(profile["port"], alice.node.bound_port) async def test_resolve_nickname_returns_none_for_stranger(self) -> None: alice = await self.make_peer("alice") self.assertIsNone(await alice.chat.resolve_nickname("nobody")) async def test_tampered_profile_is_rejected(self) -> None: signer = Identity.generate() record = { "nick": "mallory", "pub": signer.public_hex, "node": signer.node_id_hex, "host": "1.2.3.4", "port": 1234, "ts": 1.0, } signed = _sign_record(record, signer) self.assertIsNotNone(verify_record(signed)) signed["port"] = 9999 self.assertIsNone(verify_record(signed)) # -- rooms --------------------------------------------------------- async def test_room_message_reaches_member(self) -> None: alice = await self.make_peer("alice") bob = await self.make_peer("bob") await self.link(bob, alice) await self.join_and_sync(alice, bob, room="大厅") self.assertIn(bob.nickname, [m["nick"] for m in alice.chat.rooms["大厅"].member_list()]) await alice.chat.send_room_message("大厅", "大家好") await asyncio.sleep(0.3) self.assertEqual(bob.texts("room_message"), ["大家好"]) self.assertFalse(bob.of_type("room_message")[0]["own"]) async def test_late_joiner_replays_history_from_dht(self) -> None: alice = await self.make_peer("alice") bob = await self.make_peer("bob") await self.link(bob, alice) await self.join_and_sync(alice, bob, room="大厅") await alice.chat.send_room_message("大厅", "历史上的第一条") carol = await self.make_peer("carol") await self.link(carol, alice) carol.chat.join_room("大厅") await carol.chat._sync_room(carol.chat.rooms["大厅"], pull_history=True) self.assertEqual(carol.texts("room_message"), ["历史上的第一条"]) self.assertTrue(carol.of_type("room_message")[0]["history"]) async def test_room_rejects_forged_record(self) -> None: alice = await self.make_peer("alice") bob = await self.make_peer("bob") await self.link(bob, alice) await self.join_and_sync(alice, bob, room="大厅") forged = { "id": protocol.new_id(), "room": "大厅", "nick": "alice", "pub": alice.node.identity.public_hex, "node": alice.node.identity.node_id_hex, "text": "假的", "ts": 1.0, "sig": "00" * 64, } packet = bob.node._base(protocol.ROOM_MSG) packet["room"] = "大厅" packet["record"] = forged bob.node.send_raw(packet, alice.node.address) await asyncio.sleep(0.3) self.assertEqual(alice.texts("room_message"), []) async def test_room_log_is_merged_across_replicas(self) -> None: alice = await self.make_peer("alice") bob = await self.make_peer("bob") await self.link(bob, alice) await self.join_and_sync(alice, bob, room="大厅") await alice.chat.send_room_message("大厅", "A") await bob.chat.send_room_message("大厅", "B") await asyncio.sleep(0.2) blobs = await alice.node.find_value("log/room/大厅") texts = {item.get("text") for item in decode_log(blobs)} self.assertEqual(texts, {"A", "B"}) async def test_room_sync_picks_up_messages_missed_by_broadcast(self) -> None: """A member the sender did not know yet still gets the message.""" alice = await self.make_peer("alice") bob = await self.make_peer("bob") await self.link(bob, alice) await self.join_and_sync(alice, bob, room="大厅") await alice.chat.send_room_message("大厅", "广播丢了") room = bob.chat.rooms["大厅"] room.seen.clear() room.messages.clear() bob.events.clear() await bob.chat._sync_room(room) self.assertEqual(bob.texts("room_message"), ["广播丢了"]) self.assertFalse(bob.of_type("room_message")[0]["history"]) async def test_room_history_backlog_is_not_replayed_again(self) -> None: alice = await self.make_peer("alice") bob = await self.make_peer("bob") await self.link(bob, alice) await self.join_and_sync(alice, bob, room="大厅") for index in range(45): await alice.chat.send_room_message("大厅", f"消息{index}") carol = await self.make_peer("carol") await self.link(carol, alice) carol.chat.join_room("大厅") await carol.chat._sync_room(carol.chat.rooms["大厅"], pull_history=True) replayed = carol.of_type("room_message") self.assertEqual(len(replayed), 40) self.assertTrue(all(event["history"] for event in replayed)) carol.events.clear() await carol.chat._sync_room(carol.chat.rooms["大厅"]) self.assertEqual(carol.of_type("room_message"), []) # -- private messages --------------------------------------------- async def test_private_message_over_direct_connection(self) -> None: alice = await self.make_peer("alice") bob = await self.make_peer("bob") await self.link(bob, alice) result = await alice.chat.send_direct("bob", "悄悄话") await asyncio.sleep(0.2) self.assertTrue(result["delivered"]) self.assertEqual(bob.texts("direct_message"), ["悄悄话"]) self.assertEqual(alice.texts("direct_message"), ["悄悄话"]) self.assertTrue(alice.of_type("direct_message")[0]["own"]) self.assertFalse(bob.of_type("direct_message")[0]["own"]) async def test_private_message_falls_back_to_overlay_routing(self) -> None: alice = await self.make_peer("alice") bob = await self.make_peer("bob") await self.link(bob, alice) # Pretend the profile has no usable address: only the DHT can help. alice.chat._peer_address = lambda profile, node: None result = await alice.chat.send_direct("bob", "走路由") await asyncio.sleep(0.3) self.assertTrue(result["delivered"]) self.assertEqual(bob.texts("direct_message"), ["走路由"]) async def test_ciphertext_for_another_recipient_is_rejected(self) -> None: alice = await self.make_peer("alice") bob = await self.make_peer("bob") await self.link(bob, alice) shared = alice.node.identity.shared_secret_with(bob.node.identity.public) body = json.dumps({"text": "给别人的"}).encode() wrong_aad = ( b"dhtchat-dm/v1" + Identity.generate().node_id + bob.node.identity.node_id ) blob = crypto.aead_encrypt(shared, body, wrong_aad) envelope = alice.node._base(protocol.DIRECT_MSG) envelope["id"] = protocol.new_id() envelope["dst"] = bob.node.identity.node_id_hex envelope["blob"] = protocol.b64encode(blob) alice.node.send_raw(envelope, bob.node.address) await asyncio.sleep(0.3) self.assertEqual(bob.texts("direct_message"), []) self.assertTrue( any("无法解密" in event.get("text", "") for event in bob.of_type("log")) ) async def test_duplicate_private_message_is_ignored(self) -> None: alice = await self.make_peer("alice") bob = await self.make_peer("bob") await self.link(bob, alice) shared = alice.node.identity.shared_secret_with(bob.node.identity.public) aad = ( b"dhtchat-dm/v1" + alice.node.identity.node_id + bob.node.identity.node_id ) body = json.dumps({"from_nick": "alice", "text": "只此一次"}, ensure_ascii=False).encode() envelope = alice.node._base(protocol.DIRECT_MSG) envelope["id"] = protocol.new_id() envelope["dst"] = bob.node.identity.node_id_hex envelope["blob"] = protocol.b64encode(crypto.aead_encrypt(shared, body, aad)) self.assertTrue(alice.node.send_raw(envelope, bob.node.address)) await asyncio.sleep(0.25) self.assertTrue(alice.node.send_raw(envelope, bob.node.address)) await asyncio.sleep(0.25) self.assertEqual(bob.texts("direct_message"), ["只此一次"]) async def test_private_message_reaches_offline_peer_through_inbox(self) -> None: alice = await self.make_peer("alice") proxy = await self.make_peer("proxy") await self.link(proxy, alice) bob_identity = Identity.generate() alice.chat._remember_profile( { "nick": "bob", "node": bob_identity.node_id_hex, "pub": bob_identity.public_hex, "host": "", "port": "", "ts": 1e12, } ) alice.chat._peer_address = lambda profile, node: None result = await alice.chat.send_direct("bob", "离线留言") self.assertFalse(result["delivered"]) inbox = await proxy.node.find_value(f"log/inbox/{bob_identity.node_id_hex}") self.assertEqual(len(inbox), 1) self.assertEqual(len(decode_log(inbox)), 1) # Now bob comes online and drains his inbox. bob_node = DhtNode(bob_identity, host="127.0.0.1", port=0) await bob_node.start() events: list[dict] = [] bob_chat = ChatService( bob_node, bob_identity, self.tmp / "bob", events.append, nickname="bob" ) bob = Peer(bob_node, bob_chat, events) self.peers.append(bob) await bob_chat.start() self.assertIn(await bob_node.bootstrap([proxy.node.address]), (0, 1)) await bob_chat._poll_inbox() self.assertEqual(bob.texts("direct_message"), ["离线留言"]) self.assertEqual(bob.of_type("direct_message")[0]["peer"], "alice") async def test_sending_to_unknown_nickname_reports_failure(self) -> None: alice = await self.make_peer("alice") result = await alice.chat.send_direct("nobody", "在吗") self.assertFalse(result["delivered"]) self.assertIn("找不到", result["reason"]) async def test_room_history_is_capped_and_deduplicated(self) -> None: alice = await self.make_peer("alice") alice.chat.join_room("大厅") room = alice.chat.rooms["大厅"] for index in range(5): await alice.chat.send_room_message("大厅", f"消息{index}") self.assertEqual(len(room.messages), 5) self.assertEqual(len(room.seen), 5) record = alice.chat._member_record(room) self.assertIsNotNone(verify_record(record)) self.assertEqual(record["room"], "大厅") if __name__ == "__main__": unittest.main()