выполнение лабораторной на 5

This commit is contained in:
kaktuz20000
2026-10-26 17:55:33 +03:00
parent ec540a1a72
commit bd0b9f6849
34 changed files with 2818 additions and 49 deletions
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Negative attachment and cross-chat authorization checks against a running lab4 API."""
import uuid
from pathlib import Path
import sys
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run
def upload(client, actor, chat_id, data, content_type="image/png", filename="test.png", expected=201):
return client.call(
"POST",
"/api/v1/chats/" + chat_id + "/attachments?filename=" + quote(filename, safe=""),
expected,
actor=actor,
raw=data,
headers={"Content-Type": content_type},
schema="Attachment" if expected == 201 else None,
)
def main():
args = arguments("Attachment upload, size, MIME, and chat authorization checks")
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
other_chat = client.call(
"POST",
"/api/v1/chats",
201,
actor=alice,
body={"title": "Second test chat", "member_ids": [alice["id"], eve["id"]]},
schema="Chat",
)["json"]
image = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
print("Checking accepted fixture upload.", flush=True)
attachment = upload(client, alice, chat["id"], image)["json"]
print("Checking damaged and spoofed image rejection.", flush=True)
upload(client, alice, chat["id"], b"not an image", expected=415)
upload(client, alice, chat["id"], image, content_type="image/jpeg", expected=415)
print("Checking byte and pixel limits.", flush=True)
upload(client, alice, chat["id"], b"x" * (10 * 1024 * 1024 + 1), expected=413)
import struct
import zlib
def chunk(kind, payload):
return (
struct.pack(">I", len(payload))
+ kind
+ payload
+ struct.pack(">I", zlib.crc32(kind + payload) & 0xFFFFFFFF)
)
too_many_pixels = (
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", 10001, 4000, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(b""))
+ chunk(b"IEND", b"")
)
upload(client, alice, chat["id"], too_many_pixels, expected=413)
print("Checking filename and cross-chat authorization.", flush=True)
upload(client, alice, chat["id"], image, filename="../unsafe.png", expected=400)
upload(client, eve, chat["id"], image, expected=404)
client.call("GET", "/api/v1/attachments/" + attachment["id"], 404, actor=eve)
client.call(
"POST",
"/api/v1/chats/" + other_chat["id"] + "/messages",
404,
actor=alice,
headers={"Idempotency-Key": uuid.uuid4().hex},
body={"text": "", "attachment_ids": [attachment["id"]]},
)
client.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
400,
actor=bob,
headers={"Idempotency-Key": uuid.uuid4().hex},
body={"text": ""},
)
print("PASS: oversized, damaged, spoofed, unsafe-name, outsider, and cross-chat cases")
if __name__ == "__main__":
run(main)
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Prove a concurrent idempotency-key race through the load balancer."""
from concurrent.futures import ThreadPoolExecutor
import threading
import sys
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run
def main():
args = arguments("Concurrent shared-idempotency integration check")
client = Client(args.base_url, args.ca_file)
alice, _, _, chat = client.bootstrap()
key = "race-" + uuid.uuid4().hex
text = "concurrent-" + uuid.uuid4().hex
count = 12
barrier = threading.Barrier(count)
def send_once(_):
worker = Client(args.base_url, args.ca_file)
barrier.wait(timeout=10)
return worker.message(alice, chat, text, key=key)
with ThreadPoolExecutor(max_workers=count) as pool:
responses = list(pool.map(send_once, range(count)))
instance_ids = {response["headers"]["X-Instance-Id"] for response in responses}
messages = [response["json"] for response in responses]
check(len(instance_ids) >= 2, "concurrent requests did not reach multiple API replicas")
check(all(message == messages[0] for message in messages), "same-key requests returned different messages")
page = client.call(
"GET",
"/api/v1/chats/" + chat["id"] + "/messages?limit=100",
actor=alice,
schema="MessagePage",
)["json"]
matches = [message for message in page["items"] if message["text"] == text]
check(len(matches) == 1 and matches[0] == messages[0], "concurrent retry persisted duplicate messages")
print(f"PASS: {count} concurrent same-key requests on {len(instance_ids)} replicas returned one message")
if __name__ == "__main__":
run(main)
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
"""Deterministic tests of the reconciliation decision rules without deleting real objects."""
import os
import hashlib
import sys
import tempfile
from pathlib import Path
os.environ.setdefault("S3_ACCESS_KEY_ID", "test-reconciler")
os.environ.setdefault("S3_SECRET_ACCESS_KEY", "test-only-not-a-real-secret")
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from datetime import datetime, timedelta, timezone
from src.reconcile import reconcile
class FakeObjects:
def __init__(self, items):
self.items = items
self.deleted = []
def objects(self):
return iter(self.items)
def delete(self, key):
self.deleted.append(key)
self.items = [(name, date) for name, date in self.items if name != key]
def put(self, key, content, content_type):
self.items.append((key, datetime.now(timezone.utc)))
class FakeStore:
def __init__(self):
now = datetime.now(timezone.utc)
self.metadata = {
"original/present": {"id": "present-id", "object_key": "original/present"},
"original/missing": {
"id": "missing-id",
"object_key": "original/missing",
"size_bytes": 4,
"sha256": hashlib.sha256(b"test").hexdigest(),
"content_type": "image/png",
},
}
self.objects = FakeObjects(
[
("original/present", now),
("original/stale-orphan", now - timedelta(hours=2)),
("original/new-orphan", now - timedelta(minutes=10)),
]
)
self.missing_incidents = set()
self.cleared_incidents = set()
def reconciliation_snapshot(self):
return self.metadata
def record_missing_object(self, attachment_id):
self.missing_incidents.add(attachment_id)
def clear_missing_object(self, attachment_id):
self.missing_incidents.discard(attachment_id)
self.cleared_incidents.add(attachment_id)
def main():
store = FakeStore()
dry_run = reconcile(store, grace_seconds=3600, apply_changes=False)
assert dry_run["stale_orphan_candidates"] == 1
assert dry_run["missing_objects"] == 1
assert dry_run["deleted_orphans"] == 0
assert store.objects.deleted == [] and store.missing_incidents == set()
applied = reconcile(store, grace_seconds=3600, apply_changes=True)
assert store.objects.deleted == ["original/stale-orphan"]
assert "original/new-orphan" not in store.objects.deleted
assert store.missing_incidents == {"missing-id"}
assert store.cleared_incidents == {"present-id"}
assert applied["deleted_orphans"] == 1 and applied["missing_objects"] == 1
with tempfile.TemporaryDirectory() as backup:
restore_dir = Path(backup)
(restore_dir / "missing-id").write_bytes(b"test")
preview = reconcile(store, 3600, False, restore_dir)
assert preview["restorable_missing_objects"] == 1
assert store.missing_incidents == {"missing-id"}
restored = reconcile(store, 3600, True, restore_dir)
assert restored["restored_missing_objects"] == 1
assert store.missing_incidents == set()
repeated = reconcile(store, grace_seconds=3600, apply_changes=True)
assert repeated["stale_orphan_candidates"] == 0 and repeated["missing_objects"] == 0
assert store.objects.deleted == ["original/stale-orphan"]
assert store.missing_incidents == set()
print("PASS: dry-run is read-only; stale orphan cleanup is idempotent and respects grace period")
if __name__ == "__main__":
main()
+187
View File
@@ -0,0 +1,187 @@
#!/usr/bin/env python3
"""Exercise real S3/PostgreSQL reconciliation using disposable synthetic objects."""
import json
import subprocess
import sys
import time
import uuid
from pathlib import Path
import tempfile
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run
STORE_CODE = """
import sys
from pathlib import Path
from src.store import Store
store = Store()
store.open()
try:
action = sys.argv[1]
if action == "key":
attachment_id = sys.argv[2]
matches = [
key for key, row in store.reconciliation_snapshot().items()
if str(row["id"]) == attachment_id
]
if len(matches) != 1:
raise RuntimeError("attachment metadata lookup failed")
print(matches[0])
elif action == "put":
key, file_path = sys.argv[2:4]
content = Path(file_path).read_bytes()
store.objects.put(key, content, "image/png", len(content))
elif action == "delete":
store.objects.delete(sys.argv[2])
else:
raise RuntimeError("unsupported test operation")
finally:
store.close()
"""
PRIVATE_CHECK_CODE = """
import sys
import urllib.error
import urllib.request
try:
urllib.request.urlopen("http://s3:8333/messenger-attachments/", timeout=3)
except urllib.error.HTTPError as error:
if error.code == 403:
print("PASS: unauthenticated bucket access denied")
else:
raise RuntimeError("unexpected anonymous S3 status: " + str(error.code))
else:
raise RuntimeError("private bucket allowed an unauthenticated GET")
"""
def docker_exec(container_id, *args):
return subprocess.run(
["docker", "exec", container_id, *args],
cwd=ROOT,
check=True,
capture_output=True,
text=True,
)
def reconciliation(container_id, *args):
result = docker_exec(container_id, "python3", "src/reconcile.py", "--grace-seconds", "60", *args)
return json.loads(result.stdout)
def main():
args = arguments("Real PostgreSQL/SeaweedFS reconciliation and private-bucket experiment")
client = Client(args.base_url, args.ca_file)
alice, bob, _, chat = client.bootstrap()
attachment, content = client.attachment(alice, chat)
message = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
result = subprocess.run(
["docker", "compose", "ps", "--quiet", "--status", "running", "api"],
cwd=ROOT,
check=True,
capture_output=True,
text=True,
)
containers = result.stdout.split()
check(len(containers) >= 2, "at least two running API replicas are required")
container_id = containers[0]
key = docker_exec(
container_id, "python3", "-c", STORE_CODE, "key", attachment["id"]
).stdout.strip()
orphan_key = "original/" + str(uuid.uuid4())
with tempfile.TemporaryDirectory() as backup:
source = Path(backup) / "original.png"
source.write_bytes(content)
container_file = "/tmp/lab4-orphan-" + uuid.uuid4().hex + ".png"
recovery_dir = "/tmp/lab4-recovery-" + uuid.uuid4().hex
recovery_file = recovery_dir + "/" + attachment["id"]
orphan_created = False
orphan_removed = False
missing_deleted = False
missing_restored = False
try:
subprocess.run(["docker", "cp", str(source), container_id + ":" + container_file], check=True)
docker_exec(container_id, "python3", "-c", STORE_CODE, "put", orphan_key, container_file)
orphan_created = True
docker_exec(container_id, "python3", "-c", STORE_CODE, "delete", key)
missing_deleted = True
preview = reconciliation(container_id)
check(
preview["orphan_objects"] >= 1 and preview["missing_objects"] == 1,
"dry-run missed injected inconsistencies",
)
check(preview["deleted_orphans"] == 0, "dry-run modified S3")
immediate_apply = reconciliation(container_id, "--apply")
check(immediate_apply["stale_orphan_candidates"] == 0, "fresh orphan bypassed grace period")
check(immediate_apply["deleted_orphans"] == 0, "fresh orphan was deleted")
docker_exec(container_id, "mkdir", "-p", recovery_dir)
subprocess.run(
["docker", "cp", str(source), container_id + ":" + recovery_file],
check=True,
)
restore_preview = reconciliation(container_id, "--restore-dir", recovery_dir)
check(restore_preview["restorable_missing_objects"] == 1, "exact backup was not identified as restorable")
restored = reconciliation(container_id, "--apply", "--restore-dir", recovery_dir)
check(restored["restored_missing_objects"] == 1, "missing S3 object was not restored")
missing_restored = True
repeated = reconciliation(container_id, "--apply", "--restore-dir", recovery_dir)
check(repeated["missing_objects"] == 0, "repeat reconciliation still reports missing object")
check(repeated["stale_orphan_candidates"] == 0, "recent orphan did not respect grace period")
print("Waiting for the 60-second orphan grace period.")
time.sleep(61)
cleanup_preview = reconciliation(container_id)
check(cleanup_preview["stale_orphan_candidates"] == 1, "stale orphan was not identified after grace")
cleaned = reconciliation(container_id, "--apply")
check(cleaned["deleted_orphans"] == 1, "stale orphan was not removed")
orphan_removed = True
final_scan = reconciliation(container_id, "--apply")
check(
final_scan["orphan_objects"] == 0 and final_scan["missing_objects"] == 0,
"repeat scan is not clean",
)
finally:
if missing_deleted and not missing_restored:
docker_exec(container_id, "python3", "-c", STORE_CODE, "put", key, container_file)
if orphan_created and not orphan_removed:
docker_exec(container_id, "python3", "-c", STORE_CODE, "delete", orphan_key)
private = docker_exec(container_id, "python3", "-c", PRIVATE_CHECK_CODE).stdout.strip()
check("PASS:" in private, "unauthenticated S3 access check failed")
downloaded = client.call(
"GET",
"/api/v1/attachments/" + attachment["id"] + "/content",
actor=bob,
)["bytes"]
check(downloaded == content, "reconciler changed the original of an attachment used by a message")
check(message["attachment_ids"] == [attachment["id"]], "test message did not retain the attachment reference")
print(
json.dumps(
{
"result": "PASS",
"dataset_objects_scanned": final_scan["objects_seen"],
"metadata_records_scanned": final_scan["metadata_seen"],
"scan_duration_ms": final_scan["duration_ms"],
"orphan_detected_and_removed": cleaned["deleted_orphans"],
"missing_detected_and_restored": restored["restored_missing_objects"],
"fresh_orphan_preserved_until_grace": True,
"message_attachment_download_checksum": "unchanged",
"private_bucket": "anonymous request denied",
},
sort_keys=True,
)
)
if __name__ == "__main__":
run(main)
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Run ten simultaneous near-6-MiB uploads and sample API container memory."""
from concurrent.futures import ThreadPoolExecutor
import json
import os
import re
import subprocess
import threading
import time
import subprocess
import uuid
from io import BytesIO
from pathlib import Path
import sys
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, arguments, check, run
UNIT = {"B": 1, "KiB": 1024, "MiB": 1024**2, "GiB": 1024**3}
USAGE_RE = re.compile(r"([\d.]+)(B|KiB|MiB|GiB)\s*/")
def usage_bytes(line):
match = USAGE_RE.search(line)
return int(float(match.group(1)) * UNIT[match.group(2)]) if match else 0
def api_containers():
result = subprocess.run(
["docker", "compose", "ps", "--quiet", "--status", "running", "api"],
cwd=ROOT,
check=True,
capture_output=True,
text=True,
)
ids = result.stdout.split()
check(len(ids) >= 2, "at least two running API containers are required")
return ids
def sample_once(ids):
output = subprocess.run(
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", *ids],
check=True,
capture_output=True,
text=True,
).stdout.splitlines()
values = [usage_bytes(line) for line in output]
check(len(values) == len(ids) and all(values), "could not parse docker stats memory usage")
return max(values)
def main():
args = arguments("Bounded-memory ten-client upload experiment")
client = Client(args.base_url, args.ca_file)
alice, _, _, chat = client.bootstrap()
width = height = 1400
content = BytesIO()
Image.frombytes("RGB", (width, height), os.urandom(width * height * 3)).save(
content, format="PNG", compress_level=0
)
payload = content.getvalue()
check(0 < len(payload) <= 10 * 1024 * 1024, "synthetic PNG is outside the upload size limit")
ids = api_containers()
baseline = sample_once(ids)
samples = []
stats_process = subprocess.Popen(
["docker", "stats", "--format", "{{.MemUsage}}", *ids],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
)
def sampler():
if stats_process.stdout is None:
return
for line in stats_process.stdout:
value = usage_bytes(line)
if value:
samples.append(value)
sampling_thread = threading.Thread(target=sampler, daemon=True)
sampling_thread.start()
count = 10
barrier = threading.Barrier(count)
def upload(index):
worker = Client(args.base_url, args.ca_file)
barrier.wait(timeout=15)
return worker.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/attachments?filename=load-" + str(index) + ".png",
201,
actor=alice,
raw=payload,
headers={"Content-Type": "image/png"},
schema="Attachment",
)
started = time.monotonic()
try:
with ThreadPoolExecutor(max_workers=count) as pool:
responses = list(pool.map(upload, range(count)))
finally:
stopped_by_test = False
if stats_process.poll() is None:
stats_process.kill()
stopped_by_test = True
try:
stats_process.wait(timeout=5)
except subprocess.TimeoutExpired:
stats_process.kill()
stats_process.wait(timeout=5)
sampling_thread.join(timeout=5)
stats_error = stats_process.stderr.read() if stats_process.stderr is not None else ""
check(
stats_process.returncode == 0 or (stopped_by_test and stats_process.returncode == -9),
"docker stats sampling process failed (exit "
+ str(stats_process.returncode)
+ "): "
+ stats_error.strip()[:300],
)
check(bool(samples), "docker stats produced no memory samples")
peak = max([baseline] + samples)
check(len(responses) == count and all(response["status"] == 201 for response in responses), "an upload failed")
print(
json.dumps(
{
"uploads": count,
"concurrency": count,
"bytes_per_upload": len(payload),
"duration_seconds": round(time.monotonic() - started, 3),
"api_containers": len(ids),
"sample_count": len(samples) // len(ids),
"baseline_max_container_bytes": baseline,
"peak_max_container_bytes": peak,
"peak_delta_bytes": max(0, peak - baseline),
"sampling_method": "continuous docker stats stream; Docker/CLI sampling cadence",
"memory_scope": "Docker-reported API container working set; LB, DB, S3, and host cache excluded",
},
sort_keys=True,
)
)
if __name__ == "__main__":
run(main)