Fix cached session identity and document PR 63 regression checks

This commit is contained in:
2026-10-24 08:34:58 +03:00
parent 35f252ee4f
commit 6038c0f375
11 changed files with 700 additions and 277 deletions
+34
View File
@@ -8,6 +8,7 @@ import time
import urllib.error
import urllib.request
import uuid
from concurrent.futures import ThreadPoolExecutor
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
@@ -27,6 +28,8 @@ def http_json(method, path, *, expected=200, headers=None, body=None):
payload = resp.read()
if not payload:
return {"status": resp.status, "headers": dict(resp.headers), "body": None}
if resp.status not in (expected if isinstance(expected, (list, tuple, set)) else [expected]):
raise AssertionError(f"Expected {expected}, got {resp.status}")
return {"status": resp.status, "headers": dict(resp.headers), "body": json.loads(payload.decode("utf-8"))}
except urllib.error.HTTPError as exc:
payload = exc.read()
@@ -91,6 +94,25 @@ def main():
assert stale_result["status"] == 200, stale_result
assert stale_result["body"]["username"] == username, stale_result
# An unexpired payload must not be able to substitute another identity.
stale_payload["expires_at"] = "2100-01-01T00:00:00Z"
r.setex(key, 120, json.dumps(stale_payload))
forged = http_json("GET", "/api/v1/users/me", headers={"Authorization": "Bearer " + token})
assert forged["body"]["id"] == session["body"]["user"]["id"], forged
assert forged["body"]["username"] == username, forged
r.setex(key, 120, json.dumps(stale_payload))
def read_identity(_):
return http_json("GET", "/api/v1/users/me", headers={"Authorization": "Bearer " + token})["body"]["id"]
with ThreadPoolExecutor(max_workers=8) as executor:
identities = list(executor.map(read_identity, range(8)))
assert identities == [session["body"]["user"]["id"]] * 8, identities
# Syntactically valid JSON with missing fields must be treated as a miss.
r.setex(key, 120, "{}")
malformed = http_json("GET", "/api/v1/users/me", headers={"Authorization": "Bearer " + token})
assert malformed["body"]["username"] == username, malformed
r.setex(key, 1, json.dumps({
"token": token,
"user_id": str(uuid.uuid4()),
@@ -110,11 +132,23 @@ def main():
after_logout = http_json("GET", "/api/v1/users/me", expected=401, headers={"Authorization": "Bearer " + token})
assert after_logout["status"] == 401, after_logout
# Simulate a writer repopulating the cache after logout's DELETE.
stale_payload.update(session["body"])
stale_payload["user_id"] = session["body"]["user"]["id"]
stale_payload["revoked_at"] = None
r.setex(key, 120, json.dumps(stale_payload))
http_json("GET", "/api/v1/users/me", expected=401, headers={"Authorization": "Bearer " + token})
assert not r.exists(key), "stale key after logout must be removed"
print("cache_key_exists=True")
print(f"ttl_seconds={ttl}")
print(f"avg_latency_ms={avg:.2f}")
print(f"p95_latency_ms={p95:.2f}")
print("stale_cache_rejected=True")
print("forged_identity_rejected=True")
print("concurrent_identity_checks=8/8")
print("malformed_cache_recovers=True")
print("repopulated_revoked_cache_rejected=True")
print("short_ttl_recovers_from_db=True")
print("logout_revokes_cache=True")
+34
View File
@@ -0,0 +1,34 @@
"""Run against an isolated API started with SESSION_TTL_SECONDS=2.
BASE_URL defaults to http://localhost:8080; do not use a normal one-hour server.
"""
import base64
import time
import uuid
from datetime import datetime, timezone
from cache_consistency import http_json
def main():
username = "expiry_" + uuid.uuid4().hex[:16]
password = "expiry-password-123"
http_json("POST", "/api/v1/users", expected=201,
body={"username": username, "display_name": "Expiry", "password": password})
credentials = base64.b64encode(f"{username}:{password}".encode()).decode()
http_json("POST", "/api/v1/auth/sessions", expected=401,
headers={"Authorization": "Basic " + base64.b64encode(f"{username}:wrong-password".encode()).decode()})
result = http_json("POST", "/api/v1/auth/sessions", expected=201,
headers={"Authorization": "Basic " + credentials})
session = result["body"]
remaining = (datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00")) - datetime.now(timezone.utc)).total_seconds()
assert 0 < remaining <= 3, "Use an isolated server with SESSION_TTL_SECONDS=2"
headers = {"Authorization": "Bearer " + session["token"]}
http_json("GET", "/api/v1/users/me", headers=headers)
time.sleep(max(0, remaining) + 0.2)
http_json("GET", "/api/v1/users/me", expected=401, headers=headers)
print("PASS: wrong password rejected; live session accepted; expired session rejected")
if __name__ == "__main__":
main()
+91
View File
@@ -0,0 +1,91 @@
"""Run with .venv/bin/python tests/storage_regression.py against local test DB."""
import sys
import unittest
import uuid
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import app
import psycopg
import redis
class StorageRegression(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.store = app.Store()
cls.store.pool.open(wait=True)
cls.store.init()
@classmethod
def tearDownClass(cls):
cls.store.pool.close()
def setUp(self):
self.user = self.store.insert_user("reg_" + uuid.uuid4().hex[:20], "Regression", "test-password-123")
def tearDown(self):
with self.store.connect() as conn:
conn.execute("DELETE FROM chats WHERE id IN (SELECT chat_id FROM chat_members WHERE user_id = %s)", (self.user["id"],))
conn.execute("DELETE FROM users WHERE id = %s", (self.user["id"],))
def test_atomic_chat_rollback(self):
title = "rollback_" + uuid.uuid4().hex
with self.assertRaises(psycopg.errors.ForeignKeyViolation):
self.store.insert_chat(title, [self.user["id"], str(uuid.uuid4())], self.user["id"])
with self.store.connect() as conn:
self.assertEqual(conn.execute("SELECT count(*) FROM chats WHERE title = %s", (title,)).fetchone()[0], 0)
def test_registration_race(self):
username = "race_" + uuid.uuid4().hex[:20]
def register(_):
try:
return self.store.insert_user(username, "Race", "test-password-123")["id"]
except psycopg.errors.UniqueViolation:
return None
with ThreadPoolExecutor(max_workers=2) as executor:
results = list(executor.map(register, range(2)))
try:
self.assertEqual(sum(result is not None for result in results), 1)
finally:
with self.store.connect() as conn:
conn.execute("DELETE FROM users WHERE username = %s", (username,))
def test_equal_timestamp_pagination(self):
chat = self.store.insert_chat("Paging", [self.user["id"]], self.user["id"])
ids = sorted(str(uuid.uuid4()) for _ in range(7))
with self.store.connect() as conn:
for message_id in ids:
conn.execute("INSERT INTO messages(id, chat_id, sender_id, text, created_at) VALUES (%s,%s,%s,'same time',%s)",
(message_id, chat["id"], self.user["id"], "2026-01-01T00:00:00Z"))
cursor, actual = None, []
while True:
page = self.store.list_messages_for_chat(chat["id"], 2, cursor)
actual.extend(item["id"] for item in page["items"])
cursor = page["next_cursor"]
if cursor is None:
break
self.assertEqual(actual, ids)
def test_expired_db_session_overrides_live_cache(self):
session = self.store.create_session(self.user["id"], self.user["username"])
with self.store.connect() as conn:
conn.execute("UPDATE sessions SET expires_at = %s WHERE token = %s",
(self.store.utc_now() - timedelta(seconds=1), session["token"]))
self.assertIsNone(self.store.get_session_by_token(session["token"]))
def test_cache_unavailable_falls_back_to_db(self):
session = self.store.create_session(self.user["id"], self.user["username"])
try:
with patch.object(self.store, "cache_client", side_effect=redis.ConnectionError("offline")):
actual = self.store.get_session_by_token(session["token"])
self.assertEqual(actual["user_id"], self.user["id"])
finally:
self.store.delete_cached_session(session["token"])
if __name__ == "__main__":
unittest.main(verbosity=2)