Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions chatroom_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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):
Expand Down
23 changes: 13 additions & 10 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
clients_lock = threading.Lock()
connections = set()
connections_lock = threading.Lock()
chat_lock = threading.Lock()


class ProtocolError(Exception):
Expand Down Expand Up @@ -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):
Expand All @@ -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):
Expand Down
34 changes: 34 additions & 0 deletions tests/test_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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") == []
46 changes: 46 additions & 0 deletions tests/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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
Loading