ЛР 7 — БПИ2303 — Лазарев — на 3
Перенесена реализация lab6; бизнес-API без изменений, транспорт — HTTPS. - Внешний HTTPS (public-ca) на 127.0.0.1:8443; HSTS, TLS >= 1.2. - Обязательное mTLS LB -> каждая API-реплика: API проверяет цепочку internal-ca и SAN клиента (allowlist: lb); health только на 127.0.0.1. - TLS с проверкой сервера ко всем зависимостям: PostgreSQL verify-full (pg_hba только hostssl), HTTPS S3, AMQPS, OTLP/HTTPS с client cert, mTLS Collector -> Prometheus/Loki/Tempo, Grafana -> datasources, scrape. - OpenBao 2.7.2 не в dev-mode: Raft на volume, init/unseal оператором, auth/cert с ролью и policy на сервис, TTL 15 мин + renew/re-login. - Отдельные роли PostgreSQL с грантами по таблицам; разные ключи S3 и пользователи брокера выдаются из OpenBao. - Argon2id (m=19 MiB, t=2, p=1, замер на стенде) и rehash при входе. - Случайный X-Instance-Id; hardening контейнеров (non-root, cap_drop ALL, no-new-privileges, read-only, лимиты); TCP_NODELAY на сокете API. - Модель угроз, trust matrix, отрицательные тесты TLS/mTLS, API, OpenBao, hardening; evidence, в т.ч. прогон из чистого clone.
This commit is contained in:
@@ -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()
|
||||
Reference in New Issue
Block a user