forked from mtusi2026/mtusi2026lab5
- F03: тело читается через read1 (один recv) с пересчётом общего срока перед каждым чтением: upload, JSON (JSON_BODY_TIMEOUT_SECONDS) и дочитывание отклонённого тела; до исправления клиент «по байту» держал приём > 20 с при сроке 5 с - F08: непарный суррогат в JSON -> 400 invalid_request вместо 500 - F09: объект скачивается во временный файл и сверяется (размер, SHA-256) до отправки 200; при расхождении 503 - F17: send_error в общем JSON-формате с X-Request-Id/X-Instance-Id, неподдержанный метод -> 405, у HEAD без тела - тесты api_negative_lab5.py, slow_client.py, progressive_upload.py
103 lines
4.4 KiB
Python
103 lines
4.4 KiB
Python
#!/usr/bin/env python3
|
||
"""Аудит F03: общий срок приёма тела нельзя обойти, присылая данные по байту.
|
||
|
||
python3 student-tests/slow_client.py --output evidence/slow-client.json
|
||
|
||
На время теста API пересоздаётся с UPLOAD_TIMEOUT_SECONDS=5 и JSON_BODY_TIMEOUT_SECONDS=3
|
||
(чтобы не ждать 60 с), затем возвращается к .env. Сырой сокет через LB:
|
||
upload: заголовки + первые 33 байта PNG, дальше по 1 байту каждые 0,5 с (тело 5000 байт —
|
||
без ограничения передача длилась бы ~40 мин);
|
||
JSON: POST /users с Content-Length 200, по 1 байту каждые 0,5 с.
|
||
Ожидаем ответ 400 invalid_request (или закрытие соединения) не позже срок + 2 с, после чего
|
||
обычный upload снова 202 (слоты освобождены).
|
||
"""
|
||
import argparse
|
||
import json
|
||
import socket
|
||
import time
|
||
from urllib.parse import urlsplit
|
||
|
||
from lab5lib import Client, Log, SAMPLE_PNG, check, recreate, upload
|
||
|
||
ENV = {"UPLOAD_TIMEOUT_SECONDS": "5", "JSON_BODY_TIMEOUT_SECONDS": "3"}
|
||
|
||
|
||
def drip(base, head, body_first, total_len, limit_s):
|
||
u = urlsplit(base)
|
||
s = socket.create_connection((u.hostname, u.port or 80), timeout=2)
|
||
s.sendall(head + body_first)
|
||
started = time.monotonic()
|
||
sent = len(body_first)
|
||
resp = b""
|
||
while time.monotonic() - started < limit_s:
|
||
try:
|
||
chunk = s.recv(65536)
|
||
if not chunk:
|
||
break
|
||
resp += chunk
|
||
if b"\r\n\r\n" in resp:
|
||
break
|
||
except socket.timeout:
|
||
pass
|
||
except OSError:
|
||
break
|
||
if sent < total_len:
|
||
try:
|
||
s.sendall(b"\0")
|
||
sent += 1
|
||
except OSError:
|
||
break
|
||
time.sleep(0.5)
|
||
elapsed = round(time.monotonic() - started, 2)
|
||
s.close()
|
||
status = int(resp.split(b" ", 2)[1]) if resp.startswith(b"HTTP/") else None
|
||
body = resp.split(b"\r\n\r\n", 1)[1] if b"\r\n\r\n" in resp else b""
|
||
code = None
|
||
if body.startswith(b"{"):
|
||
try:
|
||
code = json.loads(body)["error"]["code"]
|
||
except ValueError:
|
||
pass
|
||
return {"status": status, "code": code, "seconds": elapsed, "bytes_sent": sent, "of": total_len,
|
||
"x_instance_id": b"x-instance-id" in resp.lower()}
|
||
|
||
|
||
def main():
|
||
p = argparse.ArgumentParser()
|
||
p.add_argument("--base-url", default="http://localhost:8080")
|
||
p.add_argument("--output")
|
||
args = p.parse_args()
|
||
log = Log("slow client vs total body deadline")
|
||
recreate("api", ENV)
|
||
log.step("api recreated", env=ENV)
|
||
res = {}
|
||
try:
|
||
c = Client(args.base_url, timeout=30)
|
||
alice, _bob, _eve, chat = c.bootstrap()
|
||
u = urlsplit(args.base_url)
|
||
head = ("POST /api/v1/chats/%s/attachments?filename=slow.png HTTP/1.1\r\nHost: %s\r\n"
|
||
"Authorization: Bearer %s\r\nContent-Type: image/png\r\nContent-Length: 5000\r\n\r\n"
|
||
% (chat["id"], u.netloc, alice["token"])).encode()
|
||
res["upload"] = drip(args.base_url, head, SAMPLE_PNG[:33], 5000, 20)
|
||
log.step("upload drip 1 B / 0.5 s", **res["upload"])
|
||
check(res["upload"]["seconds"] <= 7 and res["upload"]["bytes_sent"] < 5000, "upload deadline not enforced")
|
||
check(res["upload"]["status"] == 400 and res["upload"]["x_instance_id"], "upload: expected API 400")
|
||
head = ("POST /api/v1/users HTTP/1.1\r\nHost: %s\r\nContent-Type: application/json\r\n"
|
||
"Content-Length: 200\r\n\r\n" % u.netloc).encode()
|
||
res["json"] = drip(args.base_url, head, b'{"username":', 200, 20)
|
||
log.step("json drip 1 B / 0.5 s", **res["json"])
|
||
check(res["json"]["seconds"] <= 5 and res["json"]["bytes_sent"] < 200, "json deadline not enforced")
|
||
check(res["json"]["status"] == 400 and res["json"]["x_instance_id"], "json: expected API 400")
|
||
att = upload(c, alice, chat, SAMPLE_PNG, "after-slow.png")
|
||
res["normal_upload_after"] = att["status"]
|
||
log.step("normal upload afterwards", status=att["status"])
|
||
finally:
|
||
recreate("api")
|
||
log.step("api restored to .env configuration")
|
||
log.save(args.output, results=res)
|
||
print("PASS: slow clients are cut off by the total deadline")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|