This commit is contained in:
@@ -1,9 +1,4 @@
|
||||
#!/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
|
||||
@@ -20,7 +15,6 @@ def main():
|
||||
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")
|
||||
@@ -31,7 +25,6 @@ def main():
|
||||
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")
|
||||
@@ -56,7 +49,6 @@ def main():
|
||||
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")
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
#!/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
|
||||
@@ -9,7 +6,7 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def main():
|
||||
@@ -36,8 +33,6 @@ def main():
|
||||
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:
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/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
|
||||
|
||||
@@ -10,7 +8,6 @@ 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"}
|
||||
|
||||
@@ -24,7 +21,6 @@ def main():
|
||||
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())]})
|
||||
@@ -33,14 +29,12 @@ def main():
|
||||
"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")
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
#!/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
|
||||
@@ -27,7 +20,6 @@ def main():
|
||||
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()
|
||||
@@ -41,13 +33,12 @@ def main():
|
||||
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
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=temp)
|
||||
start = time.monotonic()
|
||||
for _ in range(10):
|
||||
c.call("GET", history + "?limit=1", actor=alice, schema="MessagePage")
|
||||
@@ -57,8 +48,7 @@ def main():
|
||||
finally:
|
||||
compose("start", "valkey")
|
||||
|
||||
# PostgreSQL down -> bounded 503, never anonymous access.
|
||||
fresh = c.user("dbdown") # token never looked up yet: not in the cache
|
||||
fresh = c.user("dbdown")
|
||||
try:
|
||||
compose("stop", "postgres")
|
||||
c.call("GET", "/health/live", 200)
|
||||
@@ -67,8 +57,8 @@ def main():
|
||||
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
|
||||
c.call("GET", "/api/v1/users/me", 503, actor=fresh)
|
||||
c.call("GET", "/api/v1/users/me", 401)
|
||||
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)
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
#!/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")/.."
|
||||
@@ -15,7 +11,6 @@ INSERT INTO users (id, username, display_name, password_hash) VALUES
|
||||
('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
|
||||
@@ -50,7 +45,6 @@ SQL
|
||||
$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;
|
||||
@@ -65,7 +59,6 @@ EXPLAIN (ANALYZE, BUFFERS) EXECUTE first_page('00000000-0000-4000-8000-000000000
|
||||
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 ==='
|
||||
|
||||
@@ -1,13 +1,4 @@
|
||||
#!/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
|
||||
@@ -17,7 +8,7 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
from client import Client, check
|
||||
|
||||
PASSED = 0
|
||||
|
||||
@@ -46,7 +37,6 @@ def main():
|
||||
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": ',
|
||||
@@ -57,24 +47,19 @@ def main():
|
||||
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
|
||||
@@ -96,8 +81,6 @@ def main():
|
||||
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(
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
#!/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")/.."
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/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")/.."
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
"""Shared helpers for student tests: public client + direct access to the compose stack."""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -6,7 +5,7 @@ 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
|
||||
from client import Client, Failure, check
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
|
||||
SHORT_TTL_URL = os.environ.get("SHORT_TTL_URL", "http://localhost:8081")
|
||||
@@ -20,7 +19,6 @@ def 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:]))
|
||||
@@ -28,12 +26,10 @@ def compose(*args, check_rc=True):
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user