From c6ef3411e3163444dfb96141ed181aebf3e8bfa5 Mon Sep 17 00:00:00 2001 From: ABuljko Date: Sat, 3 Oct 2026 18:37:59 +0200 Subject: [PATCH 1/6] Harden login against timing leaks and brute force --- README.md | 1 + chatroom_db.py | 9 +++- server.py | 69 ++++++++++++++++++++++-- tests/test_db.py | 16 ++++++ tests/test_server.py | 123 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 214 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 9a34d61..de8a44e 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ python main.py ## Good to know - To start over with an empty database, run `python initialize_db.py`. +- After 5 failed logins, each retry waits longer, up to a minute. - The connection is encrypted with TLS. The app only talks to a server whose certificate matches `cert.pem`. - To chat across machines, run `python make_cert.py --host `, start the server with `--host 0.0.0.0`, and give each user a copy of `cert.pem` (never `key.pem`). They start the app with `--host `. diff --git a/chatroom_db.py b/chatroom_db.py index 7491316..16f4088 100644 --- a/chatroom_db.py +++ b/chatroom_db.py @@ -79,10 +79,17 @@ def add_user(username, password): return True +# Checked when the user doesn't exist, so that takes as long as a wrong password. +_DUMMY_HASH = hash_password("not a real password") + + def check_user(username, password): with connect() as conn: row = conn.execute("SELECT password FROM users WHERE username = ?", (username,)).fetchone() - return row is not None and verify_password(password, row[0]) + if row is None: + verify_password(password, _DUMMY_HASH) + return False + return verify_password(password, row[0]) def user_exists(username): diff --git a/server.py b/server.py index 0e0e921..fb56793 100644 --- a/server.py +++ b/server.py @@ -2,12 +2,14 @@ import argparse import json +import math import queue import re import socket import ssl import sys import threading +import time from pathlib import Path import chatroom_db as db @@ -22,6 +24,10 @@ MAX_MESSAGE = 2000 MIN_PASSWORD, MAX_PASSWORD = 8, 128 USERNAME_RE = re.compile(r"[A-Za-z0-9_.-]{1,32}") +LOGIN_FREE_FAILURES = 5 +LOGIN_MAX_WAIT = 60 +LOGIN_FORGET = 15 * 60 +LOGIN_MAX_TRACKED = 10_000 clients = {} clients_lock = threading.Lock() @@ -38,8 +44,9 @@ class BadRequest(Exception): class Connection: """Sends from a bounded queue on its own thread, so a slow client can't block others.""" - def __init__(self, sock): + def __init__(self, sock, host=None): self.sock = sock + self.host = host self.reader = sock.makefile() self.outbox = queue.Queue(MAX_QUEUED) self.writer = threading.Thread(target=self._write_loop, daemon=True) @@ -99,6 +106,56 @@ def close(self): self.sock.close() +class LoginThrottle: + """An attempt counts as a failure until it succeeds, so parallel attempts can't slip past the limit.""" + + def __init__(self, clock=time.monotonic): + self.clock = clock + self.failures = {} # key -> (count, time of the last attempt) + self.lock = threading.Lock() + + def _get(self, key, now): + count, last = self.failures.get(key, (0, now)) + if now - last >= LOGIN_FORGET: + return 0, now + return count, last + + def _wait(self, count, last, now): + if count < LOGIN_FREE_FAILURES: + return 0 + return max(0, last + min(2 ** (count - LOGIN_FREE_FAILURES), LOGIN_MAX_WAIT) - now) + + def begin(self, host, username): + """Return the seconds left to wait, or 0 after counting the attempt.""" + keys = [("ip", host), ("user", username)] + with self.lock: + now = self.clock() + if len(self.failures) > LOGIN_MAX_TRACKED: + self.failures = {key: value for key, value in self.failures.items() if now - value[1] < LOGIN_FORGET} + states = [self._get(key, now) for key in keys] + wait = max(self._wait(count, last, now) for count, last in states) + if wait: + return wait + for key, (count, _) in zip(keys, states, strict=True): + self.failures[key] = (count + 1, now) + return 0 + + def succeeded(self, host, username): + """Undo the IP's count from begin() and clear the username.""" + with self.lock: + self.failures.pop(("user", username), None) + key = ("ip", host) + if key in self.failures: + count, last = self.failures[key] + if count > 1: + self.failures[key] = (count - 1, last) + else: + del self.failures[key] + + +login_throttle = LoginThrottle() + + def send_to(recipient, type_, /, **fields): with clients_lock: conn = clients.get(recipient) @@ -138,11 +195,17 @@ def handle_signup(conn, message): def handle_login(conn, message): if conn.username: raise BadRequest("Already logged in.") - username = text_field(message, "username") + username = username_field(message) password = text_field(message, "password") + if len(password) > MAX_PASSWORD: + raise BadRequest(f"Passwords are at most {MAX_PASSWORD} characters.") + if wait := login_throttle.begin(conn.host, username): + conn.send("login_result", ok=False, error=f"Too many failed logins. Try again in {math.ceil(wait)} s.") + return if not db.check_user(username, password): conn.send("login_result", ok=False, error="Invalid credentials.") return + login_throttle.succeeded(conn.host, username) conn.username = username with clients_lock: previous = clients.get(username) @@ -245,7 +308,7 @@ def handle_client(sock, addr, context): print(f"TLS handshake with {addr} failed: {e}") sock.close() return - conn = Connection(tls.LockedSocket(sock)) + conn = Connection(tls.LockedSocket(sock), addr[0]) try: while (message := conn.receive()) is not None: handlers = USER_HANDLERS if conn.username else GUEST_HANDLERS diff --git a/tests/test_db.py b/tests/test_db.py index 2bc306c..7d8d049 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -33,6 +33,22 @@ def test_add_and_check_user(db_path): assert not db.user_exists("nobody") +def test_unknown_user_still_runs_scrypt(db_path, monkeypatch): + db.add_user("alice", "password1") + calls = [] + real_verify = db.verify_password + + def spy(password, stored): + calls.append(stored) + return real_verify(password, stored) + + monkeypatch.setattr(db, "verify_password", spy) + assert not db.check_user("nobody", "password1") + assert not db.check_user("alice", "wrong-password") + assert len(calls) == 2 + assert calls[0].split("$")[:4] == calls[1].split("$")[:4] + + def test_friend_request_lifecycle(db_path): assert db.add_request("alice", "bob") == "sent" assert db.add_request("alice", "bob") == "pending" diff --git a/tests/test_server.py b/tests/test_server.py index 449731b..c508c8a 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -1,5 +1,9 @@ import json +import pytest + +import server as chat_server + def friends(server, first="alice", second="bob"): a = server().register(first) @@ -155,3 +159,122 @@ def test_odd_but_valid_input_keeps_connection(server): c.expect("error") c.send("signup", username="alice", password="password1") assert c.expect("signup_result")["ok"] + + +def wrong_logins(c, username, times=chat_server.LOGIN_FREE_FAILURES): + for _ in range(times): + c.send("login", username=username, password="wrong-password") + assert c.expect("login_result")["error"] == "Invalid credentials." + + +def test_unknown_user_and_wrong_password_look_the_same(server): + server().register("alice") + c = server() + for username in ["alice", "nobody"]: + c.send("login", username=username, password="wrong-password") + assert c.expect("login_result") == {"type": "login_result", "ok": False, "error": "Invalid credentials."} + + +def test_failed_logins_lock_the_username(server): + server().register("alice") + c = server() + wrong_logins(c, "alice") + c.send("login", username="alice", password="password1") + result = c.expect("login_result") + assert result["ok"] is False and result["error"].startswith("Too many failed logins.") + + +def test_failed_logins_for_any_names_lock_the_ip(server): + server().register("alice") + c = server() + for i in range(chat_server.LOGIN_FREE_FAILURES): + wrong_logins(c, f"nobody{i}", times=1) + c.send("login", username="alice", password="password1") + assert c.expect("login_result")["error"].startswith("Too many failed logins.") + + +def test_successful_logins_do_not_lock_the_ip(server): + server().register("alice") + for _ in range(chat_server.LOGIN_FREE_FAILURES + 2): + c = server() + c.send("login", username="alice", password="password1") + assert c.expect("login_result")["ok"] + c.close() + + +def test_login_validation(server): + c = server() + for username, password in [("bad name", "password1"), ("x" * 33, "password1"), ("alice", "x" * 129)]: + c.send("login", username=username, password=password) + c.expect("error") + + +class FakeClock: + def __init__(self): + self.now = 1000.0 + + def __call__(self): + return self.now + + +@pytest.fixture +def clock(): + return FakeClock() + + +@pytest.fixture +def throttle(clock): + return chat_server.LoginThrottle(clock) + + +def fail(throttle, host, username, times=1): + for _ in range(times): + assert throttle.begin(host, username) == 0 + + +def test_throttle_wait_doubles_up_to_the_cap(throttle, clock): + fail(throttle, "1.1.1.1", "alice", chat_server.LOGIN_FREE_FAILURES) + waits = [] + for _ in range(10): + waits.append(throttle.begin("1.1.1.1", "alice")) + clock.now += waits[-1] + fail(throttle, "1.1.1.1", "alice") + assert waits == [1, 2, 4, 8, 16, 32, 60, 60, 60, 60] + + +def test_throttle_locks_a_username_across_ips(throttle): + for i in range(chat_server.LOGIN_FREE_FAILURES): + fail(throttle, f"10.0.0.{i}", "alice") + assert throttle.begin("10.0.0.99", "alice") > 0 + assert throttle.begin("10.0.0.99", "bob") == 0 + + +def test_throttle_counts_attempts_still_in_progress(throttle): + for _ in range(chat_server.LOGIN_FREE_FAILURES): + assert throttle.begin("1.1.1.1", "alice") == 0 + assert throttle.begin("1.1.1.1", "alice") > 0 + + +def test_throttle_success_clears_the_username_but_not_other_ip_failures(throttle): + fail(throttle, "1.1.1.1", "nobody", chat_server.LOGIN_FREE_FAILURES - 1) + fail(throttle, "1.1.1.1", "alice") + throttle.succeeded("1.1.1.1", "alice") + assert ("user", "alice") not in throttle.failures + fail(throttle, "1.1.1.1", "bob") + assert throttle.begin("1.1.1.1", "carol") > 0 + + +def test_throttle_forgets_old_failures(throttle, clock): + fail(throttle, "1.1.1.1", "alice", chat_server.LOGIN_FREE_FAILURES) + clock.now += chat_server.LOGIN_FORGET + assert throttle.begin("1.1.1.1", "alice") == 0 + + +def test_throttle_prunes_stale_entries(throttle, clock, monkeypatch): + monkeypatch.setattr(chat_server, "LOGIN_MAX_TRACKED", 4) + for i in range(3): + fail(throttle, "1.1.1.1", f"user{i}") + clock.now += chat_server.LOGIN_FORGET + fail(throttle, "2.2.2.2", "fresh") + fail(throttle, "2.2.2.2", "fresh") + assert set(throttle.failures) == {("ip", "2.2.2.2"), ("user", "fresh")} From a6118f4bcd6d4a40644a803fcddba4c7cb263186 Mon Sep 17 00:00:00 2001 From: ABuljko Date: Sat, 3 Oct 2026 18:38:07 +0200 Subject: [PATCH 2/6] Log with the logging module instead of print --- client.py | 7 +++++-- server.py | 20 +++++++++++++------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/client.py b/client.py index 581b0ad..6a1235b 100644 --- a/client.py +++ b/client.py @@ -1,9 +1,9 @@ import argparse import json +import logging import queue import socket import threading -import traceback from datetime import UTC, datetime from pathlib import Path from tkinter import * @@ -15,6 +15,8 @@ DEFAULT_PORT = 5557 DEFAULT_CAFILE = Path(__file__).with_name("cert.pem") +log = logging.getLogger("client") + class ServerConnection: def __init__(self, host, port, cafile, events): @@ -95,7 +97,7 @@ def poll_events(): handler(message) except Exception: # A bad event must not stop the event loop. - traceback.print_exc() + log.exception("Error handling a server event") root.after(50, poll_events) @@ -450,6 +452,7 @@ def info(): "--cafile", default=DEFAULT_CAFILE, help="server certificate to trust (default: cert.pem next to this script)" ) args = parser.parse_args() +logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s") root = Tk() root.geometry("800x640") diff --git a/server.py b/server.py index fb56793..21dd258 100644 --- a/server.py +++ b/server.py @@ -2,6 +2,7 @@ import argparse import json +import logging import math import queue import re @@ -29,6 +30,8 @@ LOGIN_FORGET = 15 * 60 LOGIN_MAX_TRACKED = 10_000 +log = logging.getLogger("server") + clients = {} clients_lock = threading.Lock() @@ -200,9 +203,11 @@ def handle_login(conn, message): if len(password) > MAX_PASSWORD: raise BadRequest(f"Passwords are at most {MAX_PASSWORD} characters.") if wait := login_throttle.begin(conn.host, username): + log.warning("Login for %s from %s throttled for %.0f s", username, conn.host, wait) conn.send("login_result", ok=False, error=f"Too many failed logins. Try again in {math.ceil(wait)} s.") return if not db.check_user(username, password): + log.info("Failed login for %s from %s", username, conn.host) conn.send("login_result", ok=False, error="Invalid credentials.") return login_throttle.succeeded(conn.host, username) @@ -305,7 +310,7 @@ def handle_client(sock, addr, context): sock.settimeout(tls.HANDSHAKE_TIMEOUT) sock = context.wrap_socket(sock, server_side=True) except OSError as e: - print(f"TLS handshake with {addr} failed: {e}") + log.warning("TLS handshake with %s failed: %s", addr, e) sock.close() return conn = Connection(tls.LockedSocket(sock), addr[0]) @@ -323,27 +328,27 @@ def handle_client(sock, addr, context): conn.send("error", text=str(e)) except ProtocolError as e: conn.send("error", text=f"Protocol error: {e}.") - print(f"Dropping {addr}: {e}") + log.warning("Dropping %s: %s", addr, e) except OSError: pass - except Exception as e: - print(f"Error handling {addr}: {e!r}") + except Exception: + log.exception("Error handling %s", addr) finally: if conn.username: with clients_lock: if clients.get(conn.username) is conn: del clients[conn.username] conn.close() - print(f"Disconnected {addr}") + log.info("Disconnected %s", addr) def start_server(context, host=DEFAULT_HOST, port=DEFAULT_PORT): db.init_db() with socket.create_server((host, port)) as server: - print(f"Server listening on {host}:{port} (TLS)") + log.info("Server listening on %s:%s (TLS)", host, port) while True: client_socket, addr = server.accept() - print(f"Connection from {addr}") + log.info("Connection from %s", addr) threading.Thread(target=handle_client, args=(client_socket, addr, context), daemon=True).start() @@ -355,6 +360,7 @@ def main(): parser.add_argument("--cert", default=DEFAULT_CERT, help="TLS certificate (default: cert.pem next to this script)") parser.add_argument("--key", default=DEFAULT_KEY, help="TLS private key (default: key.pem next to this script)") args = parser.parse_args() + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") if args.db: db.DB_PATH = args.db for path in (args.cert, args.key): From 92f28c1a0af1e19261f932d82a821a0ba5cd9cee Mon Sep 17 00:00:00 2001 From: ABuljko Date: Sat, 3 Oct 2026 18:38:10 +0200 Subject: [PATCH 3/6] Detect dead connections and reconnect automatically --- README.md | 1 + client.py | 135 ++++++++++++++++++++++++++++++++++++++----- pyproject.toml | 1 + server.py | 56 +++++++++++++++++- tests/conftest.py | 36 ++++++++---- tests/test_server.py | 65 +++++++++++++++++++++ 6 files changed, 268 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index de8a44e..96189cd 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ python main.py - To start over with an empty database, run `python initialize_db.py`. - After 5 failed logins, each retry waits longer, up to a minute. +- If the connection drops, the app reconnects and logs you back in. - The connection is encrypted with TLS. The app only talks to a server whose certificate matches `cert.pem`. - To chat across machines, run `python make_cert.py --host `, start the server with `--host 0.0.0.0`, and give each user a copy of `cert.pem` (never `key.pem`). They start the app with `--host `. diff --git a/client.py b/client.py index 6a1235b..b5d15bd 100644 --- a/client.py +++ b/client.py @@ -4,6 +4,7 @@ import queue import socket import threading +import time from datetime import UTC, datetime from pathlib import Path from tkinter import * @@ -14,6 +15,9 @@ DEFAULT_HOST = "127.0.0.1" DEFAULT_PORT = 5557 DEFAULT_CAFILE = Path(__file__).with_name("cert.pem") +# The server pings every 20 s, so this much silence means the connection is dead. +SERVER_TIMEOUT = 60 +RECONNECT_DELAYS = [1, 2, 4, 8, 15, 30] log = logging.getLogger("client") @@ -24,20 +28,36 @@ def __init__(self, host, port, cafile, events): sock = socket.create_connection((host, port), timeout=5) self.sock = tls.LockedSocket(context.wrap_socket(sock, server_hostname=host)) self.events = events + # The reading thread answers pings, so sends come from two threads. + self.send_lock = threading.Lock() + self.last_seen = time.monotonic() + + def start(self): + """Queue each message except pings as (self, message). + + When the connection ends, queue (self, {"type": "disconnected"}). + """ threading.Thread(target=self._read_loop, daemon=True).start() def send(self, type_, /, **fields): - self.sock.sendall((json.dumps({"type": type_, **fields}) + "\n").encode()) + data = (json.dumps({"type": type_, **fields}) + "\n").encode() + with self.send_lock: + self.sock.sendall(data) def _read_loop(self): try: with self.sock.makefile() as reader: for line in reader: + self.last_seen = time.monotonic() try: message = json.loads(line) except (ValueError, RecursionError): continue - if isinstance(message, dict): + if not isinstance(message, dict): + continue + if message.get("type") == "ping": + self.send("pong") + else: self.events.put((self, message)) except (OSError, ValueError): pass @@ -55,6 +75,12 @@ def close(self): pending = [] pending_list = None signup_credentials = None +login_attempt = None +# Kept while logged in, to log in again after a dropped connection. +saved_login = None +# Changes in clear_app_data(), so a reconnect that was already running is ignored. +session = 0 +reconnect_attempts = 0 def connect_to_server(): @@ -63,6 +89,7 @@ def connect_to_server(): return True try: server = ServerConnection(args.host, args.port, args.cafile, events) + server.start() return True except FileNotFoundError: messagebox.showerror("Connection Error", f"Certificate {args.cafile} not found. Ask the server owner for it.") @@ -74,7 +101,10 @@ def connect_to_server(): def send(type_, /, **fields): if not server: - messagebox.showerror("Connection Error", "Not connected to the server.") + if current_user: + messagebox.showerror("Connection Error", "Reconnecting to the server. Try again in a moment.") + else: + messagebox.showerror("Connection Error", "Not connected to the server.") return try: server.send(type_, **fields) @@ -88,10 +118,14 @@ def poll_events(): conn, message = events.get_nowait() except queue.Empty: break - # Skip events left over from a closed connection. - if conn is not server: - continue try: + if callable(message): + # Work handed over from another thread. + message() + continue + # Skip events left over from a closed connection. + if conn is not server: + continue handler = EVENT_HANDLERS.get(message.get("type")) if handler: handler(message) @@ -101,13 +135,65 @@ def poll_events(): root.after(50, poll_events) +def check_server_alive(): + if server and time.monotonic() - server.last_seen > SERVER_TIMEOUT: + log.warning("No pings from the server, reconnecting") + # The reading thread then reports the connection as dropped. + server.close() + root.after(5000, check_server_alive) + + +def schedule_reconnect(): + global reconnect_attempts + delay = RECONNECT_DELAYS[min(reconnect_attempts, len(RECONNECT_DELAYS) - 1)] + reconnect_attempts += 1 + set_status(f"Lost connection. Reconnecting in {delay} s...") + root.after(delay * 1000, start_reconnect, session) + + +def start_reconnect(for_session): + if for_session != session: + return + set_status("Reconnecting...") + + def connect(): + try: + conn = ServerConnection(args.host, args.port, args.cafile, events) + except OSError as e: + log.info("Reconnect failed: %s", e) + conn = None + events.put((None, lambda: finish_reconnect(for_session, conn))) + + # Connecting can take seconds, so keep it off the Tk thread. + threading.Thread(target=connect, daemon=True).start() + + +def finish_reconnect(for_session, conn): + global server, login_attempt + if for_session != session or server: + if conn: + conn.close() + return + if not conn: + schedule_reconnect() + return + server = conn + server.start() + login_attempt = saved_login + send("login", username=saved_login[0], password=saved_login[1]) + + def clear_app_data(): - global server, current_chat, current_user + global server, current_chat, current_user, login_attempt, saved_login, session, reconnect_attempts if server: server.close() server = None current_chat = None current_user = None + login_attempt = None + saved_login = None + session += 1 + reconnect_attempts = 0 members.clear() pending.clear() refresh_pending_list() @@ -201,19 +287,36 @@ def login(): def login_user(username, password): + global login_attempt if current_user: messagebox.showerror("Login", f"Already logged in as {current_user}. Sign out first.") return if connect_to_server(): + login_attempt = (username, password) send("login", username=username, password=password) def on_login_result(message): - global current_user + global current_user, login_attempt, saved_login, reconnect_attempts + credentials, login_attempt = login_attempt, None + # Still logged in from before the connection dropped. + reconnected = current_user is not None if not message.get("ok"): - messagebox.showerror("Login Failed", message.get("error", "Login failed.")) + error = message.get("error", "Login failed.") + if reconnected: + clear_app_data() + messagebox.showerror("Disconnected", f"Reconnected, but could not log in again: {error}") + else: + messagebox.showerror("Login Failed", error) return + saved_login = credentials current_user = message["username"] + reconnect_attempts = 0 + if reconnected: + set_status("Reconnected.") + if current_chat: + send("history", username=current_chat) + return root.title(f"Chat Room! - {current_user}") hide_login_required() text_input.focus_set() @@ -225,6 +328,8 @@ def on_friends(message): person.delete(0, END) for username in message.get("users", []): add_member(username) + if current_chat in members: + person.selection_set(members.index(current_chat)) def add_member(username): @@ -304,10 +409,13 @@ def on_error(message): def on_disconnected(message): - was_logged_in = current_user is not None - clear_app_data() - if was_logged_in: - messagebox.showerror("Disconnected", "Lost connection to the server.") + global server + server.close() + server = None + if current_user: + schedule_reconnect() + else: + clear_app_data() EVENT_HANDLERS = { @@ -549,4 +657,5 @@ def info(): show_login_required() root.after(50, poll_events) +root.after(5000, check_server_alive) root.mainloop() diff --git a/pyproject.toml b/pyproject.toml index 20a4bad..b85beeb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,3 +24,4 @@ ignore = ["F403", "F405"] [tool.pytest.ini_options] testpaths = ["tests"] pythonpath = ["."] +markers = ["server_args(*args): extra command line arguments for the server fixture"] diff --git a/server.py b/server.py index 21dd258..072f50f 100644 --- a/server.py +++ b/server.py @@ -29,11 +29,17 @@ LOGIN_MAX_WAIT = 60 LOGIN_FORGET = 15 * 60 LOGIN_MAX_TRACKED = 10_000 +PING_INTERVAL = 20 +IDLE_TIMEOUT = 60 +# Clients reconnect after this long without hearing from us (SERVER_TIMEOUT in chat_client/app.py). +CLIENT_TIMEOUT = 60 log = logging.getLogger("server") clients = {} clients_lock = threading.Lock() +connections = set() +connections_lock = threading.Lock() class ProtocolError(Exception): @@ -55,6 +61,7 @@ def __init__(self, sock, host=None): self.writer = threading.Thread(target=self._write_loop, daemon=True) self.writer.start() self.username = None + self.last_seen = time.monotonic() def send(self, type_, /, **fields): data = (json.dumps({"type": type_, **fields}) + "\n").encode() @@ -83,6 +90,7 @@ def receive(self): line = self.reader.readline(MAX_LINE) if not line: return None + self.last_seen = time.monotonic() if not line.endswith("\n"): if len(line) >= MAX_LINE: raise ProtocolError("line too long") @@ -291,9 +299,14 @@ def handle_message(conn, message): send_to(receiver, "message", **fields) +def handle_pong(conn, message): + pass + + GUEST_HANDLERS = { "signup": handle_signup, "login": handle_login, + "pong": handle_pong, } USER_HANDLERS = { @@ -302,6 +315,7 @@ def handle_message(conn, message): "pending": handle_pending, "history": handle_history, "message": handle_message, + "pong": handle_pong, } @@ -314,6 +328,8 @@ def handle_client(sock, addr, context): sock.close() return conn = Connection(tls.LockedSocket(sock), addr[0]) + with connections_lock: + connections.add(conn) try: while (message := conn.receive()) is not None: handlers = USER_HANDLERS if conn.username else GUEST_HANDLERS @@ -334,6 +350,8 @@ def handle_client(sock, addr, context): except Exception: log.exception("Error handling %s", addr) finally: + with connections_lock: + connections.discard(conn) if conn.username: with clients_lock: if clients.get(conn.username) is conn: @@ -342,8 +360,27 @@ def handle_client(sock, addr, context): log.info("Disconnected %s", addr) -def start_server(context, host=DEFAULT_HOST, port=DEFAULT_PORT): +def heartbeat(interval=PING_INTERVAL, timeout=IDLE_TIMEOUT): + while True: + time.sleep(interval) + now = time.monotonic() + with connections_lock: + current = list(connections) + for conn in current: + try: + if now - conn.last_seen > timeout: + log.info("Dropping %s: no reply to pings", conn.host) + conn.shutdown() + else: + conn.send("ping") + except Exception: + # One bad connection must not stop the pings for everyone. + log.exception("Heartbeat failed for %s", conn.host) + + +def start_server(context, host=DEFAULT_HOST, port=DEFAULT_PORT, ping_interval=PING_INTERVAL, idle_timeout=IDLE_TIMEOUT): db.init_db() + threading.Thread(target=heartbeat, args=(ping_interval, idle_timeout), daemon=True).start() with socket.create_server((host, port)) as server: log.info("Server listening on %s:%s (TLS)", host, port) while True: @@ -352,6 +389,13 @@ def start_server(context, host=DEFAULT_HOST, port=DEFAULT_PORT): threading.Thread(target=handle_client, args=(client_socket, addr, context), daemon=True).start() +def seconds(text): + value = float(text) + if not 0 < value < math.inf: + raise argparse.ArgumentTypeError(f"{text} is not a positive number of seconds") + return value + + def main(): parser = argparse.ArgumentParser(description="Run the chat server.") parser.add_argument("--host", default=DEFAULT_HOST) @@ -359,7 +403,15 @@ def main(): parser.add_argument("--db", help="SQLite database file (default: chatroom.db next to this script)") parser.add_argument("--cert", default=DEFAULT_CERT, help="TLS certificate (default: cert.pem next to this script)") parser.add_argument("--key", default=DEFAULT_KEY, help="TLS private key (default: key.pem next to this script)") + parser.add_argument("--ping-interval", type=seconds, default=PING_INTERVAL, help="seconds between pings") + parser.add_argument( + "--idle-timeout", type=seconds, default=IDLE_TIMEOUT, help="drop clients silent for this many seconds" + ) args = parser.parse_args() + if args.idle_timeout <= args.ping_interval: + parser.error("--idle-timeout must be longer than --ping-interval") + if args.ping_interval >= CLIENT_TIMEOUT: + parser.error(f"--ping-interval must be under {CLIENT_TIMEOUT}, or clients will keep reconnecting") logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") if args.db: db.DB_PATH = args.db @@ -371,7 +423,7 @@ def main(): except ssl.SSLError as e: sys.exit(f"Could not load the certificate: {e}") try: - start_server(context, args.host, args.port) + start_server(context, args.host, args.port, args.ping_interval, args.idle_timeout) except KeyboardInterrupt: pass diff --git a/tests/conftest.py b/tests/conftest.py index 67ab491..b65371c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -38,12 +38,17 @@ def cert(tmp_path_factory): @pytest.fixture -def server(tmp_path, cert): - """Start server.py on a free port with its own database.""" +def server(tmp_path, cert, request): + """Start server.py on a free port with its own database. + + Extra command line arguments come from @pytest.mark.server_args(...). + """ + marker = request.node.get_closest_marker("server_args") port = free_port() proc = subprocess.Popen( [sys.executable, "-u", str(REPO / "server.py"), "--port", str(port), "--db", str(tmp_path / "server.db")] - + ["--cert", str(cert[0]), "--key", str(cert[1])], + + ["--cert", str(cert[0]), "--key", str(cert[1])] + + (list(marker.args) if marker else []), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, @@ -81,6 +86,7 @@ class Client: def __init__(self, port, context): self.sock = context.wrap_socket(socket.create_connection(("127.0.0.1", port), timeout=5), server_hostname=HOST) self.buffer = b"" + self.answer_pings = True def send(self, type_, /, **fields): self.send_raw((json.dumps({"type": type_, **fields}) + "\n").encode()) @@ -89,14 +95,22 @@ def send_raw(self, data): self.sock.sendall(data) def _next(self, timeout): - while b"\n" not in self.buffer: - self.sock.settimeout(timeout) - data = self.sock.recv(65536) - if not data: - return None - self.buffer += data - line, self.buffer = self.buffer.split(b"\n", 1) - return json.loads(line) + deadline = time.monotonic() + timeout + while True: + while b"\n" not in self.buffer: + left = deadline - time.monotonic() + if left <= 0: + raise TimeoutError + self.sock.settimeout(left) + data = self.sock.recv(65536) + if not data: + return None + self.buffer += data + line, self.buffer = self.buffer.split(b"\n", 1) + frame = json.loads(line) + if not (self.answer_pings and frame["type"] == "ping"): + return frame + self.send("pong") def expect(self, type_, timeout=15): """Return the next frame and check its type.""" diff --git a/tests/test_server.py b/tests/test_server.py index c508c8a..be3a7c5 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -1,6 +1,11 @@ +import argparse import json +import subprocess +import sys +import time import pytest +from conftest import REPO import server as chat_server @@ -278,3 +283,63 @@ def test_throttle_prunes_stale_entries(throttle, clock, monkeypatch): fail(throttle, "2.2.2.2", "fresh") fail(throttle, "2.2.2.2", "fresh") assert set(throttle.failures) == {("ip", "2.2.2.2"), ("user", "fresh")} + + +FAST_HEARTBEAT = pytest.mark.server_args("--ping-interval", "0.2", "--idle-timeout", "1") + + +@FAST_HEARTBEAT +def test_server_sends_pings(server): + c = server() + c.answer_pings = False + c.expect("ping", timeout=2) + + +@FAST_HEARTBEAT +def test_silent_client_is_dropped(server): + a = server().register("alice") + a.answer_pings = False + start = time.monotonic() + a.wait_closed(timeout=5) + assert time.monotonic() - start < 3 + again = server() + again.send("login", username="alice", password="password1") + assert again.expect("login_result")["ok"] + + +@FAST_HEARTBEAT +def test_client_that_answers_pings_stays_connected(server): + c = server().register("alice") + c.quiet(timeout=2) + c.send("pending") + assert c.expect("pending")["users"] == [] + + +@FAST_HEARTBEAT +def test_half_sent_line_does_not_count_as_alive(server): + c = server() + c.answer_pings = False + deadline = time.monotonic() + 3 + try: + while time.monotonic() < deadline: + c.send_raw(b" ") + time.sleep(0.1) + except OSError: + pass + assert all(frame["type"] == "ping" for frame in c.wait_closed(timeout=5)) + + +@pytest.mark.parametrize("text", ["-1", "0", "nan", "inf", "soon"]) +def test_heartbeat_settings_must_be_positive_numbers(text): + with pytest.raises((argparse.ArgumentTypeError, ValueError)): + chat_server.seconds(text) + + +@pytest.mark.parametrize( + "args", [["--ping-interval", "61", "--idle-timeout", "100"], ["--ping-interval", "5", "--idle-timeout", "2"]] +) +def test_server_refuses_heartbeat_settings_that_cannot_work(args): + result = subprocess.run( + [sys.executable, str(REPO / "server.py"), *args], capture_output=True, text=True, timeout=30 + ) + assert result.returncode == 2, result.stderr From 67ada6d815dd4d3e30d67e64593f3cfddb5d2c8e Mon Sep 17 00:00:00 2001 From: ABuljko Date: Sat, 3 Oct 2026 18:38:13 +0200 Subject: [PATCH 4/6] Version the database schema and enforce constraints --- chatroom_db.py | 136 +++++++++++++++++++++++++++++++++++++---------- tests/test_db.py | 117 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 225 insertions(+), 28 deletions(-) diff --git a/chatroom_db.py b/chatroom_db.py index 16f4088..9d1a71f 100644 --- a/chatroom_db.py +++ b/chatroom_db.py @@ -9,25 +9,76 @@ DB_PATH = os.environ.get("CHATROOM_DB", str(Path(__file__).with_name("chatroom.db"))) -SCHEMA = """ -CREATE TABLE IF NOT EXISTS users ( - username TEXT PRIMARY KEY, - password TEXT -); -CREATE TABLE IF NOT EXISTS messages ( - sender TEXT, - receiver TEXT, - message TEXT, - timestamp DATETIME DEFAULT CURRENT_TIMESTAMP -); -CREATE TABLE IF NOT EXISTS requests ( - sender TEXT, - receiver TEXT, - status TEXT -); -CREATE INDEX IF NOT EXISTS messages_pair ON messages (sender, receiver); -CREATE INDEX IF NOT EXISTS requests_pair ON requests (sender, receiver); -""" +# Each entry takes the database up one version, which is kept in PRAGMA user_version. +# Never change an entry once it has shipped. Add a new one instead. +MIGRATIONS = [ + # 1: NOT NULLs, foreign keys, one request per sender and receiver. Old rows that break these are dropped. + [ + # The tables as they were before versioning, so the steps below always have something to copy. + "CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, password TEXT)", + "CREATE TABLE IF NOT EXISTS messages (sender TEXT, receiver TEXT, message TEXT, timestamp DATETIME)", + "CREATE TABLE IF NOT EXISTS requests (sender TEXT, receiver TEXT, status TEXT)", + "ALTER TABLE users RENAME TO old_users", + "ALTER TABLE messages RENAME TO old_messages", + "ALTER TABLE requests RENAME TO old_requests", + """ + CREATE TABLE users ( + username TEXT PRIMARY KEY NOT NULL, + password TEXT NOT NULL + ) + """, + """ + CREATE TABLE messages ( + sender TEXT NOT NULL REFERENCES users (username) ON DELETE CASCADE, + receiver TEXT NOT NULL REFERENCES users (username) ON DELETE CASCADE, + message TEXT NOT NULL, + timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP + ) + """, + """ + CREATE TABLE requests ( + sender TEXT NOT NULL REFERENCES users (username) ON DELETE CASCADE, + receiver TEXT NOT NULL REFERENCES users (username) ON DELETE CASCADE, + status TEXT NOT NULL CHECK (status IN ('pending', 'accepted', 'rejected')), + UNIQUE (sender, receiver), + CHECK (sender <> receiver) + ) + """, + """ + INSERT INTO users (username, password) + SELECT username, password FROM old_users + WHERE username IS NOT NULL AND password IS NOT NULL + """, + """ + INSERT INTO messages (sender, receiver, message, timestamp) + SELECT sender, receiver, message, timestamp FROM old_messages + WHERE sender IN (SELECT username FROM users) + AND receiver IN (SELECT username FROM users) + AND message IS NOT NULL + AND timestamp IS NOT NULL + ORDER BY rowid + """, + # Of duplicate requests, keep an accepted one, else the newest. + """ + INSERT INTO requests (sender, receiver, status) + SELECT sender, receiver, status FROM old_requests AS o + WHERE rowid = ( + SELECT rowid FROM old_requests + WHERE sender = o.sender AND receiver = o.receiver AND status IN ('pending', 'accepted', 'rejected') + ORDER BY status = 'accepted' DESC, rowid DESC + LIMIT 1 + ) + AND sender <> receiver + AND sender IN (SELECT username FROM users) + AND receiver IN (SELECT username FROM users) + """, + "DROP TABLE old_users", + "DROP TABLE old_messages", + "DROP TABLE old_requests", + "CREATE INDEX messages_pair ON messages (sender, receiver)", + "CREATE INDEX requests_receiver ON requests (receiver)", + ], +] SCRYPT_N, SCRYPT_R, SCRYPT_P = 2**14, 8, 1 @@ -37,22 +88,46 @@ def connect(): - return closing(sqlite3.connect(DB_PATH, timeout=10)) + conn = sqlite3.connect(DB_PATH, timeout=10) + # SQLite checks foreign keys only on connections that turn them on. + conn.execute("PRAGMA foreign_keys = ON") + return closing(conn) -def init_db(): +def schema_version(): with connect() as conn: - conn.executescript(SCHEMA) + return conn.execute("PRAGMA user_version").fetchone()[0] + + +def init_db(): + # A plain connection: foreign keys stay off while tables are rebuilt, and the transaction is ours to run. + with closing(sqlite3.connect(DB_PATH, timeout=10, isolation_level=None)) as conn: + conn.execute("BEGIN IMMEDIATE") + try: + version = conn.execute("PRAGMA user_version").fetchone()[0] + if version > len(MIGRATIONS): + raise RuntimeError(f"{DB_PATH} is schema version {version}, newer than this app knows.") + for number, statements in enumerate(MIGRATIONS[version:], start=version + 1): + for statement in statements: + conn.execute(statement) + conn.execute(f"PRAGMA user_version = {number}") + if conn.execute("PRAGMA foreign_key_check").fetchone(): + raise RuntimeError(f"Migration {number} left rows pointing at missing users.") + conn.execute("COMMIT") + except BaseException: + conn.execute("ROLLBACK") + raise def reset_db(): - with connect() as conn: + with closing(sqlite3.connect(DB_PATH, timeout=10)) as conn: conn.executescript(""" - DROP TABLE IF EXISTS users; DROP TABLE IF EXISTS messages; DROP TABLE IF EXISTS requests; + DROP TABLE IF EXISTS users; + PRAGMA user_version = 0; """) - conn.executescript(SCHEMA) + init_db() def hash_password(password): @@ -114,8 +189,13 @@ def add_request(sender, receiver): (receiver, sender), ) return "accepted" - conn.execute("DELETE FROM requests WHERE sender = ? AND receiver = ?", (sender, receiver)) - conn.execute("INSERT INTO requests (sender, receiver, status) VALUES (?, ?, 'pending')", (sender, receiver)) + conn.execute( + """ + INSERT INTO requests (sender, receiver, status) VALUES (?, ?, 'pending') + ON CONFLICT (sender, receiver) DO UPDATE SET status = 'pending' + """, + (sender, receiver), + ) return "sent" @@ -133,7 +213,7 @@ def respond_to_request(sender, receiver, accept): def get_requests(username): with connect() as conn: rows = conn.execute( - "SELECT DISTINCT sender FROM requests WHERE receiver = ? AND status = 'pending' ORDER BY sender", + "SELECT sender FROM requests WHERE receiver = ? AND status = 'pending' ORDER BY sender", (username,), ).fetchall() return [row[0] for row in rows] diff --git a/tests/test_db.py b/tests/test_db.py index 7d8d049..25aa930 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -3,9 +3,17 @@ import threading from contextlib import closing +import pytest + import chatroom_db as db +def make_users(*names): + """Add users without paying for scrypt.""" + with db.connect() as conn, conn: + conn.executemany("INSERT INTO users (username, password) VALUES (?, 'x')", [(name,) for name in names]) + + def test_password_hash_round_trip(): stored = db.hash_password("correct horse") assert stored.startswith("scrypt$") @@ -50,6 +58,7 @@ def spy(password, stored): def test_friend_request_lifecycle(db_path): + make_users("alice", "bob") assert db.add_request("alice", "bob") == "sent" assert db.add_request("alice", "bob") == "pending" assert db.get_requests("bob") == ["alice"] @@ -64,12 +73,14 @@ def test_friend_request_lifecycle(db_path): def test_crossed_requests_become_friends(db_path): + make_users("alice", "bob") assert db.add_request("alice", "bob") == "sent" assert db.add_request("bob", "alice") == "accepted" assert db.are_friends("alice", "bob") def test_rejected_request_can_be_sent_again(db_path): + make_users("alice", "bob") db.add_request("alice", "bob") assert db.respond_to_request("alice", "bob", accept=False) assert not db.are_friends("alice", "bob") @@ -84,6 +95,7 @@ def test_responding_without_a_request_does_nothing(db_path): def test_chat_history_keeps_order_and_content(db_path): + make_users("alice", "bob", "carol") texts = ["first", "second | with pipe", "third\nwith newline", "fourth {[$x]}"] for i, text in enumerate(texts): sender, receiver = ("alice", "bob") if i % 2 == 0 else ("bob", "alice") @@ -125,3 +137,108 @@ def test_init_db_is_idempotent_and_reset_clears(db_path): assert db.user_exists("alice") db.reset_db() assert not db.user_exists("alice") + + +def test_new_database_is_at_the_latest_version(db_path): + assert db.schema_version() == len(db.MIGRATIONS) + db.init_db() + assert db.schema_version() == len(db.MIGRATIONS) + + +@pytest.mark.parametrize( + "sql, values", + [ + ("INSERT INTO users (username, password) VALUES (?, ?)", ("bob", None)), + ("INSERT INTO messages (sender, receiver, message) VALUES (?, ?, ?)", ("alice", "bob", None)), + ("INSERT INTO messages (sender, receiver, message) VALUES (?, ?, ?)", ("alice", "nobody", "hi")), + ("INSERT INTO requests (sender, receiver, status) VALUES (?, ?, ?)", ("alice", "nobody", "pending")), + ("INSERT INTO requests (sender, receiver, status) VALUES (?, ?, ?)", ("alice", "alice", "pending")), + ("INSERT INTO requests (sender, receiver, status) VALUES (?, ?, ?)", ("alice", "bob", "maybe")), + ("INSERT INTO requests (sender, receiver, status) VALUES (?, ?, ?)", ("alice", "bob", "rejected")), + ], + ids=[ + "null-password", + "null-message", + "message-to-missing-user", + "request-to-missing-user", + "self-request", + "bad-status", + "duplicate-request", + ], +) +def test_schema_rejects_bad_rows(db_path, sql, values): + make_users("alice", "bob") + db.add_request("alice", "bob") + with pytest.raises(sqlite3.IntegrityError), db.connect() as conn: + conn.execute(sql, values) + + +def test_deleting_a_user_removes_their_rows(db_path): + make_users("alice", "bob") + db.add_request("alice", "bob") + db.add_message("alice", "bob", "hi") + with db.connect() as conn, conn: + conn.execute("DELETE FROM users WHERE username = 'bob'") + assert db.get_friends("alice") == [] + assert db.get_chat_history("alice", "bob") == [] + + +def test_old_database_is_migrated(tmp_path, monkeypatch): + path = tmp_path / "old.db" + monkeypatch.setattr(db, "DB_PATH", str(path)) + with closing(sqlite3.connect(path)) as conn, conn: + conn.executescript(""" + CREATE TABLE users (username TEXT PRIMARY KEY, password TEXT); + CREATE TABLE messages (sender TEXT, receiver TEXT, message TEXT, + timestamp DATETIME DEFAULT CURRENT_TIMESTAMP); + CREATE TABLE requests (sender TEXT, receiver TEXT, status TEXT); + CREATE INDEX messages_pair ON messages (sender, receiver); + CREATE INDEX requests_pair ON requests (sender, receiver); + INSERT INTO users VALUES ('alice', 'a'), ('bob', 'b'), ('carol', 'c'), ('dave', 'd'), ('eve', NULL); + INSERT INTO messages VALUES + ('alice', 'bob', 'first', '2024-01-01 10:00:00'), + ('bob', 'alice', 'second', '2024-01-01 10:00:00'), + ('alice', 'bob', NULL, '2024-01-01 10:01:00'), + ('alice', 'ghost', 'to nobody', '2024-01-01 10:02:00'), + ('eve', 'alice', 'no password', '2024-01-01 10:03:00'); + INSERT INTO requests VALUES + ('alice', 'bob', 'accepted'), + ('alice', 'bob', 'pending'), + ('carol', 'alice', 'rejected'), + ('carol', 'alice', 'pending'), + ('dave', 'dave', 'pending'), + ('dave', 'ghost', 'pending'), + ('dave', 'alice', 'maybe'), + ('bob', 'dave', 'pending'); + """) + db.init_db() + + assert db.schema_version() == len(db.MIGRATIONS) + assert db.check_user("eve", "anything") is False + assert not db.user_exists("eve") + assert [(s, r, m) for s, r, m, _ in db.get_chat_history("alice", "bob")] == [ + ("alice", "bob", "first"), + ("bob", "alice", "second"), + ] + assert db.get_friends("alice") == ["bob"] + assert db.get_requests("alice") == ["carol"] + assert db.get_requests("dave") == ["bob"] + with db.connect() as conn: + assert conn.execute("SELECT count(*) FROM requests").fetchone()[0] == 3 + assert conn.execute("SELECT count(*) FROM messages").fetchone()[0] == 2 + + +def test_failed_migration_changes_nothing(db_path, monkeypatch): + make_users("alice") + monkeypatch.setattr(db, "MIGRATIONS", [*db.MIGRATIONS, ["DROP TABLE users", "SELECT * FROM missing"]]) + with pytest.raises(sqlite3.OperationalError): + db.init_db() + assert db.schema_version() == len(db.MIGRATIONS) - 1 + assert db.user_exists("alice") + + +def test_newer_database_is_refused(db_path): + with db.connect() as conn: + conn.execute(f"PRAGMA user_version = {len(db.MIGRATIONS) + 1}") + with pytest.raises(RuntimeError, match="newer"): + db.init_db() From 65ac8b5805881e970b18b3d9e4cb8fc25c9d7dfa Mon Sep 17 00:00:00 2001 From: ABuljko Date: Sat, 3 Oct 2026 18:38:17 +0200 Subject: [PATCH 5/6] Split the client into network, app, UI and dialog modules --- chat_client/__init__.py | 0 chat_client/app.py | 355 +++++++++++++++++++++ chat_client/dialogs.py | 99 ++++++ chat_client/network.py | 55 ++++ chat_client/ui.py | 166 ++++++++++ client.py | 668 ++-------------------------------------- pyproject.toml | 2 - tests/test_client.py | 341 ++++++++++++++++++++ 8 files changed, 1037 insertions(+), 649 deletions(-) create mode 100644 chat_client/__init__.py create mode 100644 chat_client/app.py create mode 100644 chat_client/dialogs.py create mode 100644 chat_client/network.py create mode 100644 chat_client/ui.py create mode 100644 tests/test_client.py diff --git a/chat_client/__init__.py b/chat_client/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/chat_client/app.py b/chat_client/app.py new file mode 100644 index 0000000..0205ec6 --- /dev/null +++ b/chat_client/app.py @@ -0,0 +1,355 @@ +import logging +import queue +import threading +import time +from datetime import UTC, datetime + +log = logging.getLogger("client") + +# The server pings every 20 s, so this much silence means the connection is dead. +SERVER_TIMEOUT = 60 +RECONNECT_DELAYS = [1, 2, 4, 8, 15, 30] +POLL_MS = 50 +ALIVE_CHECK_MS = 5000 + + +def local_time(timestamp): + try: + utc = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S").replace(tzinfo=UTC) + # astimezone() fails for very old or far-future dates. + return utc.astimezone().strftime("%Y-%m-%d %H:%M:%S") + except (TypeError, ValueError, OverflowError, OSError): + return timestamp + + +def run_in_thread(func): + threading.Thread(target=func, daemon=True).start() + + +class ChatApp: + """connect(events) must return a connection that isn't reading yet.""" + + def __init__(self, make_view, connect, run_in_background=run_in_thread): + self.connect = connect + self.run_in_background = run_in_background + self.events = queue.Queue() + self.server = None + self.current_user = None + self.current_chat = None + self.members = [] + self.pending = [] + self.signup_credentials = None + self.login_attempt = None + # Kept while logged in, to log in again after a dropped connection. + self.saved_login = None + # Changes on every reset, so a reconnect that was already running is ignored. + self.session = 0 + self.reconnect_attempts = 0 + self.handlers = { + "signup_result": self.on_signup_result, + "login_result": self.on_login_result, + "friends": self.on_friends, + "friend_added": self.on_friend_added, + "pending": self.on_pending, + "request_received": self.on_request_received, + "request_rejected": self.on_request_rejected, + "history": self.on_history, + "message": self.on_message, + "info": self.on_info, + "error": self.on_error, + "disconnected": self.on_disconnected, + } + self.view = make_view(self) + + def start(self): + self.view.set_logged_in(None) + self.view.after(POLL_MS, self.poll_events) + self.view.after(ALIVE_CHECK_MS, self.check_server_alive) + + def connect_to_server(self): + if self.server: + return True + try: + self.server = self.connect(self.events) + except FileNotFoundError as e: + self.view.show_error( + "Connection Error", f"Certificate {e.filename} not found. Ask the server owner for it." + ) + return False + except OSError as e: + self.view.show_error("Connection Error", f"Failed to connect to server: {e}") + return False + self.server.start() + return True + + def send(self, type_, /, **fields): + if not self.server: + if self.current_user: + self.view.show_error("Connection Error", "Reconnecting to the server. Try again in a moment.") + else: + self.view.show_error("Connection Error", "Not connected to the server.") + return + try: + self.server.send(type_, **fields) + except OSError as e: + self.view.show_error("Connection Error", f"Failed to reach the server: {e}") + + def process_events(self): + while True: + try: + conn, message = self.events.get_nowait() + except queue.Empty: + return + try: + if callable(message): + # Work handed over from another thread. + message() + continue + # Skip events left over from a closed connection. + if conn is not self.server: + continue + handler = self.handlers.get(message.get("type")) + if handler: + handler(message) + except Exception: + # A bad event must not stop the event loop. + log.exception("Error handling a server event") + + def poll_events(self): + self.process_events() + self.view.after(POLL_MS, self.poll_events) + + def check_server_alive(self): + if self.server and time.monotonic() - self.server.last_seen > SERVER_TIMEOUT: + log.warning("No pings from the server, reconnecting") + # The reading thread then reports the connection as dropped. + self.server.close() + self.view.after(ALIVE_CHECK_MS, self.check_server_alive) + + def schedule_reconnect(self): + delay = RECONNECT_DELAYS[min(self.reconnect_attempts, len(RECONNECT_DELAYS) - 1)] + self.reconnect_attempts += 1 + self.view.set_status(f"Lost connection. Reconnecting in {delay} s...") + self.view.after(delay * 1000, self.start_reconnect, self.session) + + def start_reconnect(self, session): + if session != self.session: + return + self.view.set_status("Reconnecting...") + + def connect(): + try: + conn = self.connect(self.events) + except OSError as e: + log.info("Reconnect failed: %s", e) + conn = None + self.events.put((None, lambda: self.finish_reconnect(session, conn))) + + # Connecting can take seconds, so keep it off the UI thread. + self.run_in_background(connect) + + def finish_reconnect(self, session, conn): + if session != self.session or self.server: + if conn: + conn.close() + return + if not conn: + self.schedule_reconnect() + return + self.server = conn + self.server.start() + self.login_attempt = self.saved_login + username, password = self.saved_login + self.send("login", username=username, password=password) + + def reset(self): + if self.server: + self.server.close() + self.server = None + self.current_user = None + self.current_chat = None + self.login_attempt = None + self.saved_login = None + self.session += 1 + self.reconnect_attempts = 0 + self.members.clear() + self.pending.clear() + self.view.set_pending(self.pending) + self.view.set_members(self.members, None) + self.view.set_chat(None, []) + self.view.set_status("") + self.view.set_logged_in(None) + + def require_login(self): + if not self.current_user: + self.view.show_error("Login Required", "Log in first.") + return False + return True + + def signup(self): + self.view.ask_credentials("Sign Up", "Sign up!", self.signup_user) + + def signup_user(self, username, password): + if self.current_user: + self.view.show_error("Sign Up", "Sign out first.") + return + if self.connect_to_server(): + self.signup_credentials = (username, password) + self.send("signup", username=username, password=password) + + def login(self): + self.view.ask_credentials("Login", "Login!", self.login_user) + + def login_user(self, username, password): + if self.current_user: + self.view.show_error("Login", f"Already logged in as {self.current_user}. Sign out first.") + return + if self.connect_to_server(): + self.login_attempt = (username, password) + self.send("login", username=username, password=password) + + def sign_out(self): + self.reset() + + def exit(self): + if self.view.confirm("Exit Application", "Are you sure you want to exit the application?"): + if self.server: + self.server.close() + self.view.close() + + def show_profile(self): + if self.current_user: + self.view.show_info("Profile", f"Logged in as: {self.current_user}") + + def show_about(self): + self.view.show_info("Info", "Chat Room\nCreated by Amin Niaziardekani, Swapnaneel Sarkhel and Ajdin Buljko") + + def find_user(self): + if self.require_login(): + self.view.ask_username(self.send_friend_request) + + def send_friend_request(self, username): + self.send("friend_request", username=username) + + def open_pending(self): + if self.require_login(): + self.view.show_pending(self.pending, self.respond_request) + self.send("pending") + + def respond_request(self, username, accept): + self.send("respond_request", username=username, accept=accept) + if username in self.pending: + self.pending.remove(username) + self.view.set_pending(self.pending) + + def select_chat(self, username): + self.current_chat = username + self.view.set_chat(username, []) + self.send("history", username=username) + + def send_message(self, text): + """Return True if the input can be cleared.""" + if not text.strip(): + return False + if not self.current_chat: + self.view.show_error("Send Error", "Pick a member to chat with first.") + return False + self.send("message", to=self.current_chat, text=text) + return True + + def format_message(self, message): + sender = "You" if message["sender"] == self.current_user else message["sender"] + # List rows can't show line breaks. + text = " ".join(message["text"].splitlines()) + return f"{local_time(message['timestamp'])} {sender}: {text}" + + def on_signup_result(self, message): + credentials, self.signup_credentials = self.signup_credentials, None + if message.get("ok"): + self.view.show_info("Sign Up Success", "User added successfully.") + if credentials: + self.login_user(*credentials) + else: + self.view.show_error("Sign Up Failed", message.get("error", "Sign up failed.")) + + def on_login_result(self, message): + credentials, self.login_attempt = self.login_attempt, None + # Still logged in from before the connection dropped. + reconnected = self.current_user is not None + if not message.get("ok"): + error = message.get("error", "Login failed.") + if reconnected: + self.reset() + self.view.show_error("Disconnected", f"Reconnected, but could not log in again: {error}") + else: + self.view.show_error("Login Failed", error) + return + self.saved_login = credentials + self.current_user = message["username"] + self.reconnect_attempts = 0 + if reconnected: + self.view.set_status("Reconnected.") + if self.current_chat: + self.send("history", username=self.current_chat) + return + self.view.set_logged_in(self.current_user) + self.view.show_info("Login Success", "Login successful.") + + def on_friends(self, message): + self.members[:] = message.get("users", []) + self.view.set_members(self.members, self.current_chat) + + def add_member(self, username): + if username not in self.members: + self.members.append(username) + self.view.set_members(self.members, self.current_chat) + + def on_friend_added(self, message): + username = message["username"] + self.add_member(username) + if username in self.pending: + self.pending.remove(username) + self.view.set_pending(self.pending) + self.view.set_status(f"You and {username} are now friends.") + + def on_pending(self, message): + self.pending[:] = message.get("users", []) + self.view.set_pending(self.pending) + if self.pending: + self.view.set_status(f"Pending requests: {len(self.pending)}") + + def on_request_received(self, message): + username = message["username"] + if username not in self.pending: + self.pending.append(username) + self.view.set_pending(self.pending) + self.view.set_status(f"New friend request from {username}. See Friends > Pending Requests.") + + def on_request_rejected(self, message): + self.view.show_info("Request Rejected", f"Your chat request to {message['username']} was rejected.") + + def on_history(self, message): + if message.get("username") != self.current_chat: + return + self.view.set_chat(self.current_chat, [self.format_message(item) for item in message.get("messages", [])]) + + def on_message(self, message): + other = message["receiver"] if message["sender"] == self.current_user else message["sender"] + if other == self.current_chat: + self.view.add_chat_line(self.format_message(message)) + else: + self.view.set_status(f"New message from {other}.") + + def on_info(self, message): + self.view.set_status(message.get("text", "")) + + def on_error(self, message): + self.view.show_error("Error", message.get("text", "Unknown error.")) + + def on_disconnected(self, message): + self.server.close() + self.server = None + if self.current_user: + self.schedule_reconnect() + else: + self.reset() diff --git a/chat_client/dialogs.py b/chat_client/dialogs.py new file mode 100644 index 0000000..7e176d2 --- /dev/null +++ b/chat_client/dialogs.py @@ -0,0 +1,99 @@ +import tkinter as tk +from tkinter import messagebox + + +def _dialog(parent, title): + dialog = tk.Toplevel(parent) + dialog.title(title) + dialog.transient(parent) + dialog.resizable(False, False) + return dialog + + +def ask_credentials(parent, title, button_text, on_submit): + dialog = _dialog(parent, title) + tk.Label(dialog, text="Username:").grid(row=0, column=0, padx=5, pady=5, sticky=tk.E) + tk.Label(dialog, text="Password:").grid(row=1, column=0, padx=5, pady=5, sticky=tk.E) + username_entry = tk.Entry(dialog) + password_entry = tk.Entry(dialog, show="*") + username_entry.grid(row=0, column=1, padx=5, pady=5) + password_entry.grid(row=1, column=1, padx=5, pady=5) + username_entry.focus_set() + + def submit(event=None): + username = username_entry.get().strip() + password = password_entry.get() + if not username or not password: + messagebox.showerror("Error", "Username and password cannot be empty.", parent=dialog) + return + dialog.destroy() + on_submit(username, password) + + tk.Button(dialog, text=button_text, command=submit).grid(row=2, columnspan=2, pady=5) + dialog.bind("", submit) + + +def ask_username(parent, on_submit): + dialog = _dialog(parent, "Find User") + tk.Label(dialog, text="Username:").grid(row=0, column=0, padx=5, pady=5) + username_entry = tk.Entry(dialog) + username_entry.grid(row=0, column=1, padx=5, pady=5) + username_entry.focus_set() + + def submit(event=None): + username = username_entry.get().strip() + if not username: + messagebox.showerror("Error", "Username cannot be empty.", parent=dialog) + return + dialog.destroy() + on_submit(username) + + tk.Button(dialog, text="Send request", command=submit).grid(row=1, columnspan=2, pady=5) + dialog.bind("", submit) + + +class PendingDialog: + """Lists friend requests. on_respond(username, accept) is called for Accept and Reject.""" + + def __init__(self, parent, on_respond): + self.on_respond = on_respond + self.window = tk.Toplevel(parent) + self.window.title("Pending Requests") + self.window.geometry("300x300") + self.window.transient(parent) + + tk.Label(self.window, text="Pending Requests:").pack(pady=10) + frame = tk.Frame(self.window) + frame.pack(fill=tk.BOTH, expand=True, padx=10) + scrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL) + self.list = tk.Listbox(frame, selectmode=tk.SINGLE, exportselection=False, yscrollcommand=scrollbar.set) + scrollbar.config(command=self.list.yview) + scrollbar.pack(side=tk.RIGHT, fill=tk.Y) + self.list.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) + + buttons = tk.Frame(self.window) + tk.Button(buttons, text="Accept", command=lambda: self.respond(True), bg="green", fg="white", width=6).pack( + side=tk.LEFT, padx=5 + ) + tk.Button(buttons, text="Reject", command=lambda: self.respond(False), bg="red", fg="white", width=6).pack( + side=tk.RIGHT, padx=5 + ) + buttons.pack(pady=10) + + def is_open(self): + return bool(self.window.winfo_exists()) + + def lift(self): + self.window.lift() + + def set_users(self, users): + self.list.delete(0, tk.END) + for username in users: + self.list.insert(tk.END, username) + + def respond(self, accept): + selection = self.list.curselection() + if not selection: + messagebox.showerror("Error", "No request selected.", parent=self.window) + return + self.on_respond(self.list.get(selection[0]), accept) diff --git a/chat_client/network.py b/chat_client/network.py new file mode 100644 index 0000000..a990193 --- /dev/null +++ b/chat_client/network.py @@ -0,0 +1,55 @@ +import errno +import json +import socket +import threading +import time +from pathlib import Path + +import tls + + +class ServerConnection: + def __init__(self, host, port, cafile, events): + if not Path(cafile).is_file(): + raise FileNotFoundError(errno.ENOENT, "certificate not found", str(cafile)) + context = tls.client_context(cafile) + sock = socket.create_connection((host, port), timeout=5) + self.sock = tls.LockedSocket(context.wrap_socket(sock, server_hostname=host)) + self.events = events + # The reading thread answers pings, so sends come from two threads. + self.send_lock = threading.Lock() + self.last_seen = time.monotonic() + + def start(self): + """Queue each message except pings as (self, message). + + When the connection ends, queue (self, {"type": "disconnected"}). + """ + threading.Thread(target=self._read_loop, daemon=True).start() + + def send(self, type_, /, **fields): + data = (json.dumps({"type": type_, **fields}) + "\n").encode() + with self.send_lock: + self.sock.sendall(data) + + def _read_loop(self): + try: + with self.sock.makefile() as reader: + for line in reader: + self.last_seen = time.monotonic() + try: + message = json.loads(line) + except (ValueError, RecursionError): + continue + if not isinstance(message, dict): + continue + if message.get("type") == "ping": + self.send("pong") + else: + self.events.put((self, message)) + except (OSError, ValueError): + pass + self.events.put((self, {"type": "disconnected"})) + + def close(self): + self.sock.close() diff --git a/chat_client/ui.py b/chat_client/ui.py new file mode 100644 index 0000000..00a49c4 --- /dev/null +++ b/chat_client/ui.py @@ -0,0 +1,166 @@ +import tkinter as tk +from tkinter import messagebox + +from chat_client import dialogs + +TITLE = "Chat Room!" +LIST_STYLE = { + "highlightthickness": 0, + "selectbackground": "deep sky blue", + "font": ("Arial", 15), + "bg": "white", + "fg": "green", + "bd": 0, + "activestyle": "none", + "exportselection": False, +} +FRAME_STYLE = {"font": ("Arial", 15, "bold"), "bg": "white", "fg": "black", "bd": 5} + + +class MainWindow: + def __init__(self, root, app): + self.root = root + self.app = app + self.pending_dialog = None + + root.geometry("800x640") + root.minsize(600, 400) + root.title(TITLE) + root.protocol("WM_DELETE_WINDOW", app.exit) + root.columnconfigure(1, weight=1) + root.rowconfigure(0, weight=1) + self._build_menu() + + members_frame = tk.LabelFrame(root, text="Members:", **FRAME_STYLE) + members_frame.grid(row=0, column=0, rowspan=2, sticky=tk.NSEW) + self.members = self._scrolled_list(members_frame, selectmode=tk.SINGLE, width=14) + self.members.bind("<>", self._on_member_selected) + + self.chat_frame = tk.LabelFrame(root, text="Chat:", **FRAME_STYLE) + self.chat_frame.grid(row=0, column=1, sticky=tk.NSEW) + self.chat = self._scrolled_list(self.chat_frame, selectmode=tk.EXTENDED) + + text_frame = tk.LabelFrame(root, bg="white", bd=5) + text_frame.grid(row=1, column=1, sticky=tk.EW) + self.input_text = tk.StringVar() + self.input = tk.Entry(text_frame, font=("Arial", 15), textvariable=self.input_text) + self.input.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5, pady=5, ipady=12) + self.input.bind("", self._on_send) + tk.Button(text_frame, text="Send", bg="white", command=self._on_send).pack( + side=tk.RIGHT, padx=5, pady=5, ipadx=5, ipady=10 + ) + + self.status_text = tk.StringVar() + tk.Label(root, textvariable=self.status_text, anchor=tk.W).grid( + row=2, column=0, columnspan=2, sticky=tk.EW, padx=5 + ) + + self.login_required = tk.Frame(root, bg="grey") + tk.Label( + self.login_required, text="Sign in or login required to continue", bg="grey", fg="white", font=("Arial", 20) + ).place(relx=0.5, rely=0.5, anchor=tk.CENTER) + self.login_required.place(x=0, y=0, relwidth=1, relheight=1) + + def _build_menu(self): + menu = tk.Menu(self.root) + self.root.config(menu=menu) + for label, items in [ + ( + "File", + [ + ("Login", self.app.login), + ("Sign up", self.app.signup), + ("Sign Out", self.app.sign_out), + None, + ("Exit", self.app.exit), + ], + ), + ("Friends", [("Find User", self.app.find_user), ("Pending Requests", self.app.open_pending)]), + ("Info", [("Profile", self.app.show_profile), ("Info", self.app.show_about)]), + ]: + submenu = tk.Menu(menu, tearoff=0) + menu.add_cascade(label=label, menu=submenu) + for item in items: + if item is None: + submenu.add_separator() + else: + submenu.add_command(label=item[0], command=item[1]) + + def _scrolled_list(self, parent, **options): + scrollbar = tk.Scrollbar(parent, orient=tk.VERTICAL) + listbox = tk.Listbox(parent, yscrollcommand=scrollbar.set, **LIST_STYLE, **options) + scrollbar.config(command=listbox.yview) + scrollbar.pack(side=tk.RIGHT, fill=tk.Y) + listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=5, pady=5) + return listbox + + def _on_member_selected(self, event): + selection = self.members.curselection() + if selection: + self.app.select_chat(self.members.get(selection[0])) + + def _on_send(self, event=None): + if self.app.send_message(self.input_text.get()): + self.input_text.set("") + + def after(self, ms, func, *args): + self.root.after(ms, func, *args) + + def close(self): + self.root.destroy() + + def show_error(self, title, text): + messagebox.showerror(title, text) + + def show_info(self, title, text): + messagebox.showinfo(title, text) + + def confirm(self, title, text): + return messagebox.askquestion(title, text, icon="warning") == "yes" + + def ask_credentials(self, title, button_text, on_submit): + dialogs.ask_credentials(self.root, title, button_text, on_submit) + + def ask_username(self, on_submit): + dialogs.ask_username(self.root, on_submit) + + def show_pending(self, users, on_respond): + if self.pending_dialog and self.pending_dialog.is_open(): + self.pending_dialog.lift() + else: + self.pending_dialog = dialogs.PendingDialog(self.root, on_respond) + self.pending_dialog.set_users(users) + + def set_pending(self, users): + if self.pending_dialog and self.pending_dialog.is_open(): + self.pending_dialog.set_users(users) + + def set_status(self, text): + self.status_text.set(text) + + def set_logged_in(self, username): + if username: + self.root.title(f"{TITLE} - {username}") + self.login_required.lower() + self.input.focus_set() + else: + self.root.title(TITLE) + self.login_required.lift() + + def set_members(self, users, selected): + self.members.delete(0, tk.END) + for username in users: + self.members.insert(tk.END, username) + if selected in users: + self.members.selection_set(users.index(selected)) + + def set_chat(self, username, lines): + self.chat_frame.config(text=f"Chat: {username}" if username else "Chat:") + self.chat.delete(0, tk.END) + for line in lines: + self.chat.insert(tk.END, line) + self.chat.yview(tk.END) + + def add_chat_line(self, line): + self.chat.insert(tk.END, line) + self.chat.yview(tk.END) diff --git a/client.py b/client.py index b5d15bd..deb5e47 100644 --- a/client.py +++ b/client.py @@ -1,661 +1,35 @@ import argparse -import json import logging -import queue -import socket -import threading -import time -from datetime import UTC, datetime +import tkinter as tk from pathlib import Path -from tkinter import * -from tkinter import messagebox -import tls +from chat_client.app import ChatApp +from chat_client.network import ServerConnection +from chat_client.ui import MainWindow DEFAULT_HOST = "127.0.0.1" DEFAULT_PORT = 5557 DEFAULT_CAFILE = Path(__file__).with_name("cert.pem") -# The server pings every 20 s, so this much silence means the connection is dead. -SERVER_TIMEOUT = 60 -RECONNECT_DELAYS = [1, 2, 4, 8, 15, 30] -log = logging.getLogger("client") - -class ServerConnection: - def __init__(self, host, port, cafile, events): - context = tls.client_context(cafile) - sock = socket.create_connection((host, port), timeout=5) - self.sock = tls.LockedSocket(context.wrap_socket(sock, server_hostname=host)) - self.events = events - # The reading thread answers pings, so sends come from two threads. - self.send_lock = threading.Lock() - self.last_seen = time.monotonic() - - def start(self): - """Queue each message except pings as (self, message). - - When the connection ends, queue (self, {"type": "disconnected"}). - """ - threading.Thread(target=self._read_loop, daemon=True).start() - - def send(self, type_, /, **fields): - data = (json.dumps({"type": type_, **fields}) + "\n").encode() - with self.send_lock: - self.sock.sendall(data) - - def _read_loop(self): - try: - with self.sock.makefile() as reader: - for line in reader: - self.last_seen = time.monotonic() - try: - message = json.loads(line) - except (ValueError, RecursionError): - continue - if not isinstance(message, dict): - continue - if message.get("type") == "ping": - self.send("pong") - else: - self.events.put((self, message)) - except (OSError, ValueError): - pass - self.events.put((self, {"type": "disconnected"})) - - def close(self): - self.sock.close() - - -server = None -events = queue.Queue() -current_chat = None -current_user = None -members = [] -pending = [] -pending_list = None -signup_credentials = None -login_attempt = None -# Kept while logged in, to log in again after a dropped connection. -saved_login = None -# Changes in clear_app_data(), so a reconnect that was already running is ignored. -session = 0 -reconnect_attempts = 0 - - -def connect_to_server(): - global server - if server: - return True - try: - server = ServerConnection(args.host, args.port, args.cafile, events) - server.start() - return True - except FileNotFoundError: - messagebox.showerror("Connection Error", f"Certificate {args.cafile} not found. Ask the server owner for it.") - return False - except OSError as e: - messagebox.showerror("Connection Error", f"Failed to connect to server: {e}") - return False - - -def send(type_, /, **fields): - if not server: - if current_user: - messagebox.showerror("Connection Error", "Reconnecting to the server. Try again in a moment.") - else: - messagebox.showerror("Connection Error", "Not connected to the server.") - return - try: - server.send(type_, **fields) - except OSError as e: - messagebox.showerror("Connection Error", f"Failed to reach the server: {e}") - - -def poll_events(): - while True: - try: - conn, message = events.get_nowait() - except queue.Empty: - break - try: - if callable(message): - # Work handed over from another thread. - message() - continue - # Skip events left over from a closed connection. - if conn is not server: - continue - handler = EVENT_HANDLERS.get(message.get("type")) - if handler: - handler(message) - except Exception: - # A bad event must not stop the event loop. - log.exception("Error handling a server event") - root.after(50, poll_events) - - -def check_server_alive(): - if server and time.monotonic() - server.last_seen > SERVER_TIMEOUT: - log.warning("No pings from the server, reconnecting") - # The reading thread then reports the connection as dropped. - server.close() - root.after(5000, check_server_alive) - - -def schedule_reconnect(): - global reconnect_attempts - delay = RECONNECT_DELAYS[min(reconnect_attempts, len(RECONNECT_DELAYS) - 1)] - reconnect_attempts += 1 - set_status(f"Lost connection. Reconnecting in {delay} s...") - root.after(delay * 1000, start_reconnect, session) - - -def start_reconnect(for_session): - if for_session != session: - return - set_status("Reconnecting...") - - def connect(): - try: - conn = ServerConnection(args.host, args.port, args.cafile, events) - except OSError as e: - log.info("Reconnect failed: %s", e) - conn = None - events.put((None, lambda: finish_reconnect(for_session, conn))) - - # Connecting can take seconds, so keep it off the Tk thread. - threading.Thread(target=connect, daemon=True).start() - - -def finish_reconnect(for_session, conn): - global server, login_attempt - if for_session != session or server: - if conn: - conn.close() - return - if not conn: - schedule_reconnect() - return - server = conn - server.start() - login_attempt = saved_login - send("login", username=saved_login[0], password=saved_login[1]) - - -def clear_app_data(): - global server, current_chat, current_user, login_attempt, saved_login, session, reconnect_attempts - if server: - server.close() - server = None - current_chat = None - current_user = None - login_attempt = None - saved_login = None - session += 1 - reconnect_attempts = 0 - members.clear() - pending.clear() - refresh_pending_list() - chat.delete(0, END) - person.delete(0, END) - chatframe.config(text="Chat:") - root.title("Chat Room!") - set_status("") - show_login_required() - - -def show_login_required(): - login_required_frame.lift() - - -def hide_login_required(): - login_required_frame.lower() - - -def set_status(text): - status_text.set(text) - - -def require_login(): - if not current_user: - messagebox.showerror("Login Required", "Log in first.") - return False - return True - - -def show_profile(): - if current_user: - messagebox.showinfo("Profile", f"Logged in as: {current_user}") - - -def credentials_dialog(title, button_text, on_submit): - dialog = Toplevel(root) - dialog.title(title) - dialog.transient(root) - dialog.resizable(False, False) - - Label(dialog, text="Username:").grid(row=0, column=0, padx=5, pady=5, sticky=E) - Label(dialog, text="Password:").grid(row=1, column=0, padx=5, pady=5, sticky=E) - - username_entry = Entry(dialog) - password_entry = Entry(dialog, show="*") - username_entry.grid(row=0, column=1, padx=5, pady=5) - password_entry.grid(row=1, column=1, padx=5, pady=5) - username_entry.focus_set() - - def submit(event=None): - username = username_entry.get().strip() - password = password_entry.get() - if not username or not password: - messagebox.showerror("Error", "Username and password cannot be empty.", parent=dialog) - return - dialog.destroy() - on_submit(username, password) - - Button(dialog, text=button_text, command=submit).grid(row=2, columnspan=2, pady=5) - dialog.bind("", submit) - - -def signup(): - credentials_dialog("Sign Up", "Sign up!", signup_user) - - -def signup_user(username, password): - global signup_credentials - if current_user: - messagebox.showerror("Sign Up", "Sign out first.") - return - if connect_to_server(): - signup_credentials = (username, password) - send("signup", username=username, password=password) - - -def on_signup_result(message): - global signup_credentials - credentials, signup_credentials = signup_credentials, None - if message.get("ok"): - messagebox.showinfo("Sign Up Success", "User added successfully.") - if credentials: - login_user(*credentials) - else: - messagebox.showerror("Sign Up Failed", message.get("error", "Sign up failed.")) - - -def login(): - credentials_dialog("Login", "Login!", login_user) - - -def login_user(username, password): - global login_attempt - if current_user: - messagebox.showerror("Login", f"Already logged in as {current_user}. Sign out first.") - return - if connect_to_server(): - login_attempt = (username, password) - send("login", username=username, password=password) - - -def on_login_result(message): - global current_user, login_attempt, saved_login, reconnect_attempts - credentials, login_attempt = login_attempt, None - # Still logged in from before the connection dropped. - reconnected = current_user is not None - if not message.get("ok"): - error = message.get("error", "Login failed.") - if reconnected: - clear_app_data() - messagebox.showerror("Disconnected", f"Reconnected, but could not log in again: {error}") - else: - messagebox.showerror("Login Failed", error) - return - saved_login = credentials - current_user = message["username"] - reconnect_attempts = 0 - if reconnected: - set_status("Reconnected.") - if current_chat: - send("history", username=current_chat) - return - root.title(f"Chat Room! - {current_user}") - hide_login_required() - text_input.focus_set() - messagebox.showinfo("Login Success", "Login successful.") - - -def on_friends(message): - members.clear() - person.delete(0, END) - for username in message.get("users", []): - add_member(username) - if current_chat in members: - person.selection_set(members.index(current_chat)) - - -def add_member(username): - if username not in members: - members.append(username) - person.insert(END, username) - - -def on_friend_added(message): - username = message["username"] - add_member(username) - if username in pending: - pending.remove(username) - refresh_pending_list() - set_status(f"You and {username} are now friends.") - - -def on_pending(message): - pending[:] = message.get("users", []) - refresh_pending_list() - if pending: - set_status(f"Pending requests: {len(pending)}") - - -def on_request_received(message): - username = message["username"] - if username not in pending: - pending.append(username) - refresh_pending_list() - set_status(f"New friend request from {username}. See Friends > Pending Requests.") - - -def on_request_rejected(message): - messagebox.showinfo("Request Rejected", f"Your chat request to {message['username']} was rejected.") - - -def local_time(timestamp): - try: - utc = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S").replace(tzinfo=UTC) - # astimezone() fails for very old or far-future dates. - return utc.astimezone().strftime("%Y-%m-%d %H:%M:%S") - except (TypeError, ValueError, OverflowError, OSError): - return timestamp - - -def format_message(message): - sender = "You" if message["sender"] == current_user else message["sender"] - # Listbox rows can't show line breaks. - text = " ".join(message["text"].splitlines()) - return f"{local_time(message['timestamp'])} {sender}: {text}" - - -def on_history(message): - if message.get("username") != current_chat: - return - chat.delete(0, END) - for item in message.get("messages", []): - chat.insert(END, format_message(item)) - chat.yview(END) - - -def on_message(message): - other = message["receiver"] if message["sender"] == current_user else message["sender"] - if other == current_chat: - chat.insert(END, format_message(message)) - chat.yview(END) - else: - set_status(f"New message from {other}.") - - -def on_info(message): - set_status(message.get("text", "")) - - -def on_error(message): - messagebox.showerror("Error", message.get("text", "Unknown error.")) - - -def on_disconnected(message): - global server - server.close() - server = None - if current_user: - schedule_reconnect() - else: - clear_app_data() - - -EVENT_HANDLERS = { - "signup_result": on_signup_result, - "login_result": on_login_result, - "friends": on_friends, - "friend_added": on_friend_added, - "pending": on_pending, - "request_received": on_request_received, - "request_rejected": on_request_rejected, - "history": on_history, - "message": on_message, - "info": on_info, - "error": on_error, - "disconnected": on_disconnected, -} - - -def select_member(event): - global current_chat - selection = person.curselection() - if not selection: - return - current_chat = person.get(selection[0]) - chatframe.config(text=f"Chat: {current_chat}") - chat.delete(0, END) - send("history", username=current_chat) - - -def send_message(event=None): - text = input_text.get() - if not text.strip(): - return - if not current_chat: - messagebox.showerror("Send Error", "Pick a member to chat with first.") - return - send("message", to=current_chat, text=text) - input_text.set("") - - -def find_user(): - if not require_login(): - return - dialog = Toplevel(root) - dialog.title("Find User") - dialog.transient(root) - dialog.resizable(False, False) - - Label(dialog, text="Username:").grid(row=0, column=0, padx=5, pady=5) - username_entry = Entry(dialog) - username_entry.grid(row=0, column=1, padx=5, pady=5) - username_entry.focus_set() - - def submit(event=None): - username = username_entry.get().strip() - if not username: - messagebox.showerror("Error", "Username cannot be empty.", parent=dialog) - return - dialog.destroy() - send("friend_request", username=username) - - Button(dialog, text="Send request", command=submit).grid(row=1, columnspan=2, pady=5) - dialog.bind("", submit) - - -def refresh_pending_list(): - if pending_list and pending_list.winfo_exists(): - pending_list.delete(0, END) - for username in pending: - pending_list.insert(END, username) - - -def pending_requests(): - global pending_list - if not require_login(): - return - if pending_list and pending_list.winfo_exists(): - pending_list.winfo_toplevel().lift() - return - - dialog = Toplevel(root) - dialog.title("Pending Requests") - dialog.geometry("300x300") - dialog.transient(root) - - Label(dialog, text="Pending Requests:").pack(pady=10) - - frame = Frame(dialog) - frame.pack(fill=BOTH, expand=True, padx=10) - scrollbar = Scrollbar(frame, orient=VERTICAL) - pending_list = Listbox(frame, selectmode=SINGLE, exportselection=False, yscrollcommand=scrollbar.set) - scrollbar.config(command=pending_list.yview) - scrollbar.pack(side=RIGHT, fill=Y) - pending_list.pack(side=LEFT, fill=BOTH, expand=True) - - def respond(accept): - selection = pending_list.curselection() - if not selection: - messagebox.showerror("Error", "No request selected.", parent=dialog) - return - username = pending_list.get(selection[0]) - send("respond_request", username=username, accept=accept) - if username in pending: - pending.remove(username) - refresh_pending_list() - - buttons = Frame(dialog) - Button(buttons, text="Accept", command=lambda: respond(True), bg="green", fg="white", width=6).pack( - side=LEFT, padx=5 - ) - Button(buttons, text="Reject", command=lambda: respond(False), bg="red", fg="white", width=6).pack( - side=RIGHT, padx=5 +def main(): + parser = argparse.ArgumentParser(description="Run the chat client.") + parser.add_argument("--host", default=DEFAULT_HOST) + parser.add_argument("--port", type=int, default=DEFAULT_PORT) + parser.add_argument( + "--cafile", default=DEFAULT_CAFILE, help="server certificate to trust (default: cert.pem next to this script)" ) - buttons.pack(pady=10) - - refresh_pending_list() - send("pending") - - -def exit_application(): - if ( - messagebox.askquestion("Exit Application", "Are you sure you want to exit the application?", icon="warning") - == "yes" - ): - if server: - server.close() - root.destroy() - - -def sign_out(): - clear_app_data() - - -def info(): - messagebox.showinfo("Info", "Chat Room\nCreated by Amin Niaziardekani, Swapnaneel Sarkhel and Ajdin Buljko") + args = parser.parse_args() + logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s") + root = tk.Tk() + app = ChatApp( + lambda app: MainWindow(root, app), + lambda events: ServerConnection(args.host, args.port, args.cafile, events), + ) + app.start() + root.mainloop() -parser = argparse.ArgumentParser(description="Run the chat client.") -parser.add_argument("--host", default=DEFAULT_HOST) -parser.add_argument("--port", type=int, default=DEFAULT_PORT) -parser.add_argument( - "--cafile", default=DEFAULT_CAFILE, help="server certificate to trust (default: cert.pem next to this script)" -) -args = parser.parse_args() -logging.basicConfig(format="%(asctime)s %(levelname)s %(message)s") - -root = Tk() -root.geometry("800x640") -root.minsize(600, 400) -root.title("Chat Room!") -root.protocol("WM_DELETE_WINDOW", exit_application) -root.columnconfigure(1, weight=1) -root.rowconfigure(0, weight=1) - -menu = Menu(root) -root.config(menu=menu) - -filemenu = Menu(menu, tearoff=0) -menu.add_cascade(label="File", menu=filemenu) -filemenu.add_command(label="Login", command=login) -filemenu.add_command(label="Sign up", command=signup) -filemenu.add_command(label="Sign Out", command=sign_out) -filemenu.add_separator() -filemenu.add_command(label="Exit", command=exit_application) - -friendsmenu = Menu(menu, tearoff=0) -menu.add_cascade(label="Friends", menu=friendsmenu) -friendsmenu.add_command(label="Find User", command=find_user) -friendsmenu.add_command(label="Pending Requests", command=pending_requests) - -infomenu = Menu(menu, tearoff=0) -menu.add_cascade(label="Info", menu=infomenu) -infomenu.add_command(label="Profile", command=show_profile) -infomenu.add_command(label="Info", command=info) - -personframe = LabelFrame(root, text="Members:", font=("Arial", 15, "bold"), bg="white", fg="black", bd=5) -personframe.grid(row=0, column=0, rowspan=2, sticky=NSEW) - -scroll2_y = Scrollbar(personframe, orient=VERTICAL) -person = Listbox( - personframe, - highlightthickness=0, - selectbackground="deep sky blue", - selectmode=SINGLE, - font=("Arial", 15), - bg="white", - fg="green", - bd=0, - activestyle="none", - exportselection=False, - width=14, - yscrollcommand=scroll2_y.set, -) -scroll2_y.config(command=person.yview) -scroll2_y.pack(side=RIGHT, fill=Y) -person.pack(side=LEFT, fill=BOTH, expand=True, padx=5, pady=5) -person.bind("<>", select_member) - -chatframe = LabelFrame(root, text="Chat:", font=("Arial", 15, "bold"), bg="white", fg="black", bd=5) -chatframe.grid(row=0, column=1, sticky=NSEW) - -scroll1_y = Scrollbar(chatframe, orient=VERTICAL) -chat = Listbox( - chatframe, - highlightthickness=0, - selectbackground="deep sky blue", - selectmode=EXTENDED, - font=("Arial", 15), - bg="white", - fg="green", - bd=0, - activestyle="none", - exportselection=False, - yscrollcommand=scroll1_y.set, -) -scroll1_y.config(command=chat.yview) -scroll1_y.pack(side=RIGHT, fill=Y) -chat.pack(side=LEFT, fill=BOTH, expand=True, padx=5, pady=5) - -textframe = LabelFrame(root, bg="white", bd=5) -textframe.grid(row=1, column=1, sticky=EW) - -input_text = StringVar() -text_input = Entry(textframe, font=("Arial", 15), textvariable=input_text) -text_input.pack(side=LEFT, fill=X, expand=True, padx=5, pady=5, ipady=12) -text_input.bind("", send_message) - -send_button = Button(textframe, text="Send", bg="white", command=send_message) -send_button.pack(side=RIGHT, padx=5, pady=5, ipadx=5, ipady=10) - -status_text = StringVar() -Label(root, textvariable=status_text, anchor=W).grid(row=2, column=0, columnspan=2, sticky=EW, padx=5) - -login_required_frame = Frame(root, bg="grey") -Label( - login_required_frame, text="Sign in or login required to continue", bg="grey", fg="white", font=("Arial", 20) -).place(relx=0.5, rely=0.5, anchor=CENTER) -login_required_frame.place(x=0, y=0, relwidth=1, relheight=1) -show_login_required() -root.after(50, poll_events) -root.after(5000, check_server_alive) -root.mainloop() +if __name__ == "__main__": + main() diff --git a/pyproject.toml b/pyproject.toml index b85beeb..75f5d0d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -18,8 +18,6 @@ line-length = 120 [tool.ruff.lint] select = ["F", "E9", "B", "UP"] -# Allow `from tkinter import *` in client.py. -ignore = ["F403", "F405"] [tool.pytest.ini_options] testpaths = ["tests"] diff --git a/tests/test_client.py b/tests/test_client.py new file mode 100644 index 0000000..fd41cad --- /dev/null +++ b/tests/test_client.py @@ -0,0 +1,341 @@ +import time + +import pytest + +from chat_client import app as client_app +from chat_client.app import ChatApp + + +class FakeView: + def __init__(self): + self.scheduled = [] + self.errors = [] + self.infos = [] + self.status = "" + self.logged_in = None + self.members = [] + self.selected = None + self.chat = (None, []) + self.pending = None + self.credentials_prompt = None + self.confirm_answer = True + self.closed = False + + def run_scheduled(self, name): + """Run the scheduled calls to the method with this name, and return their delays.""" + due = [item for item in self.scheduled if item[1].__name__ == name] + for item in due: + self.scheduled.remove(item) + for _, func, args in due: + func(*args) + return [ms for ms, _, _ in due] + + def after(self, ms, func, *args): + self.scheduled.append((ms, func, args)) + + def close(self): + self.closed = True + + def show_error(self, title, text): + self.errors.append((title, text)) + + def show_info(self, title, text): + self.infos.append((title, text)) + + def confirm(self, title, text): + return self.confirm_answer + + def ask_credentials(self, title, button_text, on_submit): + self.credentials_prompt = (title, on_submit) + + def ask_username(self, on_submit): + on_submit("bob") + + def show_pending(self, users, on_respond): + self.pending = list(users) + + def set_pending(self, users): + if self.pending is not None: + self.pending = list(users) + + def set_status(self, text): + self.status = text + + def set_logged_in(self, username): + self.logged_in = username + + def set_members(self, users, selected): + self.members = list(users) + self.selected = selected if selected in users else None + + def set_chat(self, username, lines): + self.chat = (username, list(lines)) + + def add_chat_line(self, line): + self.chat[1].append(line) + + +class FakeConnection: + def __init__(self, events): + self.events = events + self.sent = [] + self.started = False + self.closed = False + self.last_seen = time.monotonic() + + def start(self): + self.started = True + + def send(self, type_, /, **fields): + if self.closed: + raise OSError("connection closed") + self.sent.append({"type": type_, **fields}) + + def close(self): + self.closed = True + + def receive(self, type_, /, **fields): + self.events.put((self, {"type": type_, **fields})) + + def drop(self): + self.events.put((self, {"type": "disconnected"})) + + +class Connector: + def __init__(self): + self.connections = [] + self.error = None + + def __call__(self, events): + if self.error: + raise self.error + conn = FakeConnection(events) + self.connections.append(conn) + return conn + + +@pytest.fixture +def connector(): + return Connector() + + +@pytest.fixture +def app(connector): + chat = ChatApp(lambda app: FakeView(), connector, run_in_background=lambda func: func()) + chat.start() + return chat + + +def log_in(app, connector, username="alice", friends=("bob",)): + app.login_user(username, "password1") + conn = connector.connections[-1] + conn.receive("login_result", ok=True, username=username) + conn.receive("friends", users=list(friends)) + conn.receive("pending", users=[]) + app.process_events() + return conn + + +def test_login(app, connector): + app.login() + assert app.view.credentials_prompt[0] == "Login" + app.view.credentials_prompt[1]("alice", "password1") + conn = connector.connections[0] + assert conn.started + assert conn.sent == [{"type": "login", "username": "alice", "password": "password1"}] + conn.receive("login_result", ok=True, username="alice") + conn.receive("friends", users=["bob", "carol"]) + app.process_events() + assert app.view.logged_in == "alice" + assert app.view.members == ["bob", "carol"] + assert app.view.infos == [("Login Success", "Login successful.")] + + +def test_failed_login_stays_logged_out(app, connector): + app.login_user("alice", "wrong-password") + connector.connections[0].receive("login_result", ok=False, error="Invalid credentials.") + app.process_events() + assert app.view.logged_in is None + assert app.view.errors == [("Login Failed", "Invalid credentials.")] + assert app.saved_login is None + + +def test_signup_then_logs_in(app, connector): + app.signup_user("alice", "password1") + conn = connector.connections[0] + conn.receive("signup_result", ok=True) + app.process_events() + assert conn.sent[-1] == {"type": "login", "username": "alice", "password": "password1"} + + +@pytest.mark.parametrize( + "error, text", + [ + (FileNotFoundError(2, "certificate not found", "cert.pem"), "Certificate cert.pem not found."), + (ConnectionRefusedError("refused"), "Failed to connect to server: refused"), + ], +) +def test_connect_errors_are_shown(app, connector, error, text): + connector.error = error + app.login_user("alice", "password1") + assert app.view.errors[0][1].startswith(text) + assert app.server is None + + +def test_chat_history_and_messages(app, connector): + conn = log_in(app, connector) + app.select_chat("bob") + assert conn.sent[-1] == {"type": "history", "username": "bob"} + message = {"sender": "alice", "receiver": "bob", "text": "hi\nthere", "timestamp": "not a time"} + conn.receive("history", username="bob", messages=[message]) + conn.receive("message", sender="bob", receiver="alice", text="yo", timestamp="t") + conn.receive("message", sender="carol", receiver="alice", text="psst", timestamp="t") + app.process_events() + assert app.view.chat == ("bob", ["not a time You: hi there", "t bob: yo"]) + assert app.view.status == "New message from carol." + + +def test_send_message(app, connector): + conn = log_in(app, connector) + assert not app.send_message(" ") + assert not app.send_message("hi") + assert app.view.errors == [("Send Error", "Pick a member to chat with first.")] + app.select_chat("bob") + assert app.send_message("hi") + assert conn.sent[-1] == {"type": "message", "to": "bob", "text": "hi"} + + +def test_friend_requests(app, connector): + conn = log_in(app, connector, friends=()) + app.find_user() + assert conn.sent[-1] == {"type": "friend_request", "username": "bob"} + conn.receive("request_received", username="carol") + conn.receive("request_received", username="dave") + app.process_events() + app.open_pending() + assert app.view.pending == ["carol", "dave"] + app.respond_request("carol", True) + assert conn.sent[-1] == {"type": "respond_request", "username": "carol", "accept": True} + assert app.view.pending == ["dave"] + conn.receive("friend_added", username="dave") + app.process_events() + assert app.view.pending == [] + assert app.view.members == ["dave"] + + +def test_guest_commands_need_login(app): + app.find_user() + app.open_pending() + assert app.view.errors == [("Login Required", "Log in first.")] * 2 + + +def test_events_from_an_old_connection_are_ignored(app, connector): + old = log_in(app, connector) + app.sign_out() + old.receive("message", sender="bob", receiver="alice", text="late", timestamp="t") + app.process_events() + assert app.view.status == "" + + +def test_a_bad_event_does_not_stop_the_rest(app, connector): + conn = log_in(app, connector) + conn.receive("message", text="no sender") + conn.receive("info", text="still working") + app.process_events() + assert app.view.status == "still working" + + +def test_reconnects_and_logs_in_again(app, connector): + old = log_in(app, connector) + app.select_chat("bob") + old.drop() + app.process_events() + assert old.closed and app.server is None + assert app.view.logged_in == "alice" + assert app.view.status == "Lost connection. Reconnecting in 1 s..." + assert app.send_message("lost?") is True + assert app.view.errors[-1] == ("Connection Error", "Reconnecting to the server. Try again in a moment.") + + assert app.view.run_scheduled("start_reconnect") == [1000] + app.process_events() + new = connector.connections[-1] + assert new is not old and new.started + assert new.sent == [{"type": "login", "username": "alice", "password": "password1"}] + new.receive("login_result", ok=True, username="alice") + new.receive("friends", users=["bob"]) + app.process_events() + assert app.view.status == "Reconnected." + assert new.sent[-1] == {"type": "history", "username": "bob"} + assert app.view.selected == "bob" + assert app.view.infos == [("Login Success", "Login successful.")] + assert app.reconnect_attempts == 0 + + +def test_reconnect_backs_off(app, connector): + log_in(app, connector).drop() + app.process_events() + connector.error = ConnectionRefusedError("refused") + delays = [] + for _ in range(8): + delays += app.view.run_scheduled("start_reconnect") + app.process_events() + assert delays == [ms * 1000 for ms in client_app.RECONNECT_DELAYS] + [30_000, 30_000] + + +def test_sign_out_stops_reconnecting(app, connector): + log_in(app, connector).drop() + app.process_events() + app.sign_out() + count = len(connector.connections) + app.view.run_scheduled("start_reconnect") + app.process_events() + assert len(connector.connections) == count + assert app.server is None + + +def test_sign_out_while_connecting_drops_the_new_connection(app, connector): + log_in(app, connector).drop() + app.process_events() + app.view.run_scheduled("start_reconnect") + app.sign_out() + app.process_events() + assert connector.connections[-1].closed + assert app.server is None + + +def test_failed_login_after_reconnect_signs_out(app, connector): + log_in(app, connector).drop() + app.process_events() + app.view.run_scheduled("start_reconnect") + app.process_events() + connector.connections[-1].receive("login_result", ok=False, error="Too many failed logins.") + app.process_events() + assert app.view.logged_in is None and app.current_user is None + assert app.view.errors[-1] == ("Disconnected", "Reconnected, but could not log in again: Too many failed logins.") + + +def test_guest_disconnect_does_not_reconnect(app, connector): + app.login_user("alice", "password1") + connector.connections[0].drop() + app.process_events() + assert app.server is None + assert not app.view.run_scheduled("start_reconnect") + + +def test_silent_server_is_dropped(app, connector): + conn = log_in(app, connector) + app.view.run_scheduled("check_server_alive") + assert not conn.closed + conn.last_seen -= client_app.SERVER_TIMEOUT + 1 + app.view.run_scheduled("check_server_alive") + assert conn.closed + + +def test_exit_asks_first(app, connector): + conn = log_in(app, connector) + app.view.confirm_answer = False + app.exit() + assert not app.view.closed + app.view.confirm_answer = True + app.exit() + assert app.view.closed and conn.closed From b73852d720a2e271450d58432c90a90b9a537a46 Mon Sep 17 00:00:00 2001 From: ABuljko Date: Sat, 3 Oct 2026 18:38:19 +0200 Subject: [PATCH 6/6] Fix client login races and lost message text --- chat_client/app.py | 35 ++++++++++++++++++++++++++++------- tests/test_client.py | 31 ++++++++++++++++++++++++++++++- 2 files changed, 58 insertions(+), 8 deletions(-) diff --git a/chat_client/app.py b/chat_client/app.py index 0205ec6..bd438fe 100644 --- a/chat_client/app.py +++ b/chat_client/app.py @@ -83,16 +83,19 @@ def connect_to_server(self): return True def send(self, type_, /, **fields): + """Return False, after telling the user, if the message couldn't be sent.""" if not self.server: if self.current_user: self.view.show_error("Connection Error", "Reconnecting to the server. Try again in a moment.") else: self.view.show_error("Connection Error", "Not connected to the server.") - return + return False try: self.server.send(type_, **fields) except OSError as e: self.view.show_error("Connection Error", f"Failed to reach the server: {e}") + return False + return True def process_events(self): while True: @@ -168,6 +171,7 @@ def reset(self): self.server = None self.current_user = None self.current_chat = None + self.signup_credentials = None self.login_attempt = None self.saved_login = None self.session += 1 @@ -180,6 +184,13 @@ def reset(self): self.view.set_status("") self.view.set_logged_in(None) + def waiting_for_answer(self): + """A second login or signup before the first is answered would mix up which password belongs to whom.""" + if self.login_attempt or self.signup_credentials: + self.view.show_error("Please Wait", "Still waiting for the server to answer.") + return True + return False + def require_login(self): if not self.current_user: self.view.show_error("Login Required", "Log in first.") @@ -193,6 +204,8 @@ def signup_user(self, username, password): if self.current_user: self.view.show_error("Sign Up", "Sign out first.") return + if self.waiting_for_answer(): + return if self.connect_to_server(): self.signup_credentials = (username, password) self.send("signup", username=username, password=password) @@ -204,6 +217,8 @@ def login_user(self, username, password): if self.current_user: self.view.show_error("Login", f"Already logged in as {self.current_user}. Sign out first.") return + if self.waiting_for_answer(): + return if self.connect_to_server(): self.login_attempt = (username, password) self.send("login", username=username, password=password) @@ -248,14 +263,13 @@ def select_chat(self, username): self.send("history", username=username) def send_message(self, text): - """Return True if the input can be cleared.""" + """Return True if the text was sent and the input can be cleared.""" if not text.strip(): return False if not self.current_chat: self.view.show_error("Send Error", "Pick a member to chat with first.") return False - self.send("message", to=self.current_chat, text=text) - return True + return self.send("message", to=self.current_chat, text=text) def format_message(self, message): sender = "You" if message["sender"] == self.current_user else message["sender"] @@ -274,6 +288,9 @@ def on_signup_result(self, message): def on_login_result(self, message): credentials, self.login_attempt = self.login_attempt, None + if credentials is None: + log.warning("Ignoring a login result nobody asked for") + return # Still logged in from before the connection dropped. reconnected = self.current_user is not None if not message.get("ok"): @@ -285,7 +302,8 @@ def on_login_result(self, message): self.view.show_error("Login Failed", error) return self.saved_login = credentials - self.current_user = message["username"] + # The name that was sent, so it always matches the saved password. + self.current_user = credentials[0] self.reconnect_attempts = 0 if reconnected: self.view.set_status("Reconnected.") @@ -351,5 +369,8 @@ def on_disconnected(self, message): self.server = None if self.current_user: self.schedule_reconnect() - else: - self.reset() + return + was_waiting = self.login_attempt or self.signup_credentials + self.reset() + if was_waiting: + self.view.show_error("Disconnected", "Lost connection to the server.") diff --git a/tests/test_client.py b/tests/test_client.py index fd41cad..6b28c60 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -253,7 +253,7 @@ def test_reconnects_and_logs_in_again(app, connector): assert old.closed and app.server is None assert app.view.logged_in == "alice" assert app.view.status == "Lost connection. Reconnecting in 1 s..." - assert app.send_message("lost?") is True + assert app.send_message("lost?") is False assert app.view.errors[-1] == ("Connection Error", "Reconnecting to the server. Try again in a moment.") assert app.view.run_scheduled("start_reconnect") == [1000] @@ -339,3 +339,32 @@ def test_exit_asks_first(app, connector): app.view.confirm_answer = True app.exit() assert app.view.closed and conn.closed + + +def test_second_login_waits_for_the_first(app, connector): + app.login_user("alice", "alice-password") + app.login_user("bob", "bob-password") + app.signup_user("carol", "carol-password") + assert app.view.errors == [("Please Wait", "Still waiting for the server to answer.")] * 2 + conn = connector.connections[0] + assert [m["type"] for m in conn.sent] == ["login"] + conn.receive("login_result", ok=True, username="alice") + app.process_events() + assert app.current_user == "alice" + assert app.saved_login == ("alice", "alice-password") + + +def test_login_result_nobody_asked_for_is_ignored(app, connector): + app.signup_user("alice", "password1") + connector.connections[0].receive("login_result", ok=True, username="mallory") + app.process_events() + assert app.current_user is None + + +def test_drop_while_logging_in_is_reported(app, connector): + app.login_user("alice", "password1") + connector.connections[0].drop() + app.process_events() + assert app.view.errors == [("Disconnected", "Lost connection to the server.")] + app.login_user("alice", "password1") + assert len(connector.connections) == 2