#!/usr/bin/env python3 """Доказательства уровня 3 по вложениям (стенд уже запущен; только стандартная библиотека). 1. Загрузка через LB -> запоминаем X-Instance-Id обслужившей реплики -> останавливаем именно её (scripts/stop-one.*) -> второй участник скачивает файл через LB: отвечает другая реплика, SHA-256 тот же. 2. Посторонний получает 404 на метаданные и на байты. 3. Прямой анонимный GET объекта и листинг bucket в MinIO (минуя API) отклоняются. 4. У API-контейнеров нет volume: единственные монтирования — Docker secrets. В конце остановленная реплика возвращается (docker compose up --no-recreate). Токены не печатаются. python scripts/attachment_checks.py --base-url http://localhost:8080 --s3-url http://127.0.0.1:9000 """ import argparse import base64 import hashlib import json import os import subprocess import sys import time import urllib.error import urllib.request import uuid from pathlib import Path ROOT = Path(__file__).resolve().parents[1] FIXTURE = ROOT / "tests" / "fixtures" / "sample.png" PROJECT = "mtusi-lab4" def request(method, url, body=None, headers=None, timeout=15): req = urllib.request.Request(url, data=body, method=method, headers=headers or {}) try: with urllib.request.urlopen(req, timeout=timeout) as resp: return resp.status, resp.headers, resp.read() except urllib.error.HTTPError as exc: return exc.code, exc.headers, exc.read() def api_json(base, method, path, token=None, payload=None, headers=None, expect=200): all_headers = dict(headers or {}) body = None if payload is not None: body = json.dumps(payload).encode() all_headers["Content-Type"] = "application/json" if token: all_headers["Authorization"] = "Bearer " + token status, resp_headers, data = request(method, base + path, body, all_headers) if status != expect: raise SystemExit(f"{method} {path}: ожидали {expect}, получили {status}") return resp_headers, json.loads(data) if data else None def new_user(base, name): username = f"{name}_{uuid.uuid4().hex[:10]}" password = "attachment-check-" + uuid.uuid4().hex[:8] _, user = api_json(base, "POST", "/api/v1/users", expect=201, payload={"username": username, "display_name": name, "password": password}) basic = base64.b64encode(f"{username}:{password}".encode()).decode() _, session = api_json(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic}, expect=201) return user["id"], session["token"] def stop_replica(instance_id): script = ROOT / "scripts" / ("stop-one.cmd" if os.name == "nt" else "stop-one.sh") env = dict(os.environ, TARGET_INSTANCE_ID=instance_id) subprocess.run([str(script)], check=True, env=env, cwd=ROOT, stdout=subprocess.DEVNULL) def api_mounts(): ids = subprocess.run(["docker", "ps", "-q", "--filter", f"label=com.docker.compose.project={PROJECT}", "--filter", "label=com.docker.compose.service=api"], check=True, capture_output=True, text=True).stdout.split() result = {} for cid in ids: out = subprocess.run(["docker", "inspect", cid, "--format", "{{json .Mounts}}"], check=True, capture_output=True, text=True).stdout result[cid] = [{"type": m["Type"], "destination": m["Destination"]} for m in json.loads(out)] return result def main(): parser = argparse.ArgumentParser() parser.add_argument("--base-url", default="http://localhost:8080") parser.add_argument("--s3-url", default="http://127.0.0.1:9000") parser.add_argument("--bucket", default="messenger-attachments") parser.add_argument("--output", default=str(ROOT / "evidence" / "attachment-checks.json")) args = parser.parse_args() base = args.base_url.rstrip("/") content = FIXTURE.read_bytes() expected_sha = hashlib.sha256(content).hexdigest() report = {"fixture_bytes": len(content), "fixture_sha256": expected_sha} alice_id, alice = new_user(base, "alice") bob_id, bob = new_user(base, "bob") _, eve = new_user(base, "eve") _, chat = api_json(base, "POST", "/api/v1/chats", alice, {"title": "attachments", "member_ids": [alice_id, bob_id]}, expect=201) # 1. Загрузка и остановка обслужившей реплики. status, headers, data = request( "POST", f"{base}/api/v1/chats/{chat['id']}/attachments?filename=sample.png", content, {"Authorization": "Bearer " + alice, "Content-Type": "image/png"}) if status != 201: raise SystemExit(f"upload: {status}") attachment = json.loads(data) uploaded_by = headers.get("X-Instance-Id") report["upload"] = {"status": status, "instance": uploaded_by, "sha256_matches": attachment["sha256"] == expected_sha} api_json(base, "POST", f"/api/v1/chats/{chat['id']}/messages", alice, {"text": "", "attachment_ids": [attachment["id"]]}, {"Idempotency-Key": uuid.uuid4().hex}, expect=201) stop_replica(uploaded_by) stopped_at = time.monotonic() download = None while time.monotonic() - stopped_at < 15: status, headers, data = request("GET", f"{base}/api/v1/attachments/{attachment['id']}/content", headers={"Authorization": "Bearer " + bob}) if status == 200 and headers.get("X-Instance-Id") != uploaded_by: download = {"status": status, "instance": headers.get("X-Instance-Id"), "sha256": hashlib.sha256(data).hexdigest(), "content_type": headers.get("Content-Type"), "seconds_after_stop": round(time.monotonic() - stopped_at, 2)} break time.sleep(0.5) if download is None: raise SystemExit("файл не скачался через другую реплику за 15 с") download["different_instance"] = download["instance"] != uploaded_by download["sha256_matches"] = download["sha256"] == expected_sha report["download_after_stop"] = download # 2. Посторонний. report["outsider"] = { "metadata_status": request("GET", f"{base}/api/v1/attachments/{attachment['id']}", headers={"Authorization": "Bearer " + eve})[0], "content_status": request("GET", f"{base}/api/v1/attachments/{attachment['id']}/content", headers={"Authorization": "Bearer " + eve})[0], } # 3. Прямой доступ к MinIO без credentials. Ключ объекта знает только сервер; здесь — по его схеме. s3 = args.s3_url.rstrip("/") report["direct_s3_anonymous"] = { "get_object_status": request("GET", f"{s3}/{args.bucket}/originals/{attachment['id']}")[0], "list_bucket_status": request("GET", f"{s3}/{args.bucket}?list-type=2")[0], } # 4. Монтирования API-контейнеров (оставшаяся реплика). report["api_mounts"] = api_mounts() # Вернуть остановленную реплику. subprocess.run(["docker", "compose", "up", "-d", "--no-recreate", "--wait", "api", "lb"], check=True, cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) checks = [ report["upload"]["sha256_matches"], download["different_instance"] and download["sha256_matches"] and download["content_type"] == "image/png", report["outsider"] == {"metadata_status": 404, "content_status": 404}, report["direct_s3_anonymous"]["get_object_status"] == 403 and report["direct_s3_anonymous"]["list_bucket_status"] == 403, all(m["destination"].startswith("/run/secrets/") for mounts in report["api_mounts"].values() for m in mounts), ] report["result"] = "PASS" if all(checks) else "FAIL" Path(args.output).write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(json.dumps(report, ensure_ascii=False, indent=2)) return 0 if all(checks) else 1 if __name__ == "__main__": sys.exit(main())