142 lines
5.5 KiB
Python
142 lines
5.5 KiB
Python
"""Check grade 4 against the local Compose stand using synthetic data."""
|
|
|
|
import base64
|
|
import hashlib
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
from threading import Barrier
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
from client import Client, Failure, arguments, check, run, timestamp
|
|
|
|
LOGIN = "/api/v1/auth/sessions"
|
|
ME = "/api/v1/users/me"
|
|
|
|
|
|
def compose(*args):
|
|
result = subprocess.run(
|
|
["docker", "compose", *args], cwd=ROOT, check=True, timeout=60,
|
|
stdout=subprocess.PIPE, text=True, encoding="utf-8",
|
|
)
|
|
return result.stdout.strip()
|
|
|
|
|
|
def basic(registration, password):
|
|
pair = f"{registration['username']}:{password}".encode()
|
|
return {"Authorization": "Basic " + base64.b64encode(pair).decode()}
|
|
|
|
|
|
def race(client):
|
|
count = 6
|
|
body = {
|
|
"username": "race_" + uuid.uuid4().hex[:20],
|
|
"display_name": "Гонка регистрации",
|
|
"password": "Синтетический:" + uuid.uuid4().hex,
|
|
}
|
|
barrier = Barrier(count, timeout=10)
|
|
|
|
def attempt(_):
|
|
worker = Client(client.base)
|
|
barrier.wait()
|
|
return worker.call("POST", "/api/v1/users", (201, 409), body=body)["status"]
|
|
|
|
with ThreadPoolExecutor(max_workers=count) as workers:
|
|
statuses = sorted(workers.map(attempt, range(count)))
|
|
check(statuses == [201] + [409] * (count - 1), "duplicate registration race failed")
|
|
print(f"PASS registration race ({count} concurrent attempts): {statuses}")
|
|
client.call("POST", LOGIN, 201, schema="Session", headers=basic(body, body["password"]))
|
|
print("PASS Basic login with a Unicode password containing a colon")
|
|
|
|
|
|
def rollback(client, actor):
|
|
# The title is generated here from fixed ASCII and a UUID, with no external input.
|
|
title = "rollback_" + uuid.uuid4().hex
|
|
client.call("POST", "/api/v1/chats", 400, actor=actor, body={
|
|
"title": title, "member_ids": [actor["id"], str(uuid.uuid4())],
|
|
})
|
|
remaining = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
|
|
"-XAt", "-v", "ON_ERROR_STOP=1", "-c",
|
|
f"SELECT count(*) FROM chats WHERE title = '{title}'")
|
|
check(remaining == "0", "a rejected chat left an orphan row")
|
|
print("PASS rollback: HTTP 400 and zero rows for rejected chat in PostgreSQL")
|
|
|
|
|
|
def wait_ready(client):
|
|
deadline = time.monotonic() + 45
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
if client.call("GET", "/health/ready", (200, 503))["status"] == 200:
|
|
return
|
|
except Failure:
|
|
pass
|
|
time.sleep(0.3)
|
|
raise Failure("API did not become ready")
|
|
|
|
|
|
def outage(client, service, actor):
|
|
compose("stop", service)
|
|
try:
|
|
client.call("GET", "/health/live", schema="Health")
|
|
client.call("GET", "/health/ready", 503)
|
|
failure = client.call("GET", ME, 503, actor=actor)
|
|
check(failure["elapsed"] < 5, "dependency failure exceeded HTTP time budget")
|
|
client.call("GET", ME, 401, headers={"X-User-Id": actor["id"]})
|
|
finally:
|
|
compose("start", service)
|
|
started = time.monotonic()
|
|
wait_ready(client)
|
|
same = client.call("GET", ME, actor=actor, schema="User")["json"]
|
|
check(same == actor["user"], "previous session did not recover")
|
|
print(f"PASS {service} outage: live=200 ready=503 Bearer=503 "
|
|
f"({failure['elapsed']:.3f}s) anonymous=401; same token after start "
|
|
f"({time.monotonic() - started:.3f}s from docker compose start return)")
|
|
|
|
|
|
def expiry(client):
|
|
actor = client.user("expiry")
|
|
session = client.call("POST", LOGIN, 201, schema="Session",
|
|
headers=basic(actor["registration"], actor["registration"]["password"]))["json"]
|
|
actor["token"] = session["token"]
|
|
remaining = (timestamp(session["expires_at"]) - datetime.now(timezone.utc)).total_seconds()
|
|
check(0 < remaining <= 2.1, "start API with SESSION_TTL_SECONDS=2 for this test")
|
|
client.call("GET", ME, actor=actor, schema="User")
|
|
time.sleep(remaining + 0.15)
|
|
client.call("GET", ME, 401, actor=actor)
|
|
print("PASS 2s expiry: same token 200 before deadline and 401 after deadline")
|
|
|
|
|
|
def main():
|
|
args = arguments("Lab 2 grade 4 checks (stop and restore dependencies)",
|
|
lambda p: p.add_argument("--expiry-only", action="store_true"))
|
|
client = Client(args.base_url, args.ca_file, timeout=6)
|
|
wait_ready(client)
|
|
if args.expiry_only:
|
|
expiry(client)
|
|
return
|
|
race(client)
|
|
actor = client.user("outage")
|
|
rollback(client, actor)
|
|
client.call("POST", LOGIN, 401, headers=basic(actor["registration"], "Wrong:password-123"))
|
|
revoked = client.user("logout")
|
|
client.call("DELETE", LOGIN + "/current", 204, actor=revoked)
|
|
client.call("GET", ME, 401, actor=revoked)
|
|
print("PASS wrong password=401, logout=204, revoked token=401")
|
|
key = "lab2:session:" + hashlib.sha256(actor["token"].encode()).hexdigest()
|
|
ttl = int(compose("exec", "-T", "redis", "redis-cli", "TTL", key))
|
|
check(ttl >= 300, "start the default-TTL stand for the dependency tests")
|
|
print(f"PASS Redis session key has TTL ({ttl}s left)")
|
|
outage(client, "redis", actor)
|
|
client.call("GET", ME, 401, actor=revoked)
|
|
print("PASS Redis restart did not revive revoked session")
|
|
outage(client, "postgres", actor)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run(main)
|