Implement lab4 private S3 attachments and reconciliation track

This commit is contained in:
ferraronp
2026-11-12 18:15:42 +03:00
parent ec540a1a72
commit 87ce432b81
56 changed files with 2465 additions and 41 deletions
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""10 parallel uploads, report timings (capture Docker memory separately)."""
import argparse
import concurrent.futures
import json
import statistics
import time
from pathlib import Path
from client import Client, check
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--concurrency',type=int,default=10)
parser.add_argument('--output',default='evidence/attachments-concurrent.json')
parser.add_argument('--base-url',default='http://localhost:8080')
args = parser.parse_args()
c = Client(args.base_url)
alice,bob,eve,chat = c.bootstrap()
source = (Path(__file__).parent/'fixtures/sample.png').read_bytes()
path = '/api/v1/chats/'+chat['id']+'/attachments?filename=parallel.png'
def upload(i):
cli = Client(args.base_url)
res=cli.call('POST',path,201,actor=alice,raw=source,headers={'Content-Type':'image/png'},schema='Attachment')
check(res['json']['size_bytes']==len(source), 'Size mismatch')
return res['elapsed']
t=time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as pool:
values=list(pool.map(upload,range(args.concurrency)))
elapsed=time.monotonic()-t
data={'concurrency':args.concurrency,'uploads':len(values),'failed_requests':0,
'elapsed_seconds':round(elapsed,3),'upload_rps':round(len(values)/elapsed,3),
'latency_p50_ms':round(statistics.median(values)*1000,1),
'latency_max_ms':round(max(values)*1000,1),
'bytes_per_file':len(source),
'note':'Capture peak API RSS with docker stats; this script is client-side only.'}
Path(args.output).parent.mkdir(exist_ok=True,parents=True)
Path(args.output).write_text(json.dumps(data,indent=2),encoding='utf-8')
print(json.dumps(data,indent=2))
if __name__=='__main__':
main()
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Lab4 negative API tests with isolated synthetic users (requires live stack)."""
from urllib.parse import quote
import uuid
from client import Client, arguments, run, check
from pathlib import Path
def main():
args = arguments('Lab4 negative file/ACL/security tests')
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
base = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
data = (Path(__file__).parent / 'fixtures/sample.png').read_bytes()
c.call('POST', base+'big.png', 413, actor=alice, raw=data+b'\x00'*(10*1024*1024+1-len(data)), headers={'Content-Type':'image/png'})
c.call('POST', base+'bad.png', 415, actor=alice, raw=b'not-an-image', headers={'Content-Type':'image/png'})
c.call('POST', base+'fake.jpg', 415, actor=alice, raw=data, headers={'Content-Type':'image/jpeg'})
c.call('POST', base+quote('../escape.png',safe=''), 400, actor=alice, raw=data, headers={'Content-Type':'image/png'})
c.call('POST', base+'x.png', 404, actor=eve, raw=data, headers={'Content-Type':'image/png'})
c.call('POST', base+'x.png', 401, raw=data, headers={'Content-Type':'image/png'})
uploaded = c.attachment(alice,chat)[0]
unknown = str(uuid.uuid4())
c.call('GET','/api/v1/attachments/'+unknown,404,actor=alice)
c.call('GET','/api/v1/attachments/'+uploaded['id'],404,actor=eve)
c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content',404,actor=eve)
c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content?variant=thumbnail',404,actor=alice)
other_chat = c.call('POST','/api/v1/chats',201,actor=alice,
body={'title':'Другой чат','member_ids':[alice['id'],bob['id']]},schema='Chat')['json']
path = '/api/v1/chats/'+other_chat['id']+'/messages'
c.call('POST',path,404,actor=alice,
body={'text':'cross-chat','attachment_ids':[uploaded['id']]},
headers={'Idempotency-Key':uuid.uuid4().hex})
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',404,actor=alice,
body={'text':'unknown','attachment_ids':[unknown]},
headers={'Idempotency-Key':uuid.uuid4().hex})
ok = c.message(bob,chat,'',attachments=[uploaded['id']])['json']
check(ok['attachment_ids']==[uploaded['id']], 'valid attachment not linked')
print('PASS: lab4 negative image, MIME, size, filename, ACL and cross-chat checks')
if __name__=='__main__':
run(main)
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Lab3 own test: 30 requests using identical actor/chat/key/body across both replicas."""
import concurrent.futures
import sys
import uuid
from client import Client, Failure, arguments, check, run
def main():
args = arguments("Check atomic idempotency across API replicas")
c = Client(args.base_url, args.ca_file)
alice, bob, _, chat = c.bootstrap()
key = uuid.uuid4().hex
body = {"text": "Concurrent replay " + key}
path = f"/api/v1/chats/{chat['id']}/messages"
def worker(_):
# Independent request client; one shared bearer token and idempotency key.
client = Client(args.base_url, args.ca_file)
return client.call("POST", path, expected=201, actor=alice, body=body,
headers={"Idempotency-Key": key}, schema="Message")
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as executor:
results = list(executor.map(worker, range(30)))
ids = {result["json"]["id"] for result in results}
instances = {result["headers"]["X-Instance-Id"] for result in results}
check(len(ids) == 1, "parallel replay created different messages")
check(len(instances) >= 2, "LB did not serve requests via both API replicas")
check(all(r["json"] == results[0]["json"] for r in results), "replay returned altered result")
c.call("POST", path, 409, actor=alice, body={"text": "different body"}, headers={"Idempotency-Key": key})
c.call("POST", path, 201, actor=bob, body=body, headers={"Idempotency-Key": key}, schema="Message")
history = c.call("GET", path + "?limit=100", actor=bob, schema="MessagePage")["json"]["items"]
check(sum(x["id"] in ids for x in history) == 1, "message duplicated in history")
print("PASS: parallel idempotency across", len(instances), "replicas; one message, replay 201, conflicting body 409")
if __name__ == "__main__":
run(main)
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""Fast non-Docker checks for input contracts and cursor scoping."""
import sys
from pathlib import Path
from datetime import datetime, timezone
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.core import make_cursor, read_cursor, parse_limit, APIError
from app.models import CreateUser, CreateChat, CreateMessage
from pydantic import ValidationError
def reject(fn):
try:
fn()
except (APIError, ValidationError, ValueError):
return
raise AssertionError("Expected invalid input")
def main():
token = str(uuid.uuid4())
dt = datetime.now(timezone.utc)
cursor = make_cursor("messages", token, dt, str(uuid.uuid4()))
assert read_cursor(cursor, "messages", token)[0] == dt
reject(lambda: read_cursor(cursor, "messages", str(uuid.uuid4())))
reject(lambda: read_cursor(cursor, "chats", token))
assert parse_limit(None) == 50
reject(lambda: parse_limit("0"))
reject(lambda: parse_limit("101"))
reject(lambda: CreateUser(username="user_name", display_name=" \t", password="Long-enough-secret"))
reject(lambda: CreateUser(username="user_name", display_name="Test", password=" " * 3))
assert CreateMessage(text="A\u0000B").text == "A\u0000B"
reject(lambda: CreateMessage(text=" \t"))
reject(lambda: CreateChat(title="title", member_ids=[token] * 2))
reject(lambda: CreateChat(title="title", member_ids=[token] * 101))
print("PASS: models, cursor scoping, limits, Unicode U+0000")
if __name__ == "__main__":
main()