feat(lab4): implement S3 attachments and image validation
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
"""Extra grade-4 black-box negative cases. Run from project root after smoke."""
|
||||
import hashlib
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check, arguments, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Grade-4 negative attachment tests")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, outsider, chat = c.bootstrap()
|
||||
other = c.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "Other", "member_ids": [alice['id']]}, schema="Chat")['json']
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments?filename=photo.png"
|
||||
content = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
def raw(path, data, expect, actor=alice, mime="image/png"):
|
||||
return c.call("POST", path, expect, actor=actor, raw=data, headers={"Content-Type": mime})
|
||||
# Size, corrupt image, advertised MIME mismatch, invalid filename, and ACL before upload.
|
||||
raw(path, b"a" * (10485760 + 1), 413)
|
||||
raw(path, b"this is not png", 415)
|
||||
raw(path, content[:50], 415)
|
||||
raw(path, content, 415, mime="image/jpeg")
|
||||
raw(f"/api/v1/chats/{chat['id']}/attachments?filename={quote('../bad.png', safe='')}", content, 400)
|
||||
raw(path, content, 404, actor=outsider)
|
||||
att = raw(path, content, 201)
|
||||
import json
|
||||
data = json.loads(att['bytes'])
|
||||
check(data['sha256'] == hashlib.sha256(content).hexdigest(), 'SHA mismatch')
|
||||
aid = data['id']
|
||||
for suffix in ('', '/content'):
|
||||
c.call('GET', f'/api/v1/attachments/{aid}{suffix}', 404, actor=outsider)
|
||||
c.call('GET', f'/api/v1/attachments/{uuid.uuid4()}{suffix}', 404, actor=alice)
|
||||
c.message(alice, other, 'other chat', attachments=[], key=uuid.uuid4().hex)
|
||||
c.call('POST', f"/api/v1/chats/{other['id']}/messages", 404, actor=alice,
|
||||
headers={'Idempotency-Key':uuid.uuid4().hex}, body={'text':'', 'attachment_ids':[aid]})
|
||||
same = c.message(alice, chat, '', attachments=[aid], key=uuid.uuid4().hex)['json']
|
||||
check(same['attachment_ids'] == [aid], 'attachment link missing')
|
||||
fetched = c.call('GET', f'/api/v1/attachments/{aid}/content', actor=bob)
|
||||
check(fetched['bytes'] == content, 'download differs from upload')
|
||||
print('PASS: grade-4 negative upload/ACL/cross-chat cases')
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Run inside API container. Direct unsigned S3 download must be denied."""
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from src.db import pool
|
||||
from src.storage import bucket
|
||||
|
||||
|
||||
def main():
|
||||
pool.open(wait=True, timeout=10)
|
||||
try:
|
||||
with pool.connection() as conn:
|
||||
row = conn.execute("SELECT object_key FROM attachments ORDER BY created_at DESC LIMIT 1").fetchone()
|
||||
if row is None:
|
||||
raise SystemExit("Upload a test image first")
|
||||
url = f"http://s3:8333/{bucket}/{row['object_key']}"
|
||||
req = urllib.request.Request(url)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=3) as response:
|
||||
raise SystemExit(f"FAIL: anonymous S3 GET returned {response.status}")
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code != 403:
|
||||
raise SystemExit(f"FAIL: expected 403, got {exc.code}")
|
||||
print("PASS: anonymous S3 GET rejected with 403 (private bucket)")
|
||||
finally:
|
||||
pool.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,71 @@
|
||||
"""10 simultaneous real uploads + Docker RSS observations (NO invented metrics)."""
|
||||
import concurrent.futures
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from statistics import median
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, check, arguments, run
|
||||
|
||||
|
||||
def mib(value):
|
||||
value = value.strip()
|
||||
for suffix, multiplier in (("GiB",1024),("MiB",1),("KiB",1/1024),("B",1/1048576)):
|
||||
if value.endswith(suffix):
|
||||
return float(value[:-len(suffix)]) * multiplier
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Concurrent uploads + observed API container memory')
|
||||
client = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
file = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
results, memory = [], []
|
||||
stop = threading.Event()
|
||||
def observe():
|
||||
while not stop.is_set():
|
||||
r = subprocess.run(['docker','stats','--no-stream','--format','{{.Name}}|{{.MemUsage}}'],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
if r.returncode == 0:
|
||||
for line in r.stdout.splitlines():
|
||||
if '|api1-' in line or '|api2-' in line:
|
||||
pass
|
||||
parts = line.split('|')
|
||||
if len(parts)==2 and ('api1-' in parts[0] or 'api2-' in parts[0]):
|
||||
amount = mib(parts[1].split('/')[0])
|
||||
if amount is not None:
|
||||
memory.append({'container': parts[0], 'mem_mib': round(amount,3)})
|
||||
stop.wait(0.2)
|
||||
monitor = threading.Thread(target=observe, daemon=True)
|
||||
monitor.start()
|
||||
try:
|
||||
def worker(i):
|
||||
local = Client(args.base_url,args.ca_file,timeout=30)
|
||||
start=time.perf_counter()
|
||||
resp=local.call('POST', f'/api/v1/chats/{chat["id"]}/attachments?filename=run{i}.png',
|
||||
201, actor=alice, raw=file, headers={'Content-Type':'image/png'}, schema='Attachment')
|
||||
return {'elapsed_ms':round((time.perf_counter()-start)*1000,2), 'instance': resp['headers'].get('X-Instance-Id')}
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
|
||||
futures=[executor.submit(worker,i) for i in range(10)]
|
||||
results=[f.result() for f in concurrent.futures.as_completed(futures)]
|
||||
finally:
|
||||
stop.set(); monitor.join(timeout=12)
|
||||
output={'concurrency':10,'file_bytes':len(file),'completed':len(results),
|
||||
'median_latency_ms':round(median(x['elapsed_ms'] for x in results),2),
|
||||
'api_peak_mem_mib_observed':max([x['mem_mib'] for x in memory],default=None),
|
||||
'memory_samples':len(memory),'instances':sorted(set(x['instance'] for x in results))}
|
||||
target=ROOT / 'evidence' / 'uploads-10.json'
|
||||
target.write_text(json.dumps(output,ensure_ascii=False,indent=2),encoding='utf-8')
|
||||
check(len(results)==10, 'not all uploads completed')
|
||||
print('PASS: 10 parallel uploads; metrics written:',target)
|
||||
print(json.dumps(output, ensure_ascii=False, indent=2))
|
||||
if not memory:
|
||||
print('WARNING: no Docker memory samples; run docker stats separately for a valid grade-4 experiment')
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
docker compose --env-file .env stop lb api1 api2 redis postgres s3
|
||||
if errorlevel 1 exit /b 1
|
||||
docker compose --env-file .env up -d --wait
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --env-file .env stop lb api1 api2 redis postgres s3
|
||||
docker compose --env-file .env up -d --wait
|
||||
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
docker compose --env-file .env up -d --no-deps --force-recreate --wait api1
|
||||
if errorlevel 1 exit /b 1
|
||||
docker compose --env-file .env up -d --no-deps --force-recreate --wait api2
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --env-file .env up -d --no-deps --force-recreate --wait api1
|
||||
docker compose --env-file .env up -d --no-deps --force-recreate --wait api2
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
case "${1:-api1}" in
|
||||
api1|api2) docker compose --env-file .env up -d "$1" ;;
|
||||
*) echo "Usage: scripts/start-one.sh api1|api2" >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
if "%TARGET_INSTANCE_ID%"=="" set "TARGET_INSTANCE_ID=api1"
|
||||
if not "%TARGET_INSTANCE_ID%"=="api1" if not "%TARGET_INSTANCE_ID%"=="api2" exit /b 2
|
||||
docker compose --env-file .env stop %TARGET_INSTANCE_ID%
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
case "${TARGET_INSTANCE_ID:-api1}" in
|
||||
api1|api2) target="${TARGET_INSTANCE_ID:-api1}" ;;
|
||||
*) echo "Unknown API replica" >&2; exit 2 ;;
|
||||
esac
|
||||
docker compose --env-file .env stop "$target"
|
||||
@@ -0,0 +1,42 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import threading
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def main():
|
||||
client = Client()
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
key = uuid4().hex
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
text = "Проверка одновременного повтора " + key
|
||||
barrier = threading.Barrier(12)
|
||||
|
||||
def send(_):
|
||||
local = Client(timeout=10)
|
||||
barrier.wait(timeout=10)
|
||||
response = local.message(alice, chat, text, key=key)
|
||||
return response["json"], response["headers"]["X-Instance-Id"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=12) as workers:
|
||||
results = list(workers.map(send, range(12)))
|
||||
|
||||
ids = {message["id"] for message, _ in results}
|
||||
instances = {instance for _, instance in results}
|
||||
check(len(ids) == 1, "Повтор создал несколько сообщений")
|
||||
check(len(instances) == 2, "Не удалось проверить обе реплики")
|
||||
check(all(result[0] == results[0][0] for result in results), "Ответы различаются")
|
||||
client.call("POST", path, 409, actor=alice, body={"text": "Другой текст"},
|
||||
headers={"Idempotency-Key": key})
|
||||
page = client.call("GET", path + "?limit=100", actor=alice, schema="MessagePage")["json"]
|
||||
check(sum(item["id"] in ids for item in page["items"]) == 1,
|
||||
"В истории найден дубль сообщения")
|
||||
print("PASS: 12 параллельных запросов; 2 реплики; 1 сообщение; повтор с другим текстом — 409")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user