From 79430df3bffa06aba9d183475691700070f61273 Mon Sep 17 00:00:00 2001 From: yura Date: Fri, 13 Nov 2026 20:45:40 +0300 Subject: [PATCH] =?UTF-8?q?=D0=90=D1=83=D0=B4=D0=B8=D1=82=20F03,=20F08,=20?= =?UTF-8?q?F09,=20F17:=20=D0=BE=D0=B1=D1=89=D0=B8=D0=B9=20=D1=81=D1=80?= =?UTF-8?q?=D0=BE=D0=BA=20=D0=BF=D1=80=D0=B8=D1=91=D0=BC=D0=B0=20=D1=82?= =?UTF-8?q?=D0=B5=D0=BB=D0=B0,=20Unicode,=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=BA=D0=B0=20=D0=B4=D0=BE=20200,=20=D1=84=D0=BE=D1=80?= =?UTF-8?q?=D0=BC=D0=B0=D1=82=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- .env.example | 2 + compose.yaml | 1 + evidence/before-fix/http-audit.txt | 6 ++ evidence/progressive-upload.json | 66 ++++++++++++ evidence/slow-client.json | 67 ++++++++++++ src/server.py | 119 +++++++++++++++++---- student-tests/api_negative_lab5.py | 161 +++++++++++++++++++++++++++++ student-tests/s3_tamper.py | 27 +++-- student-tests/slow_client.py | 102 ++++++++++++++++++ 9 files changed, 521 insertions(+), 30 deletions(-) create mode 100644 evidence/before-fix/http-audit.txt create mode 100644 evidence/progressive-upload.json create mode 100644 evidence/slow-client.json create mode 100644 student-tests/api_negative_lab5.py create mode 100644 student-tests/slow_client.py diff --git a/.env.example b/.env.example index f62bd672..118fb3bc 100644 --- a/.env.example +++ b/.env.example @@ -42,6 +42,8 @@ MAX_UPLOAD_BYTES=10485760 MAX_IMAGE_PIXELS=40000000 # Весь приём тела upload, с; одновременных загрузок и JPEG-декодирований на реплику. UPLOAD_TIMEOUT_SECONDS=60 +# Общий срок приёма JSON-тела (до 1 MiB), с; оба срока не обойти медленной передачей (аудит F03). +JSON_BODY_TIMEOUT_SECONDS=10 UPLOAD_CONCURRENCY=8 DECODE_CONCURRENCY=1 # Lab5 (аудит F02): проверка JPEG в подпроцессе — лимит его адресного пространства (MiB), diff --git a/compose.yaml b/compose.yaml index c90bd9d2..975b00cd 100644 --- a/compose.yaml +++ b/compose.yaml @@ -185,6 +185,7 @@ services: S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_api_access_key S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_api_secret_key UPLOAD_TIMEOUT_SECONDS: ${UPLOAD_TIMEOUT_SECONDS:-60} + JSON_BODY_TIMEOUT_SECONDS: ${JSON_BODY_TIMEOUT_SECONDS:-10} UPLOAD_CONCURRENCY: ${UPLOAD_CONCURRENCY:-8} # Проверка JPEG — в подпроцессе src/jpeg_probe.py (аудит F02): progressive JPEG 40 Мпикс # 4:4:4 требует до ~250 MiB. Одна проба за раз + её лимит адресного пространства. diff --git a/evidence/before-fix/http-audit.txt b/evidence/before-fix/http-audit.txt new file mode 100644 index 00000000..fab2fade --- /dev/null +++ b/evidence/before-fix/http-audit.txt @@ -0,0 +1,6 @@ +# 2026-11-13T17:42:59Z ДО исправлений F03, F08 (код после eac7413, без шага 3) +$ python3 student-tests/api_negative_lab5.py +client.Failure: F08 display_name: 500 internal_error +$ python3 student-tests/slow_client.py (API с UPLOAD_TIMEOUT_SECONDS=5) +upload drip 1 B / 0.5 s {"status": null, "seconds": 20.06, "bytes_sent": 41, "of": 5000} # за 20 с сервер так и не оборвал приём +client.Failure: upload deadline not enforced diff --git a/evidence/progressive-upload.json b/evidence/progressive-upload.json new file mode 100644 index 00000000..a41274c1 --- /dev/null +++ b/evidence/progressive-upload.json @@ -0,0 +1,66 @@ +{ + "side": 6324, + "pixels": 39992976, + "uploads": [ + { + "kind": "progressive_444", + "bytes": 824851, + "status": 202, + "seconds": 0.37, + "instance": "1412199c46a5", + "id": "55a33e4f-a23c-455c-8138-1cba7063aeae", + "error": null, + "ready": true + }, + { + "kind": "progressive_444", + "bytes": 819143, + "status": 202, + "seconds": 0.72, + "instance": "5c4e29dc6a58", + "id": "7252c912-b911-49b4-bf2e-c228f37afdd8", + "error": null, + "ready": true + }, + { + "kind": "progressive_444", + "bytes": 939182, + "status": 202, + "seconds": 1.21, + "instance": "5c4e29dc6a58", + "id": "4d4b8fe4-d4a5-4673-9281-463c05f003ec", + "error": null, + "ready": true + }, + { + "kind": "progressive_444", + "bytes": 938143, + "status": 202, + "seconds": 0.8, + "instance": "1412199c46a5", + "id": "1ed6599a-bbf6-41c4-9a72-23ed98b88db4", + "error": null, + "ready": true + }, + { + "kind": "progressive_420", + "bytes": 530758, + "status": 202, + "seconds": 0.32, + "instance": "5c4e29dc6a58", + "id": "9fc3d589-53d4-47f0-9288-50a9e3429263", + "error": null, + "ready": true + }, + { + "kind": "baseline", + "bytes": 883286, + "status": 202, + "seconds": 0.99, + "instance": "1412199c46a5", + "id": "46bbe758-23f8-41d1-bccb-fb829fcc005d", + "error": null, + "ready": true + } + ] +} diff --git a/evidence/slow-client.json b/evidence/slow-client.json new file mode 100644 index 00000000..a3b85c89 --- /dev/null +++ b/evidence/slow-client.json @@ -0,0 +1,67 @@ +{ + "scenario": "slow client vs total body deadline", + "date_utc": "2026-11-13T17:45:32+00:00", + "steps": [ + { + "t": 9.41, + "utc": "17:45:14.226", + "step": "api recreated", + "env": { + "UPLOAD_TIMEOUT_SECONDS": "5", + "JSON_BODY_TIMEOUT_SECONDS": "3" + } + }, + { + "t": 14.87, + "utc": "17:45:19.690", + "step": "upload drip 1 B / 0.5 s", + "status": 400, + "code": "invalid_request", + "seconds": 5.02, + "bytes_sent": 35, + "of": 5000, + "x_instance_id": true + }, + { + "t": 17.88, + "utc": "17:45:22.700", + "step": "json drip 1 B / 0.5 s", + "status": 400, + "code": "invalid_request", + "seconds": 3.01, + "bytes_sent": 13, + "of": 200, + "x_instance_id": true + }, + { + "t": 17.91, + "utc": "17:45:22.728", + "step": "normal upload afterwards", + "status": "queued" + }, + { + "t": 27.47, + "utc": "17:45:32.290", + "step": "api restored to .env configuration" + } + ], + "results": { + "upload": { + "status": 400, + "code": "invalid_request", + "seconds": 5.02, + "bytes_sent": 35, + "of": 5000, + "x_instance_id": true + }, + "json": { + "status": 400, + "code": "invalid_request", + "seconds": 3.01, + "bytes_sent": 13, + "of": 200, + "x_instance_id": true + }, + "normal_upload_after": "queued" + } +} diff --git a/src/server.py b/src/server.py index 58360ff2..3a11292d 100644 --- a/src/server.py +++ b/src/server.py @@ -131,6 +131,8 @@ UPLOAD_READ_CHUNK = 64 * 1024 # выбрасывается, чтобы клиент, ещё передающий файл, получил ответ, а не обрыв соединения. # Больше — соединение просто закрывается (не тратим трафик на заведомо огромное тело). REJECT_DRAIN_BYTES = int(os.environ.get("REJECT_DRAIN_BYTES", str(2 * 10485760))) +# Общий срок приёма JSON-тела (до 1 MiB), аудит F03. +JSON_BODY_TIMEOUT_SECONDS = float(os.environ.get("JSON_BODY_TIMEOUT_SECONDS", "10")) # Bidi-override и изолирующие символы позволяют подделать видимое расширение (gpj.exe). _BIDI_CONTROLS = set("\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069\u200e\u200f") @@ -601,7 +603,10 @@ def receive_body(req, tmp, length, declared_type): raise bad_request("Загрузка не завершена вовремя") req.connection.settimeout(min(left, CLIENT_SOCKET_TIMEOUT_SECONDS)) try: - chunk = req.rfile.read(min(UPLOAD_READ_CHUNK, length - received)) + # read1, а не read: read(n) ждёт ВСЕ n байт за сколько угодно recv, и клиент, + # присылающий по байту, обходил общий срок (аудит F03). read1 — не больше одного + # recv, поэтому срок проверяется перед каждым фактическим чтением сокета. + chunk = req.rfile.read1(min(UPLOAD_READ_CHUNK, length - received)) except (TimeoutError, socket.timeout): raise bad_request("Загрузка не завершена вовремя") except (ConnectionError, OSError): @@ -754,7 +759,29 @@ def h_download_attachment(req, attachment_id): raise storage_unavailable() except StorageUnavailable: raise storage_unavailable() - try: + # Аудит F09: сначала весь объект (<= 10 MiB) во временный файл со сверкой размера и + # SHA-256 с метаданными, и только потом 200. Раньше заголовки 200 уходили до проверки, + # и повреждённый объект той же длины клиент получал как успешный ответ. + with tempfile.TemporaryFile(dir=UPLOAD_TMP_DIR) as tmp: + digest = hashlib.sha256() + got = 0 + try: + for chunk in resp.stream(objstore.STREAM_CHUNK): + got += len(chunk) + if got > size: + break + digest.update(chunk) + tmp.write(chunk) + except Exception as exc: + log.warning("download from storage interrupted (%s) request_id=%s", type(exc).__name__, req.request_id) + raise storage_unavailable() + finally: + resp.close() + resp.release_conn() + if got != size or digest.hexdigest() != sha: + log.error("stored object differs from metadata (attachment %s, variant %s) request_id=%s", + attachment["id"], variant or "original", req.request_id) + raise storage_unavailable() headers = { "Content-Type": content_type, "Content-Length": str(size), @@ -764,25 +791,14 @@ def h_download_attachment(req, attachment_id): } if filename: headers["Content-Disposition"] = "inline; filename*=UTF-8''" + _rfc5987(filename) + tmp.seek(0) req.send_raw_headers(200, headers) - sent = 0 - digest = hashlib.sha256() try: - for chunk in resp.stream(objstore.STREAM_CHUNK): - sent += len(chunk) - digest.update(chunk) + for chunk in iter(lambda: tmp.read(objstore.STREAM_CHUNK), b""): req.wfile.write(chunk) - except Exception as exc: - # Заголовки уже ушли: честно оборвать соединение, а не дописать мусор. - log.warning("download interrupted (%s) request_id=%s", type(exc).__name__, req.request_id) + except OSError as exc: + log.info("client went away during download (%s) request_id=%s", type(exc).__name__, req.request_id) req.close_connection = True - return 200, STREAMED - if sent != size or digest.hexdigest() != sha: - log.error("object differs from metadata %s request_id=%s", attachment["id"], req.request_id) - req.close_connection = True - finally: - resp.close() - resp.release_conn() return 200, STREAMED @@ -822,9 +838,16 @@ class Handler(BaseHTTPRequestHandler): if ctype != "application/json": raise ApiError(415, "unsupported_media_type", "Ожидается Content-Type: application/json") try: - return json.loads(self._body.decode("utf-8")) + body = json.loads(self._body.decode("utf-8")) except (UnicodeDecodeError, ValueError): raise bad_request("Некорректный JSON") + try: + # JSON-escape "\ud800" даёт непарный суррогат: такую строку нельзя закодировать в + # UTF-8 (ни для scrypt, ни для PostgreSQL) — это ошибка клиента, 400 (аудит F08). + json.dumps(body, ensure_ascii=False).encode("utf-8") + except UnicodeEncodeError: + raise bad_request("Строки должны состоять из корректных символов Unicode") + return body def current_user(self): """Только Bearer-токен действующей сессии. Basic и X-User-Id доступа не дают.""" @@ -857,9 +880,28 @@ class Handler(BaseHTTPRequestHandler): raise bad_request("Неверный Content-Length") if n > MAX_BODY_BYTES: raise ApiError(413, "payload_too_large", "Тело запроса слишком большое") - data = self.rfile.read(n) + deadline = time.monotonic() + JSON_BODY_TIMEOUT_SECONDS + parts, got = [], 0 + try: + while got < n: + left = deadline - time.monotonic() + if left <= 0: + raise TimeoutError() + self.connection.settimeout(min(left, CLIENT_SOCKET_TIMEOUT_SECONDS)) + chunk = self.rfile.read1(n - got) + if not chunk: + raise ClientGone() + parts.append(chunk) + got += len(chunk) + except (TimeoutError, socket.timeout): + self.no_drain = True # не дочитываем: соединение будет закрыто + raise ApiError(400, "invalid_request", "Запрос не получен вовремя") + except (ConnectionError, OSError): + raise ClientGone() + finally: + self.connection.settimeout(CLIENT_SOCKET_TIMEOUT_SECONDS) self.body_consumed = True - return data + return b"".join(parts) def _dispatch(self, method): global _INFLIGHT @@ -876,6 +918,7 @@ class Handler(BaseHTTPRequestHandler): self.extra_headers = {} self.body_consumed = False self.body_left = None # сколько байт тела ещё не прочитано (для upload) + self.no_drain = False # тело не дочитывать (срок приёма уже истёк) self.headers_sent = False started = time.monotonic() parts = urlsplit(self.path) @@ -932,6 +975,8 @@ class Handler(BaseHTTPRequestHandler): def _drain_rejected_body(self): """Дочитать и выбросить остаток тела отклонённого запроса (буфер 64 KiB). True — соединение снова в согласованном состоянии.""" + if getattr(self, "no_drain", False): + return False left = self.body_left if left is None: raw = self.headers.get("Content-Length") @@ -946,7 +991,7 @@ class Handler(BaseHTTPRequestHandler): if time.monotonic() > deadline: return False self.connection.settimeout(max(0.1, min(deadline - time.monotonic(), CLIENT_SOCKET_TIMEOUT_SECONDS))) - chunk = self.rfile.read(min(UPLOAD_READ_CHUNK, left)) + chunk = self.rfile.read1(min(UPLOAD_READ_CHUNK, left)) # один recv (аудит F03) if not chunk: return False left -= len(chunk) @@ -1009,6 +1054,38 @@ class Handler(BaseHTTPRequestHandler): def log_message(self, fmt, *args): pass + def send_error(self, code, message=None, explain=None): + """Ошибки, которые BaseHTTPRequestHandler формирует сам до _dispatch (неизвестный метод, + битая строка запроса, слишком длинный URI/заголовки), — в общем JSON-формате с + X-Request-Id и X-Instance-Id (аудит F17). Неподдержанный метод -> 405 (у стандартного + обработчика было 501 text/html без X-Request-Id). У HEAD тела нет.""" + if code == 501: + code = 405 + # Всегда новый id: на keep-alive соединении атрибут остался бы от прошлого запроса. + self.request_id = uuid.uuid4().hex + payload = {"error": {"code": "invalid_request" if code < 500 else "internal_error", + "message": "Метод не поддерживается" if code == 405 else "Неверный запрос", + "request_id": self.request_id}} + data = json.dumps(payload, ensure_ascii=False).encode("utf-8") + self.close_connection = True + try: + self.send_response(code) + self.send_header("X-Request-Id", self.request_id) + self.send_header("X-Instance-Id", INSTANCE_ID) + self.send_header("X-App-Version", APP_VERSION) + if code == 405: + self.send_header("Allow", "GET, POST, DELETE") + self.send_header("Connection", "close") + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + if getattr(self, "command", None) != "HEAD": + self.wfile.write(data) + except OSError: + pass + log.info("%s %s -> %d (protocol level) request_id=%s", getattr(self, "command", "-"), + (getattr(self, "path", "") or "")[:200].split("?")[0], code, self.request_id) + class Server(ThreadingHTTPServer): request_queue_size = 1024 diff --git a/student-tests/api_negative_lab5.py b/student-tests/api_negative_lab5.py new file mode 100644 index 00000000..6aefd001 --- /dev/null +++ b/student-tests/api_negative_lab5.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +"""Регрессии по внешнему аудиту (HTTP-уровень): F02, F05, F08, F09, F17. + + python3 student-tests/api_negative_lab5.py --output evidence/api-negative-lab5.json + + F08 непарный суррогат (JSON "\\ud800") в display_name / password / title / text -> 400, не 500; + то же в filename (%ED%A0%80 — невалидный UTF-8) -> 400 + F17 HEAD / OPTIONS / неизвестный метод -> 405 JSON с X-Request-Id и X-Instance-Id (у HEAD без тела) + F05 PNG с байтом фильтра 5 и 255, interlaced PNG с плохим фильтром -> 415, строка не создана + F09 объект ready-вложения испорчен в S3 (та же длина) -> content 503, а не 200 с чужими байтами + F02 4 progressive 4:4:4 + 1 progressive 4:2:0 + 1 baseline JPEG ~40 Мпикс одновременно -> все 202 + и ready; RestartCount/OOMKilled реплик API не изменились +""" +import argparse +import http.client +import json +import struct +import subprocess +import uuid +import zlib +from urllib.parse import urlsplit + +from lab5lib import (Client, Log, SAMPLE_PNG, check, compose, container_ids, ops, sql, upload, wait_status) + + +def api_state(): + out = {} + for cid in container_ids("api"): + r = subprocess.run(["docker", "inspect", "-f", "{{.Name}} {{.RestartCount}} {{.State.OOMKilled}}", cid], + capture_output=True, text=True).stdout.split() + out[r[0].lstrip("/")] = {"restarts": int(r[1]), "oom_killed": r[2] == "true"} + return out + + +def raw(base, method, path, body=None, headers=None): + u = urlsplit(base) + conn = http.client.HTTPConnection(u.hostname, u.port or 80, timeout=15) + conn.request(method, path, body=body, headers=headers or {}) + r = conn.getresponse() + data = r.read() + conn.close() + return r.status, dict((k.lower(), v) for k, v in r.getheaders()), data + + +def png(w, h, raw_rows, interlace=0): + def chunk(k, d): + return struct.pack(">I", len(d)) + k + d + struct.pack(">I", zlib.crc32(k + d) & 0xFFFFFFFF) + return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, interlace)) + + chunk(b"IDAT", zlib.compress(raw_rows)) + chunk(b"IEND", b"")) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--base-url", default="http://localhost:8080") + p.add_argument("--output") + args = p.parse_args() + log = Log("audit regressions: unicode, protocol errors, PNG filters, download integrity, progressive JPEG") + c = Client(args.base_url, timeout=60) + alice, bob, _eve, chat = c.bootstrap() + res = {} + + # --- F08 ------------------------------------------------------------------------- + bad = '"\\ud800"' + cases = { + "display_name": ("/api/v1/users", None, + '{"username":"u_%s","display_name":%s,"password":"Passw0rd-long-1"}' % (uuid.uuid4().hex[:10], bad)), + "password": ("/api/v1/users", None, + '{"username":"u_%s","display_name":"x","password":%s}' % (uuid.uuid4().hex[:10], '"Passw0rd-long-\\ud800"')), + "chat title": ("/api/v1/chats", alice, '{"title":%s,"member_ids":["%s"]}' % (bad, alice["id"])), + "message text": ("/api/v1/chats/%s/messages" % chat["id"], alice, '{"text":%s}' % bad), + } + f08 = {} + for name, (path, actor, body) in cases.items(): + h = {"Content-Type": "application/json", "Idempotency-Key": uuid.uuid4().hex} + if actor: + h["Authorization"] = "Bearer " + actor["token"] + st, hd, data = raw(args.base_url, "POST", path, body.encode(), h) + code = json.loads(data)["error"]["code"] if data.startswith(b"{") else None + f08[name] = {"status": st, "code": code} + check(st == 400 and code == "invalid_request", "F08 %s: %s %s" % (name, st, code)) + r = c.call("POST", "/api/v1/chats/%s/attachments?filename=%%ED%%A0%%80.png" % chat["id"], 400, actor=alice, + raw=SAMPLE_PNG, headers={"Content-Type": "image/png"}) + f08["filename %ED%A0%80"] = {"status": r["status"]} + res["F08"] = f08 + log.step("F08 lone surrogates -> 400", **f08) + + # --- F17 ------------------------------------------------------------------------- + f17 = {} + for method, path in (("HEAD", "/health/live"), ("OPTIONS", "/api/v1/chats"), ("BREW", "/health/live"), + ("TRACE", "/health/live")): + st, hd, data = raw(args.base_url, method, path) + item = {"status": st, "x_request_id": bool(hd.get("x-request-id")), "x_instance_id": bool(hd.get("x-instance-id")), + "content_type": hd.get("content-type"), "body_bytes": len(data)} + if method != "HEAD": + item["code"] = json.loads(data)["error"]["code"] + item["request_id_matches"] = json.loads(data)["error"]["request_id"] == hd.get("x-request-id") + check(item["request_id_matches"], "F17 request_id") + check(st == 405 and item["x_request_id"] and item["x_instance_id"], "F17 %s: %s" % (method, item)) + check(method != "HEAD" or len(data) == 0, "HEAD must have no body") + f17[method] = item + res["F17"] = f17 + log.step("F17 unsupported methods -> 405 JSON", **f17) + + # --- F05 ------------------------------------------------------------------------- + f05 = {} + import sys + sys.path.insert(0, str(__import__("lab5lib").ROOT / "src")) + import images + w, h = 13, 11 + passes = images._png_passes(w, h, 24, 1) + adam = bytearray(b"".join((b"\x00" + bytes(rb - 1)) * rows for rows, rb in passes)) + adam[sum(rr * bb for rr, bb in passes[:4]) + passes[4][1] * 2] = 9 + samples = {"filter 5 (1x1)": png(1, 1, b"\x05\x01\x02\x03"), + "filter 255 in row 57 (10x100)": png(10, 100, b"".join((b"\xff" if i == 57 else b"\x00") + bytes(30) + for i in range(100))), + "Adam7, filter 9 in pass 5": png(w, h, bytes(adam), interlace=1)} + for name, data in samples.items(): + fname = "badfilter-%s.png" % uuid.uuid4().hex[:8] + r = c.call("POST", "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], fname), 415, actor=alice, + raw=data, headers={"Content-Type": "image/png"}) + rows = int(sql("SELECT count(*) FROM attachments WHERE filename = '%s'" % fname)[0][0]) + check(rows == 0, "F05 row created") + f05[name] = {"status": r["status"], "bytes": len(data), "rows_created": rows} + res["F05"] = f05 + log.step("F05 bad PNG filters -> 415, no job", **f05) + + # --- F09 ------------------------------------------------------------------------- + att = upload(c, alice, chat, SAMPLE_PNG, "integrity.png") + ready = wait_status(c, bob, att["id"], {"ready", "failed"}, 60) + check(ready["status"] == "ready", "F09 not ready") + key = ops("inspect", att["id"])["attachment"]["object_key"] + compose("--profile", "tools", "run", "--rm", "-T", "checks", "/app/student-tests/s3_tamper.py", key) + st, hd, data = raw(args.base_url, "GET", "/api/v1/attachments/%s/content" % att["id"], + headers={"Authorization": "Bearer " + bob["token"]}) + thumb = c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob) + tv = [v for v in ready["variants"] if v["name"] == "thumbnail"][0] + import hashlib + res["F09"] = {"attachment_id": att["id"], "tampered_original_status": st, + "code": json.loads(data)["error"]["code"] if st >= 400 else None, + "untouched_thumbnail_status": thumb["status"], + "thumbnail_sha_ok": hashlib.sha256(thumb["bytes"]).hexdigest() == tv["sha256"]} + check(st == 503 and res["F09"]["thumbnail_sha_ok"], "F09: %s" % res["F09"]) + log.step("F09 corrupted object -> 503, intact variant still 200", **res["F09"]) + + # --- F02 ------------------------------------------------------------------------- + before = api_state() + proc = compose("--profile", "tools", "run", "--rm", "-T", "checks", "/app/student-tests/progressive_upload.py", + "--base-url", "http://lb:8080", "--output", "/app/evidence/progressive-upload.json", ok=False, + timeout=600) + after = api_state() + res["F02"] = {"checks_exit": proc.returncode, "api_before": before, "api_after": after, + "tail": proc.stdout.strip().splitlines()[-1:]} + check(proc.returncode == 0 and before == after and not any(v["oom_killed"] for v in after.values()), + "F02: %s" % res["F02"]) + log.step("F02 concurrent ~40 Mpx progressive JPEG: all ready, API not restarted", **res["F02"]) + log.save(args.output, results=res) + print("PASS: F02, F05, F08, F09, F17 regressions") + + +if __name__ == "__main__": + main() diff --git a/student-tests/s3_tamper.py b/student-tests/s3_tamper.py index 35fb92f9..6ccb7946 100644 --- a/student-tests/s3_tamper.py +++ b/student-tests/s3_tamper.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """Учебная порча staging-объекта (контейнер checks, ключ api): подменяет байты на другие -байты той же длины. Нужна worker_faults.py для проверки постоянной ошибки staging_corrupted. +байты той же длины. Нужна worker_faults.py (staging_corrupted) и api_negative_lab5.py (F09). docker compose --profile tools run --rm checks /app/student-tests/s3_tamper.py staging/ """ @@ -15,13 +15,22 @@ os.environ.setdefault("S3_SECRET_ACCESS_KEY_FILE", "/run/secrets/s3_api_secret_k import objstore # noqa: E402 key = sys.argv[1] -if not re.fullmatch(r"staging/[0-9a-f]{32}", key): - sys.exit("refusing: not a staging key") +# Только учебные ключи: staging и конечные объекты вложений (аудит F09: порча той же длины). +if not re.fullmatch(r"staging/[0-9a-f]{32}|attachments/[0-9a-f-]{36}/v1/[a-z]+(\.[a-z]+)?", key): + sys.exit("refusing: not a staging/attachment key") store = objstore.ObjectStore(objstore.make_client(), os.environ.get("S3_BUCKET", "messenger-attachments")) -resp = store.open(key) -data = resp.read() -resp.close() -resp.release_conn() -bad = bytes(b ^ 0x5A for b in data) -store.put(key, io.BytesIO(bad), len(bad), "application/octet-stream") +import time # noqa: E402 +for attempt in range(1, 6): # запись SeaweedFS после перезапусков иногда «прогревается» секунды + try: + resp = store.open(key) + data = resp.read() + resp.close() + resp.release_conn() + bad = bytes(b ^ 0x5A for b in data) + store.put(key, io.BytesIO(bad), len(bad), "application/octet-stream") + break + except objstore.StorageUnavailable: + if attempt == 5: + raise + time.sleep(2) print("tampered", key, len(bad)) diff --git a/student-tests/slow_client.py b/student-tests/slow_client.py new file mode 100644 index 00000000..a242952c --- /dev/null +++ b/student-tests/slow_client.py @@ -0,0 +1,102 @@ +#!/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()