feat: port replicated messenger baseline into lab4

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-02 12:46:12 +03:00
parent 7d4cf242e3
commit bd41f2d93d
23 changed files with 1222 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
"""Invalid pagination limits must remain client errors."""
import unittest
from fastapi import HTTPException
from src.api import parse_limit
class LimitTests(unittest.TestCase):
def test_valid_and_extremely_long_limits(self):
self.assertEqual(parse_limit("100"), 100)
for value in ("0", "101", "-1", "x", "9" * 4301):
with self.assertRaises(HTTPException) as failure:
parse_limit(value)
self.assertEqual(failure.exception.status_code, 400)
if __name__ == "__main__":
unittest.main()
+174
View File
@@ -0,0 +1,174 @@
"""HTTP and database checks for durable Basic/Bearer sessions."""
import base64
import hashlib
import json
import os
import socket
import subprocess
import sys
import time
import unittest
import urllib.error
import urllib.request
from uuid import uuid4
import psycopg
URL = os.environ.get("DATABASE_URL")
@unittest.skipUnless(URL, "set DATABASE_URL to a disposable PostgreSQL database")
class AuthTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
subprocess.run([sys.executable, "scripts/migrate.py"], check=True)
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
cls.port = sock.getsockname()[1]
cls.start_server()
@classmethod
def start_server(cls, ttl="3600"):
cls.instance_id = None
env = {**os.environ, "SESSION_TTL_SECONDS": ttl}
cls.server = subprocess.Popen(
[sys.executable, "-m", "uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", str(cls.port)],
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
for _ in range(100):
if cls.server.poll() is not None:
raise AssertionError("API server exited during startup")
try:
cls.call("GET", "/health/ready", expected=200)
return
except (AssertionError, urllib.error.URLError):
time.sleep(0.05)
raise AssertionError("API server did not become ready")
@classmethod
def stop_server(cls):
cls.server.terminate()
try:
cls.server.wait(timeout=5)
except subprocess.TimeoutExpired:
cls.server.kill()
cls.server.wait(timeout=5)
@classmethod
def tearDownClass(cls):
cls.stop_server()
@classmethod
def call(cls, method, path, *, body=None, authorization=None, user_id=None, expected=200):
headers = {"Accept": "application/json"}
data = None
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode()
headers["Content-Type"] = "application/json"
if authorization is not None:
headers["Authorization"] = authorization
if user_id is not None:
headers["X-User-Id"] = user_id
request = urllib.request.Request(
f"http://127.0.0.1:{cls.port}{path}", data=data, headers=headers, method=method,
)
try:
response = urllib.request.urlopen(request, timeout=5)
except urllib.error.HTTPError as error:
response = error
with response:
status = response.status
response_headers = response.headers
data = response.read()
assert status == expected, (method, path, expected, status)
request_id = response_headers.get("X-Request-Id")
assert request_id
instance_id = response_headers.get("X-Instance-Id")
assert instance_id
if cls.instance_id is None:
cls.instance_id = instance_id
else:
assert instance_id == cls.instance_id
payload = json.loads(data) if data else None
if status >= 400:
assert payload["error"]["request_id"] == request_id
assert "password" not in data.decode().lower()
assert "token" not in data.decode().lower()
return payload, response_headers
def user(self, password="Пароль:очень-длинный-123"):
username = "u_" + uuid4().hex[:16]
body = {"username": username, "display_name": "Алиса", "password": password}
user, _ = self.call("POST", "/api/v1/users", body=body, expected=201)
self.assertNotIn("password", user)
return user, password
def login(self, username, password, expected=201):
encoded = base64.b64encode(f"{username}:{password}".encode()).decode()
return self.call("POST", "/api/v1/auth/sessions", authorization="Basic " + encoded, expected=expected)
def test_basic_bearer_logout_and_storage(self):
alice, password = self.user()
bob, _ = self.user()
session, headers = self.login(alice["username"], password)
self.assertEqual(session["token_type"], "Bearer")
self.assertEqual(session["user"], alice)
self.assertGreaterEqual(len(base64.urlsafe_b64decode(session["token"] + "=" * (-len(session["token"]) % 4))), 32)
self.assertEqual(headers.get("Cache-Control"), "no-store")
bearer = "Bearer " + session["token"]
me, _ = self.call("GET", "/api/v1/users/me", authorization=bearer, user_id=bob["id"])
self.assertEqual(me, alice)
with psycopg.connect(URL) as conn:
row = conn.execute("SELECT token_hash,expires_at FROM sessions WHERE user_id=%s", (alice["id"],)).fetchone()
password_hash = conn.execute("SELECT password_hash FROM users WHERE id=%s", (alice["id"],)).fetchone()[0]
self.assertEqual(row[0], hashlib.sha256(session["token"].encode()).digest())
self.assertNotEqual(password_hash, password)
self.assertTrue(password_hash.startswith("$argon2id$"))
self.call("DELETE", "/api/v1/auth/sessions/current", authorization=bearer, expected=204)
for method, path in (("GET", "/api/v1/users/me"), ("DELETE", "/api/v1/auth/sessions/current")):
_, headers = self.call(method, path, authorization=bearer, expected=401)
self.assertEqual(headers.get("WWW-Authenticate"), 'Bearer realm="messenger"')
def test_challenges_and_uniform_credentials(self):
user, password = self.user()
failures = []
for username, candidate in ((user["username"], "wrong-password-123"), ("missing_user_123", password)):
payload, headers = self.login(username, candidate, expected=401)
failures.append((payload["error"]["code"], payload["error"]["message"]))
self.assertEqual(headers.get("WWW-Authenticate"), 'Basic realm="messenger", charset="UTF-8"')
self.assertEqual(failures[0], failures[1])
encoded = base64.b64encode(f"{user['username']}:{password}".encode()).decode()
for authorization in (None, "Basic " + encoded, "Bearer garbage"):
_, headers = self.call("GET", "/api/v1/users/me", authorization=authorization, user_id=user["id"], expected=401)
self.assertEqual(headers.get("WWW-Authenticate"), 'Bearer realm="messenger"')
_, headers = self.call("POST", "/api/v1/auth/sessions", authorization="Bearer garbage", expected=401)
self.assertEqual(headers.get("WWW-Authenticate"), 'Basic realm="messenger", charset="UTF-8"')
self.call("POST", "/api/v1/auth/sessions", authorization="Basic " + encoded, body={"unexpected": True}, expected=400)
def test_z_short_ttl_survives_server_restart_without_extension(self):
self.stop_server()
self.start_server(ttl="2")
try:
user, password = self.user()
session, _ = self.login(user["username"], password)
bearer = "Bearer " + session["token"]
self.call("GET", "/api/v1/users/me", authorization=bearer)
with psycopg.connect(URL) as conn:
before = conn.execute("SELECT expires_at FROM sessions WHERE user_id=%s", (user["id"],)).fetchone()[0]
self.stop_server()
self.start_server(ttl="3600")
with psycopg.connect(URL) as conn:
after = conn.execute("SELECT expires_at FROM sessions WHERE user_id=%s", (user["id"],)).fetchone()[0]
self.assertEqual(before, after)
time.sleep(2.1)
_, headers = self.call("GET", "/api/v1/users/me", authorization=bearer, expected=401)
self.assertEqual(headers.get("WWW-Authenticate"), 'Bearer realm="messenger"')
finally:
self.stop_server()
self.start_server()
if __name__ == "__main__":
unittest.main()
+85
View File
@@ -0,0 +1,85 @@
"""Integration checks against a disposable PostgreSQL database."""
import os
import subprocess
import sys
import unittest
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4
import psycopg
from src.store import Store
URL = os.environ.get("DATABASE_URL")
@unittest.skipUnless(URL, "set DATABASE_URL to a disposable PostgreSQL database")
class DatabaseTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
for _ in range(2):
subprocess.run([sys.executable, "scripts/migrate.py"], check=True)
cls.store = Store()
def user(self):
name = "u_" + uuid4().hex[:16]
return self.store.register(name, "Студент", "Test-password-123")
def test_migration_and_unique_username_race(self):
with psycopg.connect(URL) as conn:
versions = conn.execute("SELECT version FROM schema_migrations").fetchall()
self.assertEqual(versions, [(1,), (2,), (3,)])
name = "u_" + uuid4().hex[:16]
def register(_):
try:
return self.store.register(name, "Студент", "Test-password-123")
except Exception as exc:
return exc
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(register, range(2)))
self.assertEqual(sum(isinstance(result, dict) for result in results), 1)
self.assertEqual([result.status_code for result in results if not isinstance(result, dict)], [409])
with psycopg.connect(URL) as conn:
self.assertEqual(conn.execute("SELECT count(*) FROM users WHERE username=%s", (name,)).fetchone()[0], 1)
password_hash = conn.execute("SELECT password_hash FROM users WHERE username=%s", (name,)).fetchone()[0]
self.assertTrue(password_hash.startswith("$argon2id$"))
self.assertNotIn("password", str(next(result for result in results if isinstance(result, dict))))
subprocess.run([sys.executable, "scripts/migrate.py"], check=True)
with psycopg.connect(URL) as conn:
self.assertEqual(conn.execute("SELECT count(*) FROM users WHERE username=%s", (name,)).fetchone()[0], 1)
def test_chat_rollback_and_keyset_history(self):
alice, bob, eve = self.user(), self.user(), self.user()
with psycopg.connect(URL) as conn:
before = conn.execute("SELECT count(*) FROM chats").fetchone()[0]
with self.assertRaises(Exception) as failure:
self.store.create_chat(alice["id"], "invalid", [alice["id"], str(uuid4())])
self.assertEqual(failure.exception.status_code, 400)
with psycopg.connect(URL) as conn:
self.assertEqual(conn.execute("SELECT count(*) FROM chats").fetchone()[0], before)
chat = self.store.create_chat(alice["id"], "Valid", [alice["id"], bob["id"]])
chat2 = self.store.create_chat(alice["id"], "Second", [alice["id"]])
chat_page = self.store.list_chats(alice["id"], 1, None)
self.assertEqual(chat_page["items"], [chat])
self.assertEqual(self.store.list_chats(alice["id"], 1, chat_page["next_cursor"]), {"items": [chat2], "next_cursor": None})
first = self.store.create_message(alice["id"], chat["id"], "первое", uuid4().hex)
second = self.store.create_message(bob["id"], chat["id"], "второе", uuid4().hex)
page = self.store.list_messages(alice["id"], chat["id"], 1, None)
self.assertEqual(page["items"], [first])
self.assertEqual(self.store.list_messages(bob["id"], chat["id"], 1, page["next_cursor"]), {"items": [second], "next_cursor": None})
self.assertEqual(Store().chat(bob["id"], chat["id"]), chat)
with self.assertRaises(Exception) as wrong_cursor:
self.store.list_messages(alice["id"], chat2["id"], 1, page["next_cursor"])
self.assertEqual(wrong_cursor.exception.status_code, 400)
with self.assertRaises(Exception) as hidden:
self.store.chat(eve["id"], chat["id"])
self.assertEqual(hidden.exception.status_code, 404)
if __name__ == "__main__":
unittest.main()
+53
View File
@@ -0,0 +1,53 @@
"""Concurrent PostgreSQL-backed message retries create one row."""
import os
import subprocess
import sys
import unittest
from concurrent.futures import ThreadPoolExecutor
from uuid import uuid4
import psycopg
from src.store import Store
URL = os.environ.get("DATABASE_URL")
@unittest.skipUnless(URL, "set DATABASE_URL to a disposable PostgreSQL database")
class IdempotencyTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
subprocess.run([sys.executable, "scripts/migrate.py"], check=True)
cls.store = Store()
def test_parallel_replay_conflict_and_scope(self):
alice = self.store.register("u_" + uuid4().hex[:16], "Алиса", "Test-password-123")
bob = self.store.register("u_" + uuid4().hex[:16], "Боб", "Test-password-123")
chat = self.store.create_chat(alice["id"], "Test", [alice["id"], bob["id"]])
other_chat = self.store.create_chat(alice["id"], "Other", [alice["id"]])
key = uuid4().hex
def send(_):
return Store().create_message(alice["id"], chat["id"], "same body", key, [] if _ else None)
with ThreadPoolExecutor(max_workers=2) as pool:
first, replay = list(pool.map(send, range(2)))
self.assertEqual(first, replay)
with psycopg.connect(URL) as conn:
count = conn.execute(
"SELECT count(*) FROM messages WHERE chat_id=%s AND sender_id=%s AND text=%s",
(chat["id"], alice["id"], "same body"),
).fetchone()[0]
self.assertEqual(count, 1)
with self.assertRaises(Exception) as conflict:
self.store.create_message(alice["id"], chat["id"], "different body", key)
self.assertEqual(conflict.exception.status_code, 409)
self.assertNotEqual(self.store.create_message(bob["id"], chat["id"], "same body", key)["id"], first["id"])
self.assertNotEqual(self.store.create_message(alice["id"], other_chat["id"], "same body", key)["id"], first["id"])
if __name__ == "__main__":
unittest.main()
+54
View File
@@ -0,0 +1,54 @@
"""Every API response identifies the live replica process."""
import json
import socket
import subprocess
import sys
import time
import unittest
import urllib.error
import urllib.request
class InstanceHeaderTests(unittest.TestCase):
def test_process_alias_on_success_and_error(self):
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
server = subprocess.Popen(
[sys.executable, "-m", "uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", str(port)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
try:
for _ in range(100):
try:
with urllib.request.urlopen(f"http://127.0.0.1:{port}/health/live", timeout=1) as response:
live_id = response.headers.get("X-Instance-Id")
self.assertEqual(json.load(response), {"status": "ok"})
break
except urllib.error.URLError:
if server.poll() is not None:
self.fail("API exited before readiness")
time.sleep(0.05)
else:
self.fail("API did not start")
self.assertTrue(live_id)
for path in ("/health/live", "/no-such-route"):
try:
response = urllib.request.urlopen(f"http://127.0.0.1:{port}{path}", timeout=1)
except urllib.error.HTTPError as error:
response = error
with response:
self.assertEqual(response.headers.get("X-Instance-Id"), live_id)
self.assertTrue(response.headers.get("X-Request-Id"))
finally:
server.terminate()
try:
server.wait(timeout=5)
except subprocess.TimeoutExpired:
server.kill()
server.wait(timeout=5)
if __name__ == "__main__":
unittest.main()
+27
View File
@@ -0,0 +1,27 @@
"""Text-only messages retain lab3 behavior under the lab4 wire schema."""
import unittest
from datetime import datetime, timezone
from uuid import uuid4
from src.models import CreateMessage
from src.store import message_view
class Lab3CompatibilityTests(unittest.TestCase):
def test_missing_and_explicit_empty_attachments_are_equivalent(self):
missing = CreateMessage.model_validate({"text": "hello"})
explicit = CreateMessage.model_validate({"text": "hello", "attachment_ids": []})
self.assertEqual(missing, explicit)
self.assertEqual(missing.attachment_ids, [])
def test_text_message_response_has_empty_attachment_ids(self):
row = {
"id": uuid4(), "chat_id": uuid4(), "sender_id": uuid4(),
"text": "hello", "created_at": datetime.now(timezone.utc),
}
self.assertEqual(message_view(row)["attachment_ids"], [])
if __name__ == "__main__":
unittest.main()