Files
mtusi2026lab2/.claude/skills/run-mtusi-messenger/driver.py
T
ricoromaandClaude Opus 5.5 ae4154eaf5 feat: add password login and bearer sessions
- Argon2id password hashes, KDF in a thread with its own limit
- POST /auth/sessions with Basic, DELETE /auth/sessions/current
- Bearer sessions in PostgreSQL, X-User-Id ignored
- migration drops lab 1 data without passwords
- student-tests on tokens, sessions spec and synced specs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 18:50:42 +03:00

477 lines
16 KiB
Python

#!/usr/bin/env python3
"""Драйвер API мессенджера для агента: запуск, сценарий, запросы, остановка.
Только стандартная библиотека. Запускать из корня репозитория:
python3 .claude/skills/run-mtusi-messenger/driver.py [--port N] <cmd>
Команды:
start `make upgrade` (Postgres из compose и миграции), затем поднять
`python -m src` в фоне (console, reload) и дождаться
/health/ready; лог и pid — /tmp/mtusi-api-<port>.{log,pid}
status кто слушает порт и что отвечает /health/ready
flow сквозной сценарий по HTTP с проверками; код выхода 1 при провале
req один запрос: req METHOD PATH [--token T | --basic USER:PASS]
[--data JSON]
smoke публичный tests/smoke.py против этого порта
student собственные тесты student-tests/ (make student_test) против
этого порта
stop остановить свой экземпляр на порту
all start → flow → smoke → student (если есть student-tests/) → stop
Порт по умолчанию 18080, а не 8080: на 8080 обычно висит `make run_dev`
пользователя, и его процесс трогать не надо. Экземпляр драйвера пишет в
ту же рабочую базу Postgres, что и `make run_dev`. flow, req, smoke и
student работают с любым сервером на порту, в том числе с контейнером
(`make run_docker APP_OUT_PORT=<port>`).
"""
import argparse
import base64
import contextlib
import json
import os
import signal
import subprocess
import sys
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
DEFAULT_PORT = 18080
USERS = "/api/v1/users"
CHATS = "/api/v1/chats"
SESSIONS = "/api/v1/auth/sessions"
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
def paths(port: int) -> tuple[Path, Path]:
return (
Path(f"/tmp/mtusi-api-{port}.log"),
Path(f"/tmp/mtusi-api-{port}.pid"),
)
def base_url(port: int) -> str:
return f"http://127.0.0.1:{port}"
def basic(username: str, password: str) -> str:
"""Значение `Authorization: Basic` из username и пароля в UTF-8."""
raw = f"{username}:{password}".encode()
return "Basic " + base64.b64encode(raw).decode("ascii")
def call(
port: int,
method: str,
path: str,
*,
token: str | None = None,
authorization: str | None = None,
extra: dict[str, str] | None = None,
body: object = None,
raw: bytes | None = None,
) -> tuple[int, dict[str, str], object]:
data = raw
headers = {"Accept": "application/json"}
if body is not None:
data = json.dumps(body).encode()
if data is not None:
headers["Content-Type"] = "application/json"
if token is not None:
headers["Authorization"] = f"Bearer {token}"
if authorization is not None:
headers["Authorization"] = authorization
headers.update(extra or {})
request = urllib.request.Request(
base_url(port) + path,
data=data,
method=method,
headers=headers,
)
try:
with urllib.request.urlopen(request, timeout=5) as response:
status = response.status
hdrs = dict(response.headers)
payload = response.read()
except urllib.error.HTTPError as error:
status, hdrs, payload = error.code, dict(error.headers), error.read()
hdrs = {key.lower(): value for key, value in hdrs.items()}
try:
parsed = json.loads(payload) if payload else None
except json.JSONDecodeError:
parsed = payload.decode(errors="replace")
return status, hdrs, parsed
def listener_pids(port: int) -> list[int]:
out = subprocess.run(
["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-t"],
capture_output=True,
text=True,
check=False,
).stdout
return [int(pid) for pid in out.split()]
def is_ready(port: int) -> bool:
try:
status, _, _ = call(port, "GET", "/health/ready")
except OSError:
return False
return status == 200
def cmd_start(port: int) -> int:
log_path, pid_path = paths(port)
if listener_pids(port):
if is_ready(port):
print(f"already up on {base_url(port)}")
return 0
print(f"port {port} is busy:", listener_pids(port))
return 1
# без Postgres сервис стартует, но /health/ready отвечает 503
upgrade = subprocess.run(
["make", "upgrade"],
cwd=ROOT,
capture_output=True,
text=True,
check=False,
)
if upgrade.returncode != 0:
print("make upgrade failed:")
print((upgrade.stdout + upgrade.stderr)[-2000:])
return 1
env = os.environ | {"APP__RUN_MODE": "console", "APP__PORT": str(port)}
with log_path.open("wb") as log:
proc = subprocess.Popen(
["uv", "run", "python", "-m", "src"],
cwd=ROOT,
env=env,
stdout=log,
stderr=subprocess.STDOUT,
# своя группа процессов: stop гасит uv, reloader и worker разом
start_new_session=True,
)
pid_path.write_text(str(proc.pid))
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
if proc.poll() is not None:
print(f"server exited with {proc.returncode}; log: {log_path}")
print(log_path.read_text()[-2000:])
return 1
if is_ready(port):
print(f"up on {base_url(port)} pgid={proc.pid} log={log_path}")
return 0
time.sleep(0.25)
print(f"not ready after 30s; log: {log_path}")
return 1
def cmd_stop(port: int) -> int:
_, pid_path = paths(port)
if not pid_path.exists():
# экземпляр не наш (например, make run_dev): не трогаем
if listener_pids(port):
print(f"port {port} is not ours (no pid file); left running")
return 1
print(f"nothing on {port}")
return 0
with contextlib.suppress(ProcessLookupError):
os.killpg(int(pid_path.read_text()), signal.SIGTERM)
pid_path.unlink()
deadline = time.monotonic() + 12
while listener_pids(port) and time.monotonic() < deadline:
time.sleep(0.2)
if listener_pids(port):
print(f"still listening on {port}:", listener_pids(port))
return 1
print(f"stopped {port}")
return 0
def cmd_status(port: int) -> int:
pids = listener_pids(port)
print("listeners:", pids or "none")
if pids:
print("ready:", is_ready(port))
return 0 if pids else 1
def cmd_req(port: int, args: argparse.Namespace) -> int:
body = json.loads(args.data) if args.data is not None else None
authorization = None
if args.basic is not None:
username, _, password = args.basic.partition(":")
authorization = basic(username, password)
status, hdrs, payload = call(
port,
args.method.upper(),
args.path,
token=args.token,
authorization=authorization,
body=body,
)
print(status, "x-request-id:", hdrs.get("x-request-id"))
if "www-authenticate" in hdrs:
print("www-authenticate:", hdrs["www-authenticate"])
print(json.dumps(payload, ensure_ascii=False, indent=2))
return 0 if status < 400 else 2
class Flow:
def __init__(self, port: int) -> None:
self.port = port
self.failures = 0
def check(self, label: str, ok: bool, detail: object = "") -> None:
mark = "ok " if ok else "FAIL"
print(f"[{mark}] {label}" + (f" {detail}" if detail else ""))
if not ok:
self.failures += 1
def expect(
self,
label: str,
method: str,
path: str,
status: int,
challenge: str | None = None,
**kwargs: object,
) -> object:
"""Запрос + проверка статуса, X-Request-Id, формата ошибки и,
если задан, `WWW-Authenticate`."""
got, hdrs, payload = call(self.port, method, path, **kwargs)
request_id = hdrs.get("x-request-id")
ok = got == status and bool(request_id)
detail = str(got)
if got >= 400:
error = {}
if isinstance(payload, dict):
error = payload.get("error", {})
ok = ok and error.get("request_id") == request_id
detail = f"{got} {error.get('code')}"
if challenge is not None:
ok = ok and hdrs.get("www-authenticate") == challenge
detail += f" {hdrs.get('www-authenticate')}"
shown = path if len(path) <= 60 else path[:57] + "..."
self.check(f"{method} {shown} -> {status} ({label})", ok, detail)
return payload
def cmd_flow(port: int) -> int:
flow = Flow(port)
tag = uuid.uuid4().hex[:8]
flow.expect("live", "GET", "/health/live", 200)
flow.expect("ready", "GET", "/health/ready", 200)
me_path = f"{USERS}/me"
ids, tokens, logins = {}, {}, {}
for name in ("alice", "bob", "eve"):
username, password = f"{name}_{tag}", f"Pw-{name}-{uuid.uuid4().hex}"
body = {
"username": username,
"display_name": f"{name} ✨",
"password": password,
}
user = flow.expect("register", "POST", USERS, 201, body=body)
flow.check("no password in User", "password" not in user)
session = flow.expect(
"login",
"POST",
SESSIONS,
201,
authorization=basic(username, password),
)
ids[name], tokens[name] = user["id"], session["token"]
logins[name] = (username, password)
alice, bob, eve = tokens["alice"], tokens["bob"], tokens["eve"]
dup = {
"username": f"alice_{tag}",
"display_name": "again",
"password": "Another-password-1",
}
flow.expect("duplicate username", "POST", USERS, 409, body=dup)
no_password = {"username": f"nopw_{tag}", "display_name": "x"}
flow.expect("no password", "POST", USERS, 400, body=no_password)
username, password = logins["alice"]
wrong = basic(username, "Wrong-password-1")
flow.expect(
"wrong password",
"POST",
SESSIONS,
401,
challenge=BASIC_CHALLENGE,
authorization=wrong,
)
me = flow.expect("me", "GET", me_path, 200, token=alice)
flow.check("me.id == alice", me.get("id") == ids["alice"])
flow.expect("no token", "GET", me_path, 401, challenge=BEARER_CHALLENGE)
flow.expect(
"Basic on business endpoint",
"GET",
me_path,
401,
challenge=BEARER_CHALLENGE,
authorization=basic(username, password),
)
flow.expect(
"only X-User-Id",
"GET",
me_path,
401,
challenge=BEARER_CHALLENGE,
extra={"X-User-Id": ids["alice"]},
)
spoofed = flow.expect(
"X-User-Id ignored",
"GET",
me_path,
200,
token=alice,
extra={"X-User-Id": ids["eve"]},
)
flow.check("still alice", spoofed.get("id") == ids["alice"])
flow.expect(
"unknown token",
"GET",
me_path,
401,
challenge=BEARER_CHALLENGE,
token=uuid.uuid4().hex * 2,
)
body = {"title": "Проект 🚀", "member_ids": [ids["alice"], ids["bob"]]}
chat = flow.expect("new chat", "POST", CHATS, 201, token=alice, body=body)
chat_path = f"{CHATS}/{chat['id']}"
msgs = f"{chat_path}/messages"
body = {"title": "x", "member_ids": [ids["alice"]]}
flow.expect("not a member", "POST", CHATS, 400, token=eve, body=body)
texts = ["привет", "hi 👋", "третье", "четвёртое", "пятое"]
for index, text in enumerate(texts):
sender = alice if index % 2 == 0 else bob
body = {"text": text}
flow.expect("send", "POST", msgs, 201, token=sender, body=body)
blank = {"text": " "}
flow.expect("blank text", "POST", msgs, 400, token=alice, body=blank)
spoof = {"text": "x", "sender_id": ids["alice"]}
flow.expect("sender_id", "POST", msgs, 400, token=alice, body=spoof)
seen, cursor, pages = [], None, 0
while pages < 10:
query = "?limit=2" + (f"&cursor={cursor}" if cursor else "")
page = flow.expect("page", "GET", msgs + query, 200, token=bob)
seen += [item["text"] for item in page["items"]]
cursor, pages = page["next_cursor"], pages + 1
if cursor is None:
break
flow.check("history order via cursor", seen == texts, f"{pages} pages")
flow.check("created_at ends with Z", chat["created_at"].endswith("Z"))
flow.expect("outsider reads chat", "GET", chat_path, 404, token=eve)
flow.expect("outsider reads history", "GET", msgs, 404, token=eve)
hi = {"text": "hi"}
flow.expect("outsider posts", "POST", msgs, 404, token=eve, body=hi)
flow.expect("no token beats 404", "GET", chat_path, 401)
flow.expect("limit=0", "GET", msgs + "?limit=0", 400, token=alice)
flow.expect("bad cursor", "GET", msgs + "?cursor=zzz", 400, token=alice)
flow.expect("chat_id not uuid", "GET", f"{CHATS}/nope", 400, token=alice)
flow.expect("malformed json", "POST", USERS, 400, raw=b"{not json")
flow.expect("unknown path", "GET", "/nope", 404)
chats = flow.expect("list chats", "GET", CHATS, 200, token=bob)
listed = [item["id"] for item in chats["items"]]
flow.check("bob sees the chat", chat["id"] in listed)
flow.expect("logout", "DELETE", f"{SESSIONS}/current", 204, token=eve)
flow.expect(
"token after logout",
"GET",
me_path,
401,
challenge=BEARER_CHALLENGE,
token=eve,
)
print(
f"\nalice={ids['alice']}\nbob={ids['bob']}\neve={ids['eve']}"
f"\nchat={chat['id']}"
# синтетический токен локального стенда: для `req --token`
f"\nalice_token={alice}",
)
print("FAILED:", flow.failures or "none")
return 1 if flow.failures else 0
def cmd_smoke(port: int) -> int:
return subprocess.call(
[
sys.executable,
"tests/smoke.py",
"--base-url",
f"http://localhost:{port}",
],
cwd=ROOT,
)
def cmd_student(port: int) -> int:
if not (ROOT / "student-tests").is_dir():
print("no student-tests/ in this checkout")
return 1
return subprocess.call(
["make", "student_test", f"BASE_URL=http://localhost:{port}"],
cwd=ROOT,
)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
sub = parser.add_subparsers(dest="cmd", required=True)
for name in ("start", "stop", "status", "flow", "smoke", "student", "all"):
sub.add_parser(name)
req = sub.add_parser("req")
req.add_argument("method")
req.add_argument("path")
auth = req.add_mutually_exclusive_group()
auth.add_argument("--token", help="Bearer-токен сессии")
auth.add_argument("--basic", help="USER:PASS для POST /auth/sessions")
req.add_argument("--data")
args = parser.parse_args()
port = args.port
if args.cmd == "all":
if cmd_start(port) != 0:
return 1
try:
flow_rc = cmd_flow(port)
smoke_rc = cmd_smoke(port)
student_rc = 0
if (ROOT / "student-tests").is_dir():
student_rc = cmd_student(port)
finally:
cmd_stop(port)
return flow_rc or smoke_rc or student_rc
if args.cmd == "req":
return cmd_req(port, args)
handlers = {
"start": cmd_start,
"stop": cmd_stop,
"status": cmd_status,
"flow": cmd_flow,
"smoke": cmd_smoke,
"student": cmd_student,
}
return handlers[args.cmd](port)
if __name__ == "__main__":
sys.exit(main())