diff --git a/chatroom_db.py b/chatroom_db.py index 9d1a71f..794079e 100644 --- a/chatroom_db.py +++ b/chatroom_db.py @@ -72,6 +72,12 @@ AND sender IN (SELECT username FROM users) AND receiver IN (SELECT username FROM users) """, + """ + DELETE FROM requests WHERE status <> 'accepted' AND EXISTS ( + SELECT 1 FROM requests AS r + WHERE r.sender = requests.receiver AND r.receiver = requests.sender AND r.status = 'accepted' + ) + """, "DROP TABLE old_users", "DROP TABLE old_messages", "DROP TABLE old_requests", @@ -137,11 +143,14 @@ def hash_password(password): def verify_password(password, stored): - if not stored or not stored.startswith("scrypt$"): + if not isinstance(stored, str) or not stored.startswith("scrypt$"): + return False + try: + _, n, r, p, salt, digest = stored.split("$") + candidate = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=int(n), r=int(r), p=int(p)) + return hmac.compare_digest(candidate, bytes.fromhex(digest)) + except (ValueError, OverflowError, TypeError): return False - _, n, r, p, salt, digest = stored.split("$") - candidate = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=int(n), r=int(r), p=int(p)) - return hmac.compare_digest(candidate, bytes.fromhex(digest)) def add_user(username, password): diff --git a/server.py b/server.py index d3a7c1c..384d455 100644 --- a/server.py +++ b/server.py @@ -43,6 +43,7 @@ clients_lock = threading.Lock() connections = set() connections_lock = threading.Lock() +chat_lock = threading.Lock() class ProtocolError(Exception): @@ -293,11 +294,12 @@ def require_friend(conn, other): def handle_history(conn, message): other = username_field(message) require_friend(conn, other) - history = [ - {"sender": sender, "receiver": receiver, "text": text, "timestamp": timestamp} - for sender, receiver, text, timestamp in db.get_chat_history(conn.username, other) - ] - conn.send("history", username=other, messages=history) + with chat_lock: + history = [ + {"sender": sender, "receiver": receiver, "text": text, "timestamp": timestamp} + for sender, receiver, text, timestamp in db.get_chat_history(conn.username, other) + ] + conn.send("history", username=other, messages=history) def handle_message(conn, message): @@ -308,11 +310,12 @@ def handle_message(conn, message): if len(text) > MAX_MESSAGE: raise BadRequest(f"Messages are at most {MAX_MESSAGE} characters.") require_friend(conn, receiver) - timestamp = db.add_message(conn.username, receiver, text) - fields = {"sender": conn.username, "receiver": receiver, "text": text, "timestamp": timestamp} - conn.send("message", **fields) - if receiver != conn.username: - send_to(receiver, "message", **fields) + with chat_lock: + timestamp = db.add_message(conn.username, receiver, text) + fields = {"sender": conn.username, "receiver": receiver, "text": text, "timestamp": timestamp} + conn.send("message", **fields) + if receiver != conn.username: + send_to(receiver, "message", **fields) def handle_pong(conn, message): diff --git a/tests/test_db.py b/tests/test_db.py index 25aa930..e09b852 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -31,6 +31,25 @@ def test_verify_rejects_unhashed_or_missing_values(): assert not db.verify_password("x", None) +@pytest.mark.parametrize( + "stored", + [ + "scrypt$", + "scrypt$1$2", + "scrypt$zz$8$1$ab$cd", + "scrypt$0$8$1$ab$cd", + "scrypt$3$8$1$ab$cd", + "scrypt$16384$8$1$xyz$cd", + "scrypt$16384$8$1$ab$xyz", + "scrypt$16$" + "2" * 30 + "$1$ab$cd", + "scrypt$-1$8$1$ab$cd", + b"scrypt$16384$8$1$ab$cd", + ], +) +def test_verify_rejects_broken_hashes(stored): + assert db.verify_password("pw", stored) is False + + def test_add_and_check_user(db_path): assert db.add_user("alice", "password1") assert not db.add_user("alice", "other-password") @@ -242,3 +261,18 @@ def test_newer_database_is_refused(db_path): conn.execute(f"PRAGMA user_version = {len(db.MIGRATIONS) + 1}") with pytest.raises(RuntimeError, match="newer"): db.init_db() + + +def test_migration_drops_requests_between_friends(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 requests (sender TEXT, receiver TEXT, status TEXT); + INSERT INTO users VALUES ('alice', 'a'), ('bob', 'b'); + INSERT INTO requests VALUES ('alice', 'bob', 'accepted'), ('bob', 'alice', 'pending'); + """) + db.init_db() + assert db.get_friends("alice") == ["bob"] + assert db.get_requests("alice") == [] diff --git a/tests/test_server.py b/tests/test_server.py index fee522f..a532136 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -3,12 +3,14 @@ import sqlite3 import subprocess import sys +import threading import time from contextlib import closing import pytest from conftest import REPO +import chatroom_db as db import server as chat_server @@ -397,3 +399,47 @@ def test_server_refuses_heartbeat_settings_that_cannot_work(args): [sys.executable, str(REPO / "server.py"), *args], capture_output=True, text=True, timeout=30 ) assert result.returncode == 2, result.stderr + + +class RecordingConnection: + def __init__(self, username): + self.username = username + self.sent = [] + + def send(self, type_, /, **fields): + self.sent.append((type_, fields)) + + +def test_message_sent_while_history_loads_is_shown_once(db_path, monkeypatch): + with db.connect() as conn, conn: + conn.executemany("INSERT INTO users (username, password) VALUES (?, 'x')", [("alice",), ("bob",)]) + db.add_request("alice", "bob") + db.add_request("bob", "alice") + alice, bob = RecordingConnection("alice"), RecordingConnection("bob") + monkeypatch.setattr(chat_server, "clients", {"alice": alice, "bob": bob}) + stored, go_on = threading.Event(), threading.Event() + real_send_to = chat_server.send_to + + def paused_send_to(*args, **fields): + stored.set() + go_on.wait(5) + real_send_to(*args, **fields) + + monkeypatch.setattr(chat_server, "send_to", paused_send_to) + sender = threading.Thread(target=chat_server.handle_message, args=(alice, {"to": "bob", "text": "hi"})) + loader = threading.Thread(target=chat_server.handle_history, args=(bob, {"username": "alice"})) + sender.start() + assert stored.wait(5) + loader.start() + loader.join(0.5) + go_on.set() + sender.join(5) + loader.join(5) + assert not sender.is_alive() and not loader.is_alive() + shown = [] + for type_, fields in bob.sent: + if type_ == "history": + shown = [item["text"] for item in fields["messages"]] + elif type_ == "message": + shown.append(fields["text"]) + assert shown == ["hi"], bob.sent