Реализовать лабораторную 2 на оценку 4

PostgreSQL как источник истины, непрозрачные сессии в Redis с TTL и AOF, миграции под advisory lock, пул и таймауты, проверки гонки/отката/отказов и отчёт с evidence.
This commit is contained in:
Чиняева
2026-11-06 22:37:31 +03:00
parent 65003b6119
commit df31f4a9fb
43 changed files with 2045 additions and 22 deletions
+31
View File
@@ -0,0 +1,31 @@
# Студенческие проверки уровня 4
Все проверки, кроме `rollback_chat.py` и `explain_history.py`, запускаются на
хосте и обращаются к API по HTTP. Две проверки используют `psycopg` и запускаются
внутри контейнера `api`, где зависимость уже установлена.
```sh
# 1. Негативная аутентификация и logout
python student-tests/auth_negative.py --base-url http://localhost:8080
# 2. Гонка регистрации одного username
python student-tests/race_username.py --base-url http://localhost:8080 --workers 8
# 3. Откат составной операции (внутри контейнера)
docker compose exec -T api python student-tests/rollback_chat.py
# 4. EXPLAIN на 10 000 сообщений (внутри контейнера)
docker compose exec -T api python student-tests/explain_history.py \
--output /tmp/explain_history.txt
# 5. Отказы Redis и PostgreSQL (с хоста; управляет docker compose)
python student-tests/fault_matrix.py
# 6. Истечение сессии: API должен быть запущен с коротким TTL
# SESSION_TTL_SECONDS=2 docker compose up -d --force-recreate api
python student-tests/expiry.py --wait 4
```
`fault_matrix.py` останавливает `redis`/`postgres` и обязательно запускает их
обратно в `finally`. Он проверяет только ограниченные `503`, отсутствие
доверенного анонимного доступа и сохранность сессии после рестарта Redis с AOF.
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Wrong password, Basic-on-business-endpoint, logout and reuse checks."""
from __future__ import annotations
import argparse
import base64
from common import HttpClient, assert_status, error_code
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
client = HttpClient(args.base_url)
user, registration = client.register()
wrong = base64.b64encode(
(registration["username"] + ":wrong-password-value").encode("utf-8")
).decode("ascii")
status, headers, payload, _ = client.call(
"POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + wrong}
)
assert_status(status, 401, "wrong password")
assert error_code(payload) == "unauthorized"
assert headers.get("WWW-Authenticate", "").lower().startswith("basic")
good = base64.b64encode(
(registration["username"] + ":" + registration["password"]).encode("utf-8")
).decode("ascii")
status, headers, _, _ = client.call(
"GET", "/api/v1/users/me", headers={"Authorization": "Basic " + good}
)
assert_status(status, 401, "Basic on business endpoint")
assert headers.get("WWW-Authenticate", "").lower().startswith("bearer")
session = client.login(registration)
token = session["token"]
status, _, me, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 200, "login")
assert me["id"] == user["id"]
status, _, _, raw = client.call("DELETE", "/api/v1/auth/sessions/current", token=token)
assert_status(status, 204, "logout")
assert raw == b"", "204 must have an empty body"
status, headers, payload, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 401, "token after logout")
assert error_code(payload) == "unauthorized"
assert headers.get("WWW-Authenticate", "").lower().startswith("bearer")
status, _, _, _ = client.call("DELETE", "/api/v1/auth/sessions/current", token=token)
assert_status(status, 401, "second logout")
print("PASS: wrong password, Basic rejection, logout and token reuse checks")
if __name__ == "__main__":
main()
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Small standard-library HTTP helpers for the student checks."""
from __future__ import annotations
import base64
import json
import os
import uuid
import urllib.error
import urllib.request
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
class HttpClient:
def __init__(self, base_url: str | None = None):
self.base = (base_url or BASE_URL).rstrip("/")
def call(self, method: str, path: str, body=None, token: str | None = None, headers=None):
h = {"Accept": "application/json"}
data = None
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
h["Content-Type"] = "application/json"
if token:
h["Authorization"] = "Bearer " + token
h.update(headers or {})
request = urllib.request.Request(self.base + path, data=data, headers=h, method=method)
try:
response = urllib.request.urlopen(request, timeout=10)
except urllib.error.HTTPError as error:
response = error
with response:
raw = response.read()
payload = None
if raw:
try:
payload = json.loads(raw)
except ValueError:
payload = None
return response.code, response.headers, payload, raw
def register(self) -> tuple[dict, dict]:
suffix = uuid.uuid4().hex[:12]
registration = {
"username": "st_" + suffix,
"display_name": "Студент " + suffix,
"password": "T3st-" + uuid.uuid4().hex,
}
status, _headers, user, _raw = self.call("POST", "/api/v1/users", registration)
if status != 201:
raise AssertionError(f"registration failed: HTTP {status}")
return user, registration
def login(self, registration: dict) -> dict:
credential = base64.b64encode(
(registration["username"] + ":" + registration["password"]).encode("utf-8")
).decode("ascii")
status, _headers, session, _raw = self.call(
"POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + credential}
)
if status != 201:
raise AssertionError(f"login failed: HTTP {status}")
return session
def assert_status(actual: int, expected: int, label: str) -> None:
if actual != expected:
raise AssertionError(f"{label}: expected HTTP {expected}, received {actual}")
def error_code(payload) -> str | None:
if not isinstance(payload, dict):
return None
error = payload.get("error")
return error.get("code") if isinstance(error, dict) else None
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
"""Expiry check: run against an API with SESSION_TTL_SECONDS=2 (or pass --wait)."""
from __future__ import annotations
import argparse
import time
from common import HttpClient, assert_status, error_code
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--wait", type=float, default=3.0)
args = parser.parse_args()
client = HttpClient(args.base_url)
user, registration = client.register()
session = client.login(registration)
token = session["token"]
status, headers, payload, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 200, "fresh session")
assert payload["id"] == user["id"], "wrong current user"
time.sleep(args.wait)
status, headers, payload, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 401, "expired session")
assert error_code(payload) == "unauthorized", "expired session must be unauthorized"
assert headers.get("WWW-Authenticate", "").lower().startswith("bearer"), "missing Bearer challenge"
print("PASS: expired session is rejected with 401 and Bearer challenge")
if __name__ == "__main__":
main()
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env python3
"""Create 10 000 synthetic messages and record EXPLAIN (ANALYZE, BUFFERS).
Run inside the API container (psycopg is installed there):
docker compose exec -T api python student-tests/explain_history.py \
--output /app/evidence/explain_history.txt
The evidence directory is mounted read-only in the container, so the example
below is normally executed with a writable bind mount or copied out.
"""
from __future__ import annotations
import argparse
import os
import uuid
from datetime import datetime, timezone
from pathlib import Path
import psycopg
MESSAGES = 10_000
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--database-url", default=os.environ.get("DATABASE_URL"))
parser.add_argument("--output", default="evidence/explain_history.txt")
parser.add_argument("--messages", type=int, default=MESSAGES)
args = parser.parse_args()
if not args.database_url:
raise SystemExit("DATABASE_URL is required")
tag = uuid.uuid4().hex[:10]
user_id = uuid.uuid4()
chat_id = uuid.uuid4()
with psycopg.connect(args.database_url) as conn:
conn.execute(
"INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s)",
(user_id, "perf_" + tag, "Performance synthetic", "not-a-real-password-hash"),
)
conn.execute("INSERT INTO chats (id, title) VALUES (%s, %s)", (chat_id, "perf-" + tag))
conn.execute(
"INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", (chat_id, user_id)
)
conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), %s, %s, 'synthetic message ' || g,
timestamptz '2026-01-01 00:00:00+00' + (g || ' milliseconds')::interval
FROM generate_series(1, %s) AS g
""",
(chat_id, user_id, args.messages),
)
total = conn.execute(
"SELECT count(*) FROM messages WHERE chat_id = %s", (chat_id,)
).fetchone()[0]
conn.execute("ANALYZE messages")
cursor = conn.execute(
"""
SELECT created_at, id FROM messages
WHERE chat_id = %s ORDER BY created_at, id
OFFSET %s LIMIT 1
""",
(chat_id, max(0, args.messages - 500)),
).fetchone()
plan_rows = conn.execute(
"""
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = %s AND (created_at, id) > (%s, %s)
ORDER BY created_at, id
LIMIT 51
""",
(chat_id, cursor[0], cursor[1]),
).fetchall()
conn.commit()
plan = "\n".join(row[0] for row in plan_rows)
if "messages_chat_created_at_id_idx" not in plan:
raise AssertionError("history query did not use the keyset index:\n" + plan)
if "Seq Scan" in plan:
raise AssertionError("history query performed a sequential scan:\n" + plan)
header = (
"# EXPLAIN (ANALYZE, BUFFERS) for keyset history pagination\n"
f"generated_at_utc: {datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')}\n"
f"messages_in_chat: {total}\n"
f"chat_id: {chat_id}\n"
"query: WHERE chat_id = ? AND (created_at, id) > (?, ?) "
"ORDER BY created_at, id LIMIT 51\n\n"
)
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(header + plan + "\n", encoding="utf-8")
print(header + plan)
print(f"PASS: index used on {total} messages; evidence written to {output}")
if __name__ == "__main__":
main()
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
"""Dependency-failure matrix: Redis and PostgreSQL outages must be bounded.
The check uses the local Compose project. It stops one dependency, verifies
503 (never 200 and never a trusted anonymous request), starts it again, waits
for readiness and confirms the original bearer session still works after the
Redis restart (AOF persistence).
"""
from __future__ import annotations
import argparse
import os
import subprocess
import time
from pathlib import Path
from common import HttpClient, assert_status, error_code
ROOT = Path(__file__).resolve().parents[1]
def compose(*args: str) -> None:
subprocess.run(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def wait_ready(client: HttpClient, expected: int, seconds: float = 90) -> None:
deadline = time.monotonic() + seconds
last = None
while time.monotonic() < deadline:
try:
status, _, _, _ = client.call("GET", "/health/ready")
last = status
if status == expected:
return
except OSError:
last = "connection error"
time.sleep(0.5)
raise AssertionError(f"readiness did not become {expected}; last={last}")
def expect_503(client: HttpClient, path: str, token: str | None, label: str) -> None:
status, _headers, payload, _raw = client.call("GET", path, token=token)
if status != 503:
raise AssertionError(f"{label}: expected 503, received {status}")
if error_code(payload) != "unavailable":
raise AssertionError(f"{label}: expected unavailable error code")
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
client = HttpClient(args.base_url)
user, registration = client.register()
session = client.login(registration)
token = session["token"]
results = []
try:
compose("stop", "redis")
expect_503(client, "/health/ready", None, "Redis down readiness")
expect_503(client, "/api/v1/users/me", token, "Redis down authenticated request")
results.append("redis down: readiness=503, bearer request=503")
started = time.monotonic()
compose("start", "redis")
wait_ready(client, 200)
redis_recovery = round(time.monotonic() - started, 2)
status, _, me, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 200, "session after Redis restart")
if me["id"] != user["id"]:
raise AssertionError("session identity changed after Redis restart")
results.append(f"redis up: readiness=200 in {redis_recovery}s, same token=200 (AOF persistence)")
compose("stop", "postgres")
time.sleep(1)
expect_503(client, "/health/ready", None, "PostgreSQL down readiness")
expect_503(client, "/api/v1/users/me", token, "PostgreSQL down authenticated request")
results.append("postgres down: readiness=503, bearer request=503")
started = time.monotonic()
compose("start", "postgres")
wait_ready(client, 200)
postgres_recovery = round(time.monotonic() - started, 2)
status, _, me, _ = client.call("GET", "/api/v1/users/me", token=token)
assert_status(status, 200, "session after PostgreSQL restart")
results.append(f"postgres up: readiness=200 in {postgres_recovery}s, same token=200")
finally:
compose("start", "redis")
compose("start", "postgres")
for line in results:
print("OBSERVED:", line)
print("PASS: dependency loss produced only bounded 503 responses; no anonymous trust")
if __name__ == "__main__":
main()
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Print the effective PostgreSQL timeouts and pool limits.
Run inside the API container:
docker compose exec -T api python student-tests/pool_settings.py
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app import db
def main() -> None:
db.pool().open(wait=True, timeout=5)
db.apply_migrations()
with db.pool().connection() as conn:
statement = conn.execute("SHOW statement_timeout").fetchone()["statement_timeout"]
idle = conn.execute("SHOW idle_in_transaction_session_timeout").fetchone()[
"idle_in_transaction_session_timeout"
]
lock = conn.execute("SHOW lock_timeout").fetchone()["lock_timeout"]
stats = db.pool().get_stats()
print("statement_timeout =", statement)
print("idle_in_transaction_session_timeout =", idle)
print("lock_timeout =", lock)
print("pool_min =", stats["pool_min"])
print("pool_max =", stats["pool_max"])
print("pool_size =", stats["pool_size"])
print("pool_available =", stats["pool_available"])
print("PASS: bounded pool and SQL timeouts are active")
if __name__ == "__main__":
main()
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Concurrent registration with the same username: one 201, the rest 409."""
from __future__ import annotations
import argparse
import uuid
from concurrent.futures import ThreadPoolExecutor
from common import HttpClient, assert_status, error_code
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--workers", type=int, default=8)
args = parser.parse_args()
client = HttpClient(args.base_url)
username = "race_" + uuid.uuid4().hex[:16]
body = {
"username": username,
"display_name": "Race candidate",
"password": "T3st-" + uuid.uuid4().hex,
}
def register(_index: int):
status, _, payload, _ = client.call("POST", "/api/v1/users", body)
return status, error_code(payload)
with ThreadPoolExecutor(max_workers=args.workers) as executor:
results = list(executor.map(register, range(args.workers)))
statuses = [status for status, _code in results]
if statuses.count(201) != 1 or statuses.count(409) != args.workers - 1:
raise AssertionError(f"expected one 201 and {args.workers - 1} conflicts, got {statuses}")
for status, code in results:
if status == 409 and code != "conflict":
raise AssertionError("409 must carry conflict code")
session = client.login(body)
assert session["user"]["username"] == username
print(f"PASS: {args.workers} concurrent registrations produced exactly one user and one session")
if __name__ == "__main__":
main()
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
"""Prove that a failure after the chat insert rolls back the whole chat.
Run inside the API container (psycopg is installed there):
docker compose exec -T api python student-tests/rollback_chat.py
A temporary trigger aborts the second chat_members insert. The API must
return a bounded 500 and leave no chat row, because chat + membership share
one transaction.
"""
from __future__ import annotations
import argparse
import os
import uuid
import psycopg
from common import HttpClient, assert_status, error_code
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--database-url", default=os.environ.get("DATABASE_URL"))
args = parser.parse_args()
if not args.database_url:
raise SystemExit("DATABASE_URL is required")
client = HttpClient(args.base_url)
actor, actor_registration = client.register()
victim, _victim_registration = client.register()
session = client.login(actor_registration)
token = session["token"]
title = "rollback-" + uuid.uuid4().hex
function_name = "test_fail_member_" + uuid.uuid4().hex[:8]
victim_id = str(uuid.UUID(victim["id"]))
with psycopg.connect(args.database_url, autocommit=True) as conn:
conn.execute(
f"""
CREATE FUNCTION {function_name}() RETURNS trigger AS $$
BEGIN
IF NEW.user_id = '{victim_id}'::uuid THEN
RAISE EXCEPTION 'injected membership failure';
END IF;
RETURN NEW;
END
$$ LANGUAGE plpgsql
"""
)
conn.execute(
f"CREATE TRIGGER {function_name} BEFORE INSERT ON chat_members "
f"FOR EACH ROW EXECUTE FUNCTION {function_name}()"
)
try:
status, _, payload, _ = client.call(
"POST",
"/api/v1/chats",
{"title": title, "member_ids": [actor["id"], victim["id"]]},
token=token,
)
assert_status(status, 500, "injected membership failure")
if error_code(payload) != "internal_error":
raise AssertionError("unexpected error code for injected failure")
rows = conn.execute("SELECT count(*) FROM chats WHERE title = %s", (title,)).fetchone()
if rows[0] != 0:
raise AssertionError("chat survived a failed membership transaction")
finally:
conn.execute(f"DROP TRIGGER IF EXISTS {function_name} ON chat_members")
conn.execute(f"DROP FUNCTION IF EXISTS {function_name}()")
status, _, chat, _ = client.call(
"POST",
"/api/v1/chats",
{"title": title + "-ok", "member_ids": [actor["id"], victim["id"]]},
token=token,
)
assert_status(status, 201, "chat after trigger cleanup")
assert set(chat["member_ids"]) == {actor["id"], victim["id"]}
print("PASS: failed membership insert rolled back the chat; subsequent create is atomic")
if __name__ == "__main__":
main()