forked from mtusi2026/mtusi2026lab2
выполнение лр2 на 4
This commit is contained in:
Executable
+70
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sessions: wrong password, Basic/Bearer separation, X-User-Id ignored, logout, expiry.
|
||||
|
||||
Expiry runs against the api-short-ttl service (SESSION_TTL_SECONDS=2):
|
||||
docker compose --profile ttl-test up -d --wait api-short-ttl
|
||||
"""
|
||||
import base64
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from stack import BASE_URL, SHORT_TTL_URL, Client, check, main_wrapper, ok
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
return {"Authorization": "Basic " + base64.b64encode((username + ":" + password).encode("utf-8")).decode()}
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(BASE_URL)
|
||||
alice = c.user("auth")
|
||||
reg = alice["registration"]
|
||||
|
||||
# Wrong password and unknown user: the same 401 with a Basic challenge.
|
||||
r1 = c.call("POST", "/api/v1/auth/sessions", 401, headers=basic(reg["username"], "wrong-password-123"))
|
||||
r2 = c.call("POST", "/api/v1/auth/sessions", 401, headers=basic("nobody_" + uuid.uuid4().hex[:8], "wrong-password-123"))
|
||||
check(r1["json"]["error"]["message"] == r2["json"]["error"]["message"], "unknown user must look like a wrong password")
|
||||
ok("wrong password / unknown user -> identical 401 Basic")
|
||||
|
||||
c.call("POST", "/api/v1/auth/sessions", 401)
|
||||
c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic !!!not-base64"})
|
||||
c.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Bearer " + alice["token"]})
|
||||
ok("missing / malformed / non-Basic login -> 401")
|
||||
|
||||
# A password with ':' and non-ASCII characters survives Basic encoding.
|
||||
tricky = "пароль:с:двоеточием-" + uuid.uuid4().hex[:6]
|
||||
user = c.call("POST", "/api/v1/users", 201, body={"username": "u_colon_" + uuid.uuid4().hex[:8], "display_name": "Двоеточие", "password": tricky}, schema="User")["json"]
|
||||
c.call("POST", "/api/v1/auth/sessions", 201, headers=basic(user["username"], tricky), schema="Session")
|
||||
ok("UTF-8 password containing ':' -> 201")
|
||||
|
||||
c.call("POST", "/api/v1/users", 400, body={"username": "u_short_" + uuid.uuid4().hex[:8], "display_name": "x", "password": "short-11ch"})
|
||||
c.call("POST", "/api/v1/users", 400, body={"username": "u_nopass_" + uuid.uuid4().hex[:8], "display_name": "x"})
|
||||
ok("password shorter than 12 / missing -> 400")
|
||||
|
||||
me = c.call("GET", "/api/v1/users/me", 401, headers=basic(reg["username"], reg["password"]))
|
||||
check(me["headers"].get("WWW-Authenticate", "").startswith("Bearer"), "Bearer challenge expected")
|
||||
c.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": alice["id"]})
|
||||
c.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer " + uuid.uuid4().hex * 2})
|
||||
ok("Basic / X-User-Id / unknown token on business endpoint -> 401")
|
||||
|
||||
session = c.call("POST", "/api/v1/auth/sessions", 201, headers=basic(reg["username"], reg["password"]), schema="Session")["json"]
|
||||
check(session["token"] != alice["token"], "every login must issue a new token")
|
||||
second = dict(alice, token=session["token"])
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=alice)
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=alice)
|
||||
c.call("GET", "/api/v1/users/me", 200, actor=second, schema="User")
|
||||
ok("logout revokes only the current token; repeat logout -> 401")
|
||||
|
||||
# Expiry: separate instance of the same image with SESSION_TTL_SECONDS=2.
|
||||
s = Client(SHORT_TTL_URL)
|
||||
bob = s.user("ttl")
|
||||
s.call("GET", "/api/v1/users/me", 200, actor=bob, schema="User")
|
||||
time.sleep(3)
|
||||
s.call("GET", "/api/v1/users/me", 401, actor=bob)
|
||||
s.call("DELETE", "/api/v1/auth/sessions/current", 401, actor=bob)
|
||||
ok("session with TTL=2s is rejected after 3s (cache entry included)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_wrapper(main)
|
||||
Executable
+61
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level-4 race-protection evidence: 10 clients send 100 messages concurrently;
|
||||
expect exactly 100 unique messages, with no loss/duplication under pagination.
|
||||
"""
|
||||
import sys
|
||||
import urllib.parse
|
||||
import concurrent.futures
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
base_url = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
|
||||
n_messages = 100
|
||||
n_clients = 10
|
||||
|
||||
c = Client(base_url)
|
||||
users = [c.user("race%d" % i) for i in range(n_clients)]
|
||||
chat = c.call(
|
||||
"POST", "/api/v1/chats", 201, actor=users[0],
|
||||
body={"title": "race", "member_ids": [u["id"] for u in users]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
|
||||
def send(i):
|
||||
actor = users[i % n_clients]
|
||||
return c.message(actor, chat, "race-%d" % i)["json"]["id"]
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=n_clients) as pool:
|
||||
ids = list(pool.map(send, range(n_messages)))
|
||||
|
||||
check(len(ids) == n_messages, "expected %d responses" % n_messages)
|
||||
check(len(set(ids)) == n_messages, "expected %d unique message ids, got %d" % (n_messages, len(set(ids))))
|
||||
|
||||
# Walk the full history back through the API to confirm the store itself
|
||||
# (not just the HTTP responses) holds exactly n_messages distinct rows.
|
||||
seen = []
|
||||
cursor = None
|
||||
while True:
|
||||
qs = "?limit=25" + ("&cursor=" + urllib.parse.quote(cursor, safe="") if cursor else "")
|
||||
page = c.call("GET", path + qs, actor=users[0], schema="MessagePage")["json"]
|
||||
seen.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
break
|
||||
check(len(seen) == n_messages, "expected to read back %d messages, got %d" % (n_messages, len(seen)))
|
||||
check(len({m["id"] for m in seen}) == n_messages, "readback contains duplicates")
|
||||
|
||||
print("PASS: %d unique messages written and read back from %d concurrent clients" % (n_messages, n_clients))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print("FAIL:", exc)
|
||||
raise SystemExit(1)
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""PostgreSQL integrity: registration race, rollback of chat creation, repeatable migrations,
|
||||
password storage. Needs the compose stack (reads tables via `docker compose exec postgres`)."""
|
||||
import concurrent.futures
|
||||
import uuid
|
||||
|
||||
from stack import BASE_URL, Client, check, compose, main_wrapper, ok, psql
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(BASE_URL)
|
||||
|
||||
# 1. Registration race: 20 parallel requests for one username.
|
||||
username = "u_race_" + uuid.uuid4().hex[:10]
|
||||
body = {"username": username, "display_name": "Гонка", "password": "Race-password-123"}
|
||||
|
||||
def register(_):
|
||||
return c.call("POST", "/api/v1/users", [201, 409], body=body)["status"]
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as pool:
|
||||
statuses = list(pool.map(register, range(20)))
|
||||
check(statuses.count(201) == 1, "exactly one registration must win, got %s" % statuses)
|
||||
check(statuses.count(409) == 19, "all others must get 409, got %s" % statuses)
|
||||
check(psql("SELECT count(*) FROM users WHERE username = '%s'" % username) == "1", "exactly one row expected")
|
||||
ok("20 concurrent registrations of one username -> 1x201, 19x409, 1 row")
|
||||
|
||||
# 2. Rollback: the chat row is inserted, then the member insert hits the FK.
|
||||
alice = c.user("rb")
|
||||
title = "rollback-" + uuid.uuid4().hex
|
||||
c.call("POST", "/api/v1/chats", 400, actor=alice, body={"title": title, "member_ids": [alice["id"], str(uuid.uuid4())]})
|
||||
check(psql("SELECT count(*) FROM chats WHERE title = '%s'" % title) == "0", "failed chat creation left a chat row")
|
||||
check(psql("SELECT count(*) FROM chats c WHERE NOT EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = c.id)") == "0",
|
||||
"chat without members exists")
|
||||
ok("chat with unknown member -> 400 and transaction rolled back (no orphan chat)")
|
||||
|
||||
# 3. Passwords are stored as Argon2id hashes, never plaintext.
|
||||
stored = psql("SELECT password_hash FROM users WHERE username = '%s'" % username)
|
||||
check(stored.startswith("$argon2id$") and "Race-password-123" not in stored, "password must be an Argon2id hash")
|
||||
check(psql("SELECT count(*) FROM information_schema.columns WHERE table_name = 'sessions' AND column_name = 'token'") == "0",
|
||||
"raw tokens must not be stored")
|
||||
ok("password stored as $argon2id$..., sessions keep only sha256(token)")
|
||||
|
||||
# 4. Migrations re-run without duplicates or data changes.
|
||||
before = psql("SELECT (SELECT count(*) FROM schema_migrations) || ':' || (SELECT count(*) FROM users)")
|
||||
compose("run", "--rm", "--no-deps", "migrate")
|
||||
compose("run", "--rm", "--no-deps", "migrate")
|
||||
after = psql("SELECT (SELECT count(*) FROM schema_migrations) || ':' || (SELECT count(*) FROM users)")
|
||||
check(before == after, "migrations changed data on re-run: %s -> %s" % (before, after))
|
||||
ok("migrations run twice more: schema_migrations and data unchanged (%s)" % after)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_wrapper(main)
|
||||
Executable
+86
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Valkey's role and failures of each dependency. STOPS AND STARTS containers of this stack.
|
||||
|
||||
- Valkey really caches sessions and holds logout tombstones.
|
||||
- Valkey down: API keeps working (cache bypassed), readiness stays 200.
|
||||
- PostgreSQL down: bounded 503 quickly, readiness 503, liveness 200; an unverifiable
|
||||
token is never accepted; no token is still 401. Recovery after start.
|
||||
"""
|
||||
import time
|
||||
|
||||
from stack import BASE_URL, Client, Failure, check, compose, main_wrapper, ok, valkey
|
||||
|
||||
|
||||
def wait_ready(c, seconds=60):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call("GET", "/health/ready", 200)
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(0.5)
|
||||
raise Failure("API did not become ready")
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(BASE_URL, timeout=10)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
history = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
|
||||
# Role of Valkey: a session lookup fills the cache, logout leaves a tombstone.
|
||||
before = int(valkey("DBSIZE"))
|
||||
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
keys = valkey("--scan", "--pattern", "session:*").split()
|
||||
check(len(keys) >= 1 and int(valkey("DBSIZE")) >= before, "session lookups must be cached in Valkey")
|
||||
ttl = int(valkey("TTL", keys[0]))
|
||||
check(0 < ttl <= 300, "cache entries must expire (TTL %d)" % ttl)
|
||||
temp = c.user("tomb")
|
||||
c.call("GET", "/api/v1/users/me", actor=temp, schema="User")
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=temp)
|
||||
tombstones = [k for k in valkey("--scan", "--pattern", "session:*").split() if valkey("GET", k) == "revoked"]
|
||||
check(tombstones, "logout must leave a 'revoked' tombstone in the cache")
|
||||
ok("Valkey caches sessions with TTL<=300s and keeps logout tombstones")
|
||||
|
||||
# Valkey down -> the API bypasses the cache, PostgreSQL stays the source of truth.
|
||||
try:
|
||||
compose("stop", "valkey")
|
||||
c.call("GET", "/health/ready", 200)
|
||||
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
c.message(bob, chat, "без кэша")
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=temp) # revoked in PostgreSQL too
|
||||
start = time.monotonic()
|
||||
for _ in range(10):
|
||||
c.call("GET", history + "?limit=1", actor=alice, schema="MessagePage")
|
||||
per_request = (time.monotonic() - start) / 10
|
||||
check(per_request < 0.5, "cache bypass must be fast (%.3fs per request)" % per_request)
|
||||
ok("Valkey stopped: ready=200, reads/writes OK, revoked token 401, %.0f ms/request" % (per_request * 1000))
|
||||
finally:
|
||||
compose("start", "valkey")
|
||||
|
||||
# PostgreSQL down -> bounded 503, never anonymous access.
|
||||
fresh = c.user("dbdown") # token never looked up yet: not in the cache
|
||||
try:
|
||||
compose("stop", "postgres")
|
||||
c.call("GET", "/health/live", 200)
|
||||
start = time.monotonic()
|
||||
r = c.call("GET", "/health/ready", 503)
|
||||
check(r["json"]["error"]["code"] == "unavailable", "readiness must report unavailable")
|
||||
c.call("GET", "/api/v1/chats", 503, actor=alice)
|
||||
c.call("POST", history, 503, actor=alice, body={"text": "в никуда"})
|
||||
c.call("GET", "/api/v1/users/me", 503, actor=fresh) # cannot verify -> not trusted
|
||||
c.call("GET", "/api/v1/users/me", 401) # no credentials at all
|
||||
elapsed = time.monotonic() - start
|
||||
check(elapsed < 20, "errors must be bounded in time (%.1fs)" % elapsed)
|
||||
ok("PostgreSQL stopped: live=200, ready/business=503 in %.1fs total, unverified token not trusted" % elapsed)
|
||||
finally:
|
||||
compose("start", "postgres")
|
||||
|
||||
wait_ready(c)
|
||||
c.call("GET", "/api/v1/users/me", actor=fresh, schema="User")
|
||||
page = c.call("GET", history + "?limit=100", actor=alice, schema="MessagePage")["json"]
|
||||
check(any(m["text"] == "без кэша" for m in page["items"]), "message written without cache must persist")
|
||||
ok("PostgreSQL started again: API recovers without restart, data intact")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main_wrapper(main)
|
||||
Executable
+81
@@ -0,0 +1,81 @@
|
||||
#!/bin/sh
|
||||
# Seed synthetic history (20 000 messages in one chat + 50 000 in 50 other chats) and
|
||||
# record EXPLAIN (ANALYZE, BUFFERS) of the exact keyset queries used by the API,
|
||||
# with and without messages_chat_history_idx. Output: evidence/explain_history.txt
|
||||
# Seeding is idempotent (fixed IDs, ON CONFLICT DO NOTHING); data is synthetic.
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
OUT="${OUT:-evidence/explain_history.txt}"
|
||||
PSQL="docker compose exec -T postgres psql -U messenger -d messenger -X -v ON_ERROR_STOP=1"
|
||||
|
||||
$PSQL -q <<'SQL'
|
||||
INSERT INTO users (id, username, display_name, password_hash) VALUES
|
||||
('00000000-0000-4000-8000-000000000001', 'seed_explain_a', 'Seed A', 'not-a-login'),
|
||||
('00000000-0000-4000-8000-000000000002', 'seed_explain_b', 'Seed B', 'not-a-login')
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- chat ...0100 is the measured one; ...0101-0150 are background noise.
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
SELECT ('00000000-0000-4000-8000-' || lpad((100 + g)::text, 12, '0'))::uuid, 'explain ' || g, now()
|
||||
FROM generate_series(0, 50) g
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
SELECT c.id, u.id, u.pos
|
||||
FROM chats c
|
||||
CROSS JOIN (VALUES ('00000000-0000-4000-8000-000000000001'::uuid, 0),
|
||||
('00000000-0000-4000-8000-000000000002'::uuid, 1)) AS u(id, pos)
|
||||
WHERE c.title LIKE 'explain %'
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT md5('explain-' || c.n || '-' || g)::uuid,
|
||||
('00000000-0000-4000-8000-' || lpad((100 + c.n)::text, 12, '0'))::uuid,
|
||||
CASE WHEN g % 2 = 0 THEN '00000000-0000-4000-8000-000000000001'::uuid
|
||||
ELSE '00000000-0000-4000-8000-000000000002'::uuid END,
|
||||
'synthetic message ' || g,
|
||||
timestamptz '2026-01-01' + (g * interval '1 second') + (c.n * interval '1 millisecond')
|
||||
FROM (SELECT n, CASE WHEN n = 0 THEN 20000 ELSE 1000 END AS cnt FROM generate_series(0, 50) n) c
|
||||
CROSS JOIN LATERAL generate_series(1, c.cnt) g
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
ANALYZE users; ANALYZE chats; ANALYZE chat_members; ANALYZE messages;
|
||||
SQL
|
||||
|
||||
{
|
||||
echo "# EXPLAIN evidence for message history pagination"
|
||||
echo "# date: $(date -u +%Y-%m-%dT%H:%M:%SZ) commit: $(git rev-parse --short HEAD 2>/dev/null || echo n/a)"
|
||||
echo "# postgres: $($PSQL -tA -c 'SHOW server_version')"
|
||||
$PSQL -tA -c "SELECT '# messages total: ' || count(*) || ', in measured chat: ' || count(*) FILTER (WHERE chat_id = '00000000-0000-4000-8000-000000000100') FROM messages"
|
||||
echo
|
||||
$PSQL <<'SQL'
|
||||
-- The same statements as app/storage.py (Store.list_messages), as prepared statements.
|
||||
PREPARE first_page(uuid, int) AS
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = $1 ORDER BY created_at, id LIMIT $2;
|
||||
PREPARE next_page(uuid, timestamptz, uuid, int) AS
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4;
|
||||
|
||||
\echo '=== 1. WITH index messages_chat_history_idx: first page (limit 50 + 1) ==='
|
||||
EXPLAIN (ANALYZE, BUFFERS) EXECUTE first_page('00000000-0000-4000-8000-000000000100', 51);
|
||||
|
||||
\echo '=== 2. WITH index: deep page, cursor after message #15000 of 20000 ==='
|
||||
EXPLAIN (ANALYZE, BUFFERS) EXECUTE next_page('00000000-0000-4000-8000-000000000100',
|
||||
timestamptz '2026-01-01' + interval '15000 seconds', md5('explain-0-15000')::uuid, 51);
|
||||
|
||||
-- Same queries without the index, inside a transaction that is rolled back.
|
||||
BEGIN;
|
||||
DROP INDEX messages_chat_history_idx;
|
||||
\echo '=== 3. WITHOUT index: first page ==='
|
||||
EXPLAIN (ANALYZE, BUFFERS) EXECUTE first_page('00000000-0000-4000-8000-000000000100', 51);
|
||||
\echo '=== 4. WITHOUT index: deep page ==='
|
||||
EXPLAIN (ANALYZE, BUFFERS) EXECUTE next_page('00000000-0000-4000-8000-000000000100',
|
||||
timestamptz '2026-01-01' + interval '15000 seconds', md5('explain-0-15000')::uuid, 51);
|
||||
ROLLBACK;
|
||||
SQL
|
||||
} > "$OUT"
|
||||
|
||||
echo "written $OUT"
|
||||
grep -E '^===|Index|Seq Scan|Sort|Buffers|Execution Time' "$OUT"
|
||||
Executable
+120
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Student-written negative/edge-case tests, additional to the public tests/smoke.py.
|
||||
|
||||
Covers level-4 requirements from README.md:
|
||||
- malformed JSON
|
||||
- foreign chat access
|
||||
- empty message text
|
||||
- duplicate username
|
||||
- multi-page pagination traversal
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
|
||||
PASSED = 0
|
||||
|
||||
|
||||
def ok(label):
|
||||
global PASSED
|
||||
PASSED += 1
|
||||
print("ok -", label)
|
||||
|
||||
|
||||
def raw_call(base, method, path, data=None, headers=None):
|
||||
h = {"Accept": "application/json"}
|
||||
h.update(headers or {})
|
||||
req = urllib.request.Request(base + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=10)
|
||||
except urllib.error.HTTPError as exc:
|
||||
resp = exc
|
||||
with resp:
|
||||
return resp.code, resp.read()
|
||||
|
||||
|
||||
def main():
|
||||
base_url = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
|
||||
c = Client(base_url)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"]
|
||||
|
||||
# 1. Malformed JSON body -> 400 invalid_request, not a 500.
|
||||
status, body = raw_call(
|
||||
base_url, "POST", "/api/v1/users",
|
||||
data=b'{"username": "broken", "display_name": ',
|
||||
headers={"Content-Type": "application/json", "X-User-Id": alice["id"]},
|
||||
)
|
||||
check(status == 400, "malformed JSON must yield 400, got %d" % status)
|
||||
parsed = json.loads(body)
|
||||
check(parsed["error"]["code"] == "invalid_request", "malformed JSON must report invalid_request")
|
||||
ok("malformed JSON -> 400 invalid_request")
|
||||
|
||||
# 2. Foreign chat: eve is not a member -> 404, not 403 (no existence leak).
|
||||
c.call("GET", path, 404, actor=eve)
|
||||
c.call("GET", path + "/messages", 404, actor=eve)
|
||||
ok("foreign chat access -> 404 (no leak)")
|
||||
|
||||
# 3. Empty / whitespace-only message text -> 400.
|
||||
c.call("POST", path + "/messages", 400, actor=alice, body={"text": ""})
|
||||
c.call("POST", path + "/messages", 400, actor=alice, body={"text": " "})
|
||||
ok("empty/whitespace message text -> 400")
|
||||
|
||||
# 4. Duplicate username -> 409 conflict, original user untouched.
|
||||
c.call("POST", "/api/v1/users", 409, body=alice["registration"])
|
||||
me = c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["json"]
|
||||
check(me == alice["user"], "existing user must be unaffected by a rejected duplicate registration")
|
||||
ok("duplicate username -> 409, original user intact")
|
||||
|
||||
# 5. Multi-page pagination traversal: write N messages, walk every page with a small
|
||||
# limit and confirm the full, ordered, duplicate-free set is recovered.
|
||||
sent = [c.message(alice, chat, "page-msg-%d" % i)["json"] for i in range(7)]
|
||||
collected = []
|
||||
cursor = None
|
||||
pages = 0
|
||||
while True:
|
||||
qs = "?limit=2" + ("&cursor=" + urllib.parse.quote(cursor, safe="") if cursor else "")
|
||||
page = c.call("GET", path + "/messages" + qs, actor=bob, schema="MessagePage")["json"]
|
||||
pages += 1
|
||||
check(len(page["items"]) <= 2, "page must respect limit")
|
||||
collected.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
break
|
||||
check(pages < 50, "pagination did not terminate")
|
||||
ids_seen = [m["id"] for m in collected]
|
||||
check(len(ids_seen) == len(set(ids_seen)), "pagination must not repeat messages")
|
||||
check({m["id"] for m in sent}.issubset(set(ids_seen)), "pagination must not drop messages")
|
||||
tail = [m for m in collected if m["id"] in {s["id"] for s in sent}]
|
||||
check(tail == sorted(tail, key=lambda m: (m["created_at"], m["id"])), "pagination must stay ordered")
|
||||
ok("multi-page pagination traversal: %d pages, %d messages, no dup/loss" % (pages, len(collected)))
|
||||
|
||||
# 6. A cursor is bound to the chat it was issued for: reusing it on a
|
||||
# different chat the same actor can also read must be rejected.
|
||||
first_page = c.call("GET", path + "/messages?limit=1", actor=alice, schema="MessagePage")["json"]
|
||||
check(first_page["next_cursor"], "need a non-null cursor to test cross-chat reuse")
|
||||
chat2 = c.call(
|
||||
"POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "second chat", "member_ids": [alice["id"], bob["id"]]}, schema="Chat",
|
||||
)["json"]
|
||||
c.message(alice, chat2, "unrelated message")
|
||||
foreign_cursor = urllib.parse.quote(first_page["next_cursor"], safe="")
|
||||
c.call("GET", "/api/v1/chats/" + chat2["id"] + "/messages?limit=1&cursor=" + foreign_cursor, 400, actor=alice)
|
||||
ok("cursor from another chat -> 400 (cursor is bound to its resource)")
|
||||
|
||||
print("PASS: %d/%d student checks" % (PASSED, 6))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print("FAIL:", exc)
|
||||
raise SystemExit(1)
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/bin/sh
|
||||
# All student tests in one command. Needs the running compose stack; starts the
|
||||
# short-TTL instance itself. dependency_test/sigterm_test STOP AND START containers.
|
||||
# Usage: BASE_URL=http://localhost:8080 student-tests/run_all.sh
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
PY="${PYTHON:-python3}"
|
||||
export BASE_URL="${BASE_URL:-http://localhost:8080}"
|
||||
export SHORT_TTL_URL="${SHORT_TTL_URL:-http://localhost:8081}"
|
||||
|
||||
docker compose --profile ttl-test up -d --no-build --wait api-short-ttl >/dev/null 2>&1
|
||||
|
||||
for t in own_tests.py concurrency_test.py auth_test.py db_integrity_test.py dependency_test.py; do
|
||||
echo "== $t"
|
||||
"$PY" "student-tests/$t" "$BASE_URL"
|
||||
echo
|
||||
done
|
||||
echo "== sigterm_test.sh"
|
||||
sh student-tests/sigterm_test.sh
|
||||
|
||||
docker compose --profile ttl-test stop api-short-ttl >/dev/null 2>&1
|
||||
echo
|
||||
echo "ALL STUDENT TESTS PASSED"
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
# Graceful shutdown of the compose api service: SIGTERM -> exit 0 within 10s
|
||||
# (not SIGKILL 137), then the service is started again. Volumes are untouched.
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
CID=$(docker compose ps -q api)
|
||||
[ -n "$CID" ] || { echo "FAIL: api is not running"; exit 1; }
|
||||
|
||||
START=$(date +%s)
|
||||
docker compose stop api >/dev/null 2>&1
|
||||
ELAPSED=$(( $(date +%s) - START ))
|
||||
EXIT_CODE=$(docker inspect -f '{{.State.ExitCode}}' "$CID")
|
||||
echo "api stopped in ${ELAPSED}s, exit code ${EXIT_CODE} (0 = graceful, 137 = SIGKILL)"
|
||||
docker compose logs --since 30s api 2>&1 | grep -q "Application shutdown complete" || { echo "FAIL: no graceful shutdown line"; exit 1; }
|
||||
[ "$ELAPSED" -le 10 ] && [ "$EXIT_CODE" -eq 0 ] || { docker compose up -d --wait api; echo "FAIL: not graceful"; exit 1; }
|
||||
|
||||
docker compose up -d --no-build --wait api >/dev/null 2>&1
|
||||
echo "PASS: graceful SIGTERM shutdown, api restarted"
|
||||
Executable
+47
@@ -0,0 +1,47 @@
|
||||
"""Shared helpers for student tests: public client + direct access to the compose stack."""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check # noqa: E402,F401
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
|
||||
SHORT_TTL_URL = os.environ.get("SHORT_TTL_URL", "http://localhost:8081")
|
||||
|
||||
PASSED = []
|
||||
|
||||
|
||||
def ok(label):
|
||||
PASSED.append(label)
|
||||
print("ok -", label)
|
||||
|
||||
|
||||
def compose(*args, check_rc=True):
|
||||
"""docker compose in the repository root; output is captured, never printed raw."""
|
||||
proc = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True)
|
||||
if check_rc and proc.returncode != 0:
|
||||
raise Failure("docker compose %s failed: %s" % (args[0], proc.stderr.strip()[-300:]))
|
||||
return proc.stdout
|
||||
|
||||
|
||||
def psql(sql):
|
||||
"""Run SQL inside the postgres container (local socket, no password on the wire)."""
|
||||
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tAX", "-c", sql).strip()
|
||||
|
||||
|
||||
def valkey(*args):
|
||||
"""valkey-cli with the password read inside the container, never on this host's argv."""
|
||||
cmd = 'valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" /run/secrets/valkey_conf)" "$@"'
|
||||
return compose("exec", "-T", "valkey", "sh", "-c", cmd, "valkey-cli", *args).strip()
|
||||
|
||||
|
||||
def main_wrapper(main):
|
||||
try:
|
||||
main()
|
||||
except (AssertionError, Failure) as exc:
|
||||
print("FAIL:", exc)
|
||||
raise SystemExit(1)
|
||||
print("PASS: %d checks" % len(PASSED))
|
||||
Reference in New Issue
Block a user