Лабораторная 4
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
import io
|
||||
import uuid
|
||||
from PIL import Image
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def png_bytes(size=(32, 32), color=(40, 120, 200, 255)):
|
||||
out = io.BytesIO()
|
||||
Image.new("RGBA", size, color).save(out, format="PNG")
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Level-4 attachment negative checks")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
oversize = b"x" * (10 * 1024 * 1024 + 1)
|
||||
c.call(
|
||||
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename=oversize.png",
|
||||
413, actor=alice, raw=oversize,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
c.call(
|
||||
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename=broken.png",
|
||||
415, actor=alice, raw=b"not an image",
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
jpeg = io.BytesIO()
|
||||
Image.new("RGB", (32, 32), (200, 100, 30)).save(jpeg, format="JPEG")
|
||||
c.call(
|
||||
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename=spoof.png",
|
||||
415, actor=alice, raw=jpeg.getvalue(),
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
c.call(
|
||||
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename=bad/name.png",
|
||||
400, actor=alice, raw=png_bytes(),
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
attachment, content = c.attachment(alice, chat)
|
||||
c.call("GET", f"/api/v1/attachments/{attachment['id']}", 404, actor=eve)
|
||||
c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", 404, actor=eve)
|
||||
|
||||
other_chat = c.call(
|
||||
"POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "Второй чат", "member_ids": [alice["id"], eve["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
c.call(
|
||||
"POST", f"/api/v1/chats/{other_chat['id']}/messages",
|
||||
404, actor=alice,
|
||||
body={"text": "", "attachment_ids": [attachment["id"]]},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
print("PASS: oversized, corrupt, MIME-spoof, dangerous filename, foreign attachment and cross-chat checks")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from PIL import Image
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def png_bytes(size=(512, 512)):
|
||||
out = io.BytesIO()
|
||||
Image.new("RGBA", size, (30, 90, 170, 255)).save(out, format="PNG")
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def docker_memory():
|
||||
result = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{json .}}", "mtusi2026lab4-api1-1", "mtusi2026lab4-api2-1"],
|
||||
capture_output=True, text=True, check=False,
|
||||
)
|
||||
rows = []
|
||||
for line in result.stdout.splitlines():
|
||||
try:
|
||||
rows.append(json.loads(line))
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
return rows
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("10 concurrent attachment uploads; Docker memory snapshot")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
payload = png_bytes()
|
||||
before = docker_memory()
|
||||
|
||||
def upload(index):
|
||||
local = Client(args.base_url, args.ca_file, timeout=30)
|
||||
started = time.monotonic()
|
||||
response = local.call(
|
||||
"POST", f"/api/v1/chats/{chat['id']}/attachments?filename=concurrent-{index}.png",
|
||||
201, actor=alice, raw=payload,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)
|
||||
return response["elapsed"], response["json"]["sha256"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
results = list(pool.map(upload, range(10)))
|
||||
time.sleep(1)
|
||||
after = docker_memory()
|
||||
|
||||
latencies = [x[0] for x in results]
|
||||
report = {
|
||||
"concurrency": 10,
|
||||
"payload_bytes": len(payload),
|
||||
"successful_uploads": len(results),
|
||||
"latency_seconds": {
|
||||
"min": round(min(latencies), 3),
|
||||
"max": round(max(latencies), 3),
|
||||
"avg": round(sum(latencies) / len(latencies), 3),
|
||||
},
|
||||
"docker_stats_before": before,
|
||||
"docker_stats_after": after,
|
||||
}
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
Path = __import__("pathlib").Path
|
||||
evidence = Path(__file__).resolve().parents[1] / "evidence" / "attachment-load.json"
|
||||
evidence.parent.mkdir(parents=True, exist_ok=True)
|
||||
evidence.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
check(len(results) == 10, "not all concurrent uploads succeeded")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
+1
-1
@@ -14,7 +14,7 @@ import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LAB = json.loads((ROOT / 'lab.json').read_text())['number']
|
||||
SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text())
|
||||
SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text(encoding='utf-8'))
|
||||
|
||||
class Failure(AssertionError):
|
||||
pass
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import subprocess
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from client import Client, arguments, run
|
||||
|
||||
|
||||
def compose(*args):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=Path(__file__).resolve().parents[1],
|
||||
capture_output=True, text=True, check=True,
|
||||
)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def reconcile(apply=False, grace="24"):
|
||||
command = ["exec", "-T", "api1", "python", "/app/reconcile.py", "--grace-hours", grace]
|
||||
if apply:
|
||||
command.append("--apply")
|
||||
return compose(*command)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Track 2 reconciler fault-injection proof")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
attachment, content = c.attachment(alice, chat)
|
||||
|
||||
orphan_key = f"reconcile-fault/orphan-{uuid.uuid4()}"
|
||||
compose("exec", "-T", "api1", "python", "-c",
|
||||
"import boto3,os;"
|
||||
f"c=boto3.client('s3',endpoint_url=os.environ['S3_ENDPOINT'],aws_access_key_id=os.environ['S3_ACCESS_KEY_ID'],aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY'],region_name='us-east-1');"
|
||||
f"c.put_object(Bucket=os.environ['S3_BUCKET'],Key='{orphan_key}',Body=b'orphan')")
|
||||
|
||||
compose(
|
||||
"exec", "-T", "api1", "python", "-c",
|
||||
"import boto3,os,psycopg;"
|
||||
f"con=psycopg.connect(os.environ['DATABASE_URL']);"
|
||||
f"cur=con.execute('SELECT object_key FROM attachments WHERE id=%s',('{attachment['id']}',));"
|
||||
"key=cur.fetchone()[0];"
|
||||
"c=boto3.client('s3',endpoint_url=os.environ['S3_ENDPOINT'],"
|
||||
"aws_access_key_id=os.environ['S3_ACCESS_KEY_ID'],"
|
||||
"aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY'],region_name='us-east-1');"
|
||||
"c.delete_object(Bucket=os.environ['S3_BUCKET'],Key=key)",
|
||||
)
|
||||
|
||||
before = reconcile(False, "24")
|
||||
report = {
|
||||
"scenario": "missing metadata object and orphan object",
|
||||
"dry_run_before_apply": before.strip(),
|
||||
"apply_grace_hours": 0,
|
||||
}
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
|
||||
apply_fresh = reconcile(True, "0")
|
||||
print(apply_fresh.strip())
|
||||
second = reconcile(True, "0")
|
||||
print(second.strip())
|
||||
report["apply_output"] = apply_fresh.strip()
|
||||
report["repeat_output"] = second.strip()
|
||||
evidence = Path(__file__).resolve().parents[1] / "evidence" / "reconciler-track2.json"
|
||||
evidence.parent.mkdir(parents=True, exist_ok=True)
|
||||
evidence.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user