feat(lab4): private S3 attachments and safe storage reconciliation

This commit is contained in:
Quzzqq
2026-11-06 16:51:18 +03:00
parent ec540a1a72
commit 435a6465ec
61 changed files with 3106 additions and 33 deletions
+94
View File
@@ -0,0 +1,94 @@
"""Additional contract, image, concurrency and private-bucket tests; run inside api1."""
import concurrent.futures
import hashlib
import io
import json
import os
from pathlib import Path
import socket
import sys
import time
import urllib.error
import urllib.request
import uuid
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from client import Client, check
from PIL import Image
from src.storage import BUCKET, db, s3
def main():
c = Client('http://lb:8080',timeout=30)
alice,bob,eve,chat = c.bootstrap()
path = '/api/v1/chats/'+chat['id']
fixture = Path('tests/fixtures/sample.png').read_bytes()
def upload(raw=fixture,mime='image/png',filename='photo.png',expected=201):
return c.call('POST',path+'/attachments?filename='+filename,expected,actor=alice,
raw=raw,headers={'Content-Type':mime},schema='Attachment' if expected==201 else None)
upload(raw=b'broken',expected=415)
upload(mime='image/jpeg',expected=415)
upload(filename='..%2Fsecret.png',expected=400)
upload(filename='bad%00.png',expected=400)
upload(raw=b'x'*(10485760+1),expected=413)
out = io.BytesIO()
Image.new('RGB',(7000,6000)).save(out,format='PNG')
upload(raw=out.getvalue(),expected=413)
out = io.BytesIO()
Image.new('RGB',(40,30)).save(out,format='JPEG')
jpeg = upload(raw=out.getvalue(),mime='image/jpeg')['json']
check(c.call('GET','/api/v1/attachments/'+jpeg['id']+'/content',actor=bob)['bytes']==out.getvalue(),'JPEG changed')
att = upload()['json']
c.call('GET','/api/v1/attachments/'+att['id'],404,actor=eve)
other = c.call('POST','/api/v1/chats',201,actor=alice,
body={'title':'other','member_ids':[alice['id']]},schema='Chat')['json']
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=alice,
body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
c.call('POST',path+'/messages',404,actor=alice,
body={'text':'','attachment_ids':[str(uuid.uuid4())]},headers={'Idempotency-Key':uuid.uuid4().hex})
c.call('POST',path+'/messages',400,actor=alice,body={'text':'x','sender_id':eve['id']})
c.call('GET','/api/v1/chats/not-a-uuid',400,actor=alice)
c.call('GET',path+'/messages?cursor=invalid',400,actor=alice)
m1 = c.message(alice,chat,'one')['json']
c.message(alice,chat,'two')
cursor = c.call('GET',path+'/messages?limit=1',actor=alice,schema='MessagePage')['json']['next_cursor']
c.call('GET','/api/v1/chats/'+other['id']+'/messages?cursor='+cursor,400,actor=alice)
key = uuid.uuid4().hex
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
rows = list(pool.map(lambda _:c.message(alice,chat,'same',key=key)['json'],range(12)))
check(len({r['id'] for r in rows})==1,'concurrent duplicate message')
c.call('POST',path+'/messages',201,actor=alice,body={'attachment_ids':[],'text':'same'},
headers={'Idempotency-Key':key},schema='Message')
with db() as con:
objkey = con.execute('SELECT object_key FROM attachments WHERE id=%s',(att['id'],)).fetchone()['object_key']
before = con.execute('SELECT count(*) n FROM attachments').fetchone()['n']
try:
urllib.request.urlopen('http://s3:9000/'+BUCKET+'/'+objkey)
except urllib.error.HTTPError as exc:
check(exc.code==403,'unexpected anonymous S3 status')
else:
raise AssertionError('bucket public')
try:
s3().create_bucket(Bucket='forbidden-'+uuid.uuid4().hex)
except Exception as exc:
check(getattr(exc,'response',{}).get('Error',{}).get('Code')=='AccessDenied','scope test failed')
else:
raise AssertionError('application has admin S3 rights')
# Abandon binary request before declared end; it must never reach PUT.
sock = socket.create_connection(('api2',8080))
headers = ('POST '+path+'/attachments?filename=partial.png HTTP/1.1\r\nHost: api2\r\n'
'Authorization: Bearer '+alice['token']+'\r\nContent-Type: image/png\r\n'
'Content-Length: 100000\r\n\r\n').encode()
sock.sendall(headers+fixture[:80])
sock.close()
time.sleep(1)
with db() as con:
check(con.execute('SELECT count(*) n FROM attachments').fetchone()['n']==before,'partial upload committed')
print(json.dumps({'result':'PASS','negative_image_and_acl':True,'private_bucket_status':403,
'scoped_credentials':True,'parallel_idempotency_requests':12,
'unique_messages':1,'interrupted_upload_no_metadata':True}))
if __name__ == '__main__':
main()
+34
View File
@@ -0,0 +1,34 @@
"""20 ms cgroup-v2 memory sampler; stop by EOF on stdin. No privileged access."""
import json
from pathlib import Path
import threading
import time
done = threading.Event()
def wait():
import sys
sys.stdin.read()
done.set()
threading.Thread(target=wait,daemon=True).start()
root = Path('/sys/fs/cgroup')
def read(name):
path = root/name
return int(path.read_text()) if path.exists() else None
def rss():
lines = Path('/proc/1/status').read_text().splitlines()
return int(next(x.split()[1] for x in lines if x.startswith('VmRSS:')))*1024
baseline = read('memory.current')
peak_before = read('memory.peak')
peak = baseline
rss_peak = rss()
samples = 0
start = time.monotonic()
while not done.is_set():
peak = max(peak,read('memory.current'))
rss_peak = max(rss_peak,rss())
samples += 1
done.wait(0.02)
print(json.dumps(dict(baseline_bytes=baseline,sampled_peak_bytes=peak,
kernel_lifetime_peak_before_bytes=peak_before,kernel_lifetime_peak_after_bytes=read('memory.peak'),
api_rss_peak_bytes=rss_peak,sample_count=samples,interval_seconds=0.02,
elapsed_seconds=time.monotonic()-start)))
+92
View File
@@ -0,0 +1,92 @@
"""Track 2: real S3 PUT + rolled-back SQL, missing bytes, safe repeated repairs."""
import datetime as dt
import json
from pathlib import Path
import sys
import time
import uuid
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from client import Client, check
from src.storage import BUCKET, PREFIX, db, s3
from src.reconcile import reconcile
def main():
client = s3()
c = Client('http://lb:8080')
alice,bob,eve,chat = c.bootstrap()
used,raw = c.attachment(alice,chat)
c.message(alice,chat,'keep',attachments=[used['id']])
missing,_ = c.attachment(alice,chat)
with db() as con:
rows = con.execute('SELECT * FROM attachments WHERE id=ANY(%s::uuid[])',([used['id'],missing['id']],)).fetchall()
keys = {str(row['id']):row['object_key'] for row in rows}
def all_keys():
return {obj['Key'] for page in client.get_paginator('list_objects_v2').paginate(Bucket=BUCKET,Prefix=PREFIX)
for obj in page.get('Contents',[])}
before = all_keys()
# Failure injection is entirely in the test DB, not a production HTTP switch.
# A filename-specific trigger aborts the real API INSERT, after its real PUT.
marker = 'inject-'+uuid.uuid4().hex+'.png'
with db() as con:
con.execute("""CREATE OR REPLACE FUNCTION lab4_inject_failure() RETURNS trigger
LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename LIKE 'inject-%%' THEN
RAISE EXCEPTION 'synthetic commit-path failure'; END IF; RETURN NEW; END $$""")
con.execute('CREATE TRIGGER lab4_inject BEFORE INSERT ON attachments '
'FOR EACH ROW EXECUTE FUNCTION lab4_inject_failure()')
try:
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename='+marker,500,
actor=alice,raw=raw,headers={'Content-Type':'image/png'})
finally:
with db() as con:
con.execute('DROP TRIGGER IF EXISTS lab4_inject ON attachments')
con.execute('DROP FUNCTION IF EXISTS lab4_inject_failure()')
new_keys = all_keys()-before
check(len(new_keys)==1,'failed real upload must leave exactly one orphan')
orphan = new_keys.pop()
client.delete_object(Bucket=BUCKET,Key=keys[missing['id']])
with db() as con:
con.execute("UPDATE attachments SET created_at=clock_timestamp()-interval '2 hours' WHERE id=ANY(%s::uuid[])",
([used['id'],missing['id']],))
early = reconcile(True,60)
check(orphan not in early['orphan'],'fresh orphan deleted')
# LIST timestamps are assigned by S3, not forged. Wait for genuine grace expiry.
time.sleep(62)
fresh = PREFIX+'fresh-'+uuid.uuid4().hex
client.put_object(Bucket=BUCKET,Key=fresh,Body=raw)
preview = reconcile(False,60)
check(orphan in preview['orphan'] and missing['id'] in preview['missing'],'dry-run missed discrepancies')
check(client.head_object(Bucket=BUCKET,Key=orphan)['ContentLength']==len(raw),'dry-run mutated S3')
applied = reconcile(True,60)
check(orphan in applied['orphan'],'orphan not removed')
check(client.head_object(Bucket=BUCKET,Key=fresh)['ContentLength']==len(raw),'fresh deleted')
check(c.call('GET','/api/v1/attachments/'+used['id']+'/content',actor=bob)['bytes']==raw,'used attachment deleted')
c.call('GET','/api/v1/attachments/'+missing['id'],409,actor=alice)
again = reconcile(True,60)
check(not again['orphan'],'second run repeated deletion')
client.put_object(Bucket=BUCKET,Key=keys[missing['id']],Body=b'bad-backup')
wrong = reconcile(True,60)
check(missing['id'] not in wrong['repaired'],'corrupt backup published')
client.put_object(Bucket=BUCKET,Key=keys[missing['id']],Body=raw,ContentType='image/png')
restored = reconcile(True,60)
check(missing['id'] in restored['repaired'],'backup not restored')
check(c.call('GET','/api/v1/attachments/'+missing['id']+'/content',actor=bob)['bytes']==raw,'restored bytes mismatch')
# Force pagination (>1000 keys); new objects must all survive even --apply.
scale_prefix = PREFIX+'scale-'+uuid.uuid4().hex+'-'
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:
list(pool.map(lambda n:client.put_object(Bucket=BUCKET,Key=scale_prefix+str(n),Body=b'x'),range(1005)))
scaled = reconcile(False,3600)
check(scaled['list_requests']>=2,'pagination not tested')
# Clean only the exact keys this scenario owns (operator test cleanup).
for start in (0,1000):
client.delete_objects(Bucket=BUCKET,Delete={'Objects':[{'Key':scale_prefix+str(i)} for i in range(start,min(start+1000,1005))]})
client.delete_object(Bucket=BUCKET,Key=fresh)
print(json.dumps({'result':'PASS','early':early,'dry_run':preview,'apply':applied,
'repeat':again,'wrong_backup':wrong,'restore':restored,'scale':scaled},indent=2))
if __name__ == '__main__':
main()
+27
View File
@@ -0,0 +1,27 @@
"""Called with session/chat/attachment over stdin, never via arguments or files."""
import json
from pathlib import Path
import sys
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client, check
from src.reconcile import reconcile
from src.storage import db
data = json.load(sys.stdin)
c = Client('http://api1:8080',timeout=15)
c.call('GET','/health/ready',503)
c.call('GET','/health/live',200)
path = '/api/v1/chats/'+data['chat']['id']+'/attachments?filename=outage.png'
c.call('POST',path,503,actor=data['actor'],raw=Path('tests/fixtures/sample.png').read_bytes(),
headers={'Content-Type':'image/png'})
c.call('GET','/api/v1/attachments/'+data['attachment']['id']+'/content',503,actor=data['actor'])
try:
reconcile(True)
except Exception:
pass
else:
raise AssertionError('reconciler pretended unavailable storage was empty')
print(json.dumps({'result':'PASS','dependency':sys.argv[1],'live':200,'ready':503,
'upload':503,'download':503,'reconcile_aborted':True}))
+47
View File
@@ -0,0 +1,47 @@
"""10 concurrent real PNG uploads at two sizes; RSS includes all API processes.
Run in api1: /proc gives that replica's RSS; Docker stats sampled by run-all.py
records memory (including tmpfs/cache) for BOTH replicas during the same run.
"""
import concurrent.futures
import io
import json
import os
from pathlib import Path
import statistics
import sys
import time
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from client import Client, check
from PIL import Image
def main():
c = Client('http://lb:8080',timeout=60)
alice,bob,eve,chat = c.bootstrap()
results = []
for side in (512,1800):
out = io.BytesIO()
Image.frombytes('RGB',(side,side),os.urandom(side*side*3)).save(out,format='PNG')
data = out.getvalue()
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=warm.png',201,
actor=alice,raw=data,headers={'Content-Type':'image/png'},schema='Attachment')
for repeat in range(3):
start = time.monotonic()
def one(_):
return c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=load.png',
actor=alice,expected=201,raw=data,headers={'Content-Type':'image/png'},schema='Attachment')['elapsed']
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:
times = sorted(pool.map(one,range(10)))
duration = time.monotonic()-start
results.append(dict(size_bytes=len(data),pixels=side*side,concurrency=10,repeat=repeat+1,
duration_seconds=duration,successful_rps=10/duration,errors=0,
p50_seconds=statistics.median(times),p95_seconds=times[9],p99_seconds=times[9]))
print(json.dumps({'result':'PASS','profile':'closed-loop, 10 simultaneous uploads, 3 repeats/size',
'results':results},indent=2))
if __name__ == '__main__':
main()