Files
mtusi2026lab7/student-tests/transform_limits.py
T
zemiles 9cc80d2529 ЛР 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.
2026-11-18 23:59:35 +03:00

102 lines
4.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Лимиты worker на «плохие» входы: пиксели, память, CPU-время, повреждённые данные.
Запускает src/transform.py так же, как worker (подпроцесс), В КОНТЕЙНЕРЕ checks:
docker compose --profile tools run --rm checks /app/student-tests/transform_limits.py \
--output /app/evidence/transform-limits.json
API отсекает > 10 MiB и > 40 Мпикс ещё до очереди (lab4); здесь проверяется вторая линия
обороны — сам worker, если в staging всё же оказался такой файл.
"""
import argparse
import io
import json
import os
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from PIL import Image
TRANSFORM = "/app/src/transform.py"
EXPECT = {0: "ok", 3: "invalid_image", 4: "image_too_large", 5: "resource_limit"}
def run(data, ctype, env=None, max_pixels=40000000, timeout=60):
"""Как worker: подпроцесс; timeout — wall-clock (у worker JOB_TIMEOUT_SECONDS)."""
with tempfile.TemporaryDirectory() as d:
src = os.path.join(d, "in")
Path(src).write_bytes(data)
out = os.path.join(d, "out")
os.mkdir(out)
e = dict(os.environ, **(env or {}))
t = time.monotonic()
try:
p = subprocess.run([sys.executable, TRANSFORM, src, out, ctype, str(max_pixels)], capture_output=True,
env=e, timeout=timeout)
rc = p.returncode
except subprocess.TimeoutExpired:
rc = "timeout"
dur = round(time.monotonic() - t, 2)
if rc == "timeout":
return {"exit": rc, "class": "processing_timeout", "seconds": round(time.monotonic() - t, 2)}
cls = EXPECT.get(rc, "killed_by_signal_%d" % -rc if isinstance(rc, int) and rc < 0 else str(rc))
return {"exit": rc, "class": cls, "seconds": dur}
def png(size, mode="RGB", color=(10, 20, 30)):
buf = io.BytesIO()
Image.new(mode, size, color).save(buf, "PNG")
return buf.getvalue()
def main():
p = argparse.ArgumentParser()
p.add_argument("--output")
args = p.parse_args()
ok = png((640, 480))
big = png((6000, 6000)) # 36 Мпикс: допустимо, ~108 MiB в RGB
# Несжимаемый RGBA-шум ~40 Мпикс: декодирование, alpha-композиция и resize — секунды CPU.
buf = io.BytesIO()
n = Image.effect_noise((6300, 6300), 80)
Image.merge("RGBA", [n, n.transpose(Image.Transpose.ROTATE_90), n, n]).save(buf, "PNG", compress_level=1)
heavy = buf.getvalue()
# Аудит F02: progressive 4:4:4 ~40 Мпикс — допустимый вход, ~250 MiB на декодирование.
g = Image.radial_gradient("L").resize((6324, 6324))
buf = io.BytesIO()
Image.merge("RGB", (g, g.rotate(90), g)).save(buf, "JPEG", quality=85, progressive=True, subsampling=0)
prog = buf.getvalue()
cases = [
("valid 640x480", ok, "image/png", {}, 40000000, "ok"),
("40 Mpx progressive 4:4:4 JPEG, default limits", prog, "image/jpeg", {}, 40000000, "ok"),
("49 Mpx PNG (> MAX_IMAGE_PIXELS)", png((7000, 7000)), "image/png", {}, 40000000, "image_too_large"),
("36 Mpx PNG, normal limits", big, "image/png", {}, 40000000, "ok"),
("36 Mpx PNG, memory limit 160 MiB", big, "image/png", {"TRANSFORM_MEMORY_LIMIT_MB": "160"}, 40000000,
"resource_limit"),
("40 Mpx RGBA noise PNG, CPU limit 1 s", heavy, "image/png", {"TRANSFORM_CPU_SECONDS": "1"}, 40000000,
"killed_by_signal_24"),
("40 Mpx RGBA noise PNG, wall timeout 0.5 s", heavy, "image/png", {}, 40000000, "processing_timeout"),
("truncated PNG", ok[: len(ok) // 2], "image/png", {}, 40000000, "invalid_image"),
("garbage declared as JPEG", b"\xff\xd8\xff" + os.urandom(5000), "image/jpeg", {}, 40000000, "invalid_image"),
("PNG declared as JPEG", ok, "image/jpeg", {}, 40000000, "invalid_image"),
]
results = []
failed = 0
for name, data, ctype, env, mp, want in cases:
r = run(data, ctype, env, mp, timeout=0.5 if want == "processing_timeout" else 60)
r.update(case=name, expected=want, input_bytes=len(data), env=env)
r["pass"] = r["class"] == want or (want.startswith("killed") and r["class"] in ("resource_limit", want))
failed += not r["pass"]
results.append(r)
print("%s %-36s -> %s (%.2fs)" % ("PASS" if r["pass"] else "FAIL", name, r["class"], r["seconds"]), flush=True)
if args.output:
Path(args.output).write_text(json.dumps({"cases": results}, ensure_ascii=False, indent=1) + "\n")
print("PASS" if not failed else "FAIL", "%d/%d" % (len(cases) - failed, len(cases)))
sys.exit(1 if failed else 0)
if __name__ == "__main__":
main()