forked from mtusi2026/mtusi2026lab4
Implement lab4 private S3 attachments, safe reconciliation and defense guide
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deterministic storage faults on synthetic attachments; repeatable reconciliation."""
|
||||
import hashlib,json,os,subprocess,sys,time,uuid,urllib.request,urllib.error,socket
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'))
|
||||
from client import Client,check
|
||||
BASE='http://localhost:8084'
|
||||
def dc(*a,input=None):return subprocess.check_output(['docker','compose',*a],cwd=ROOT,input=input,text=True,stderr=subprocess.DEVNULL).strip()
|
||||
def sql(query):return dc('exec','-T','postgres','psql','-v','ON_ERROR_STOP=1','-U','messenger','-d','messenger','-Atqc',query)
|
||||
def mc(command):
|
||||
# Credentials are consumed inside the one-shot admin container; never output.
|
||||
prefix='mc alias set local http://s3:9000 "$(cat /run/secrets/s3_root_user)" "$(cat /run/secrets/s3_root_password)" >/dev/null; '
|
||||
return dc('run','--rm','--no-deps','--entrypoint','/bin/sh','s3-init','-c',prefix+command)
|
||||
def reconcile(apply=False):
|
||||
raw=dc('run','--rm','--no-deps','api','reconcile','--grace-seconds','60',*(['--apply'] if apply else []))
|
||||
return json.loads(raw.splitlines()[-1])
|
||||
def main():
|
||||
c=Client(BASE);a,b,e,chat=c.bootstrap();original=(ROOT/'tests/fixtures/sample.png').read_bytes();report={}
|
||||
def upload(name):return c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename='+name,201,actor=a,raw=original,headers={'Content-Type':'image/png'},schema='Attachment')['json']
|
||||
def key(att):return sql("SELECT object_key FROM attachments WHERE id='"+att['id']+"'")
|
||||
used=upload('used.png');c.message(a,chat,'Used and preserved',attachments=[used['id']])
|
||||
missing=upload('missing-unused.png');missing_used=upload('missing-used.png');c.message(a,chat,'Keep reference',attachments=[missing_used['id']])
|
||||
orphan=upload('orphan.png');orphan_key=key(orphan)
|
||||
sql("DELETE FROM attachments WHERE id='"+orphan['id']+"'")
|
||||
for att in [missing,missing_used]:mc('mc rm local/messenger-attachments/'+key(att))
|
||||
# Fail exactly AFTER S3 PUT, at the metadata INSERT. The persistent intent
|
||||
# and real orphan are evidence, without a runtime fault-injection endpoint.
|
||||
sql("CREATE FUNCTION research_reject_attachment() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='commit_fail.png' THEN RAISE EXCEPTION 'synthetic metadata failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER research_fail BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION research_reject_attachment()")
|
||||
try:c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=commit_fail.png',503,actor=a,raw=original,headers={'Content-Type':'image/png'})
|
||||
finally:sql('DROP TRIGGER research_fail ON attachments; DROP FUNCTION research_reject_attachment()')
|
||||
report['after_pg_insert_fault']={'intents':int(sql('SELECT count(*) FROM upload_intents')),'metadata_committed':int(sql("SELECT count(*) FROM attachments WHERE filename='commit_fail.png'"))}
|
||||
check(report['after_pg_insert_fault']['intents']>=1 and report['after_pg_insert_fault']['metadata_committed']==0,'journal missing after DB fault')
|
||||
# Interrupted client body: close a real LB socket after part of the PNG.
|
||||
from urllib.parse import urlsplit
|
||||
target=urlsplit(BASE);s=socket.create_connection((target.hostname,target.port));head=('POST /api/v1/chats/'+chat['id']+'/attachments?filename=interrupted.png HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer '+a['token']+'\r\nContent-Type: image/png\r\nContent-Length: '+str(len(original))+'\r\n\r\n').encode();s.sendall(head+original[:30]);s.close();time.sleep(1)
|
||||
report['interrupted_upload_metadata']=int(sql("SELECT count(*) FROM attachments WHERE filename='interrupted.png'"));check(report['interrupted_upload_metadata']==0,'interrupted metadata')
|
||||
# Test anonymous access to the exact existing private object, from the network.
|
||||
cmd='wget -S -O /dev/null http://s3:9000/messenger-attachments/'+key(used)
|
||||
denied=subprocess.run(['docker','compose','exec','-T','api','sh','-c',cmd],cwd=ROOT,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
|
||||
report['private_bucket_anonymous_http_403']='403 Forbidden' in denied.stdout;check(report['private_bucket_anonymous_http_403'],'bucket is public')
|
||||
# S3 outage cannot produce 201. LB can synthesize its own 503 while all
|
||||
# readiness probes fail, so inspect raw status instead of API-only headers.
|
||||
dc('stop','s3');start=time.monotonic()
|
||||
try:
|
||||
req=urllib.request.Request(BASE+'/api/v1/chats/'+chat['id']+'/attachments?filename=down.png',data=original,method='POST',headers={'Authorization':'Bearer '+a['token'],'Content-Type':'image/png'})
|
||||
try:status=urllib.request.urlopen(req,timeout=5).status
|
||||
except urllib.error.HTTPError as ex:status=ex.code
|
||||
report['s3_outage']={'status':status,'seconds':time.monotonic()-start};check(status==503,'S3 down accepted upload')
|
||||
finally:dc('start','s3');dc('up','-d','--wait');time.sleep(2)
|
||||
print('Fault fixtures created; waiting for 60s grace without overriding timestamps',flush=True)
|
||||
# All old fixtures predate this wait. Fresh objects are created afterwards.
|
||||
time.sleep(62)
|
||||
fresh=upload('fresh.png');fresh_orphan='originals/'+str(uuid.uuid4());mc('mc cp /config/s3-policy.json local/messenger-attachments/'+fresh_orphan+' >/dev/null')
|
||||
report['dry_run']=reconcile();report['apply']=reconcile(True);report['rerun']=reconcile(True)
|
||||
check(report['dry_run']['orphans']>=2 and report['dry_run']['missing']>=2,'fault detection incomplete')
|
||||
check(report['apply']['deleted_objects']>=2 and report['apply']['deleted_metadata']>=1,'repair incomplete')
|
||||
check(report['apply']['referenced_protected']>=1 and report['apply']['fresh_protected']>=2,'unsafe repair')
|
||||
check(report['rerun']['deleted_objects']==0 and report['rerun']['deleted_metadata']==0 and report['rerun']['cleared_intents']==0,'not idempotent')
|
||||
for att in [used,fresh]:
|
||||
data=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)['bytes'];check(hashlib.sha256(data).hexdigest()==att['sha256'],'valid original removed')
|
||||
check(sql("SELECT count(*) FROM attachments WHERE id='"+missing_used['id']+"'")=='1','used metadata deleted')
|
||||
# Bytes cannot be reconstructed from a checksum: restoring the missing used
|
||||
# object requires the original, kept here only as the synthetic fixture.
|
||||
restore_key=key(missing_used)
|
||||
fixture_hex=original.hex()
|
||||
# Pass original through stdin to mc pipe (no auth in stdin or output).
|
||||
prefix='mc alias set local http://s3:9000 "$(cat /run/secrets/s3_root_user)" "$(cat /run/secrets/s3_root_password)" >/dev/null; mc pipe local/messenger-attachments/'+restore_key+' >/dev/null'
|
||||
subprocess.run(['docker','compose','run','--rm','--no-deps','-T','--entrypoint','/bin/sh','s3-init','-c',prefix],cwd=ROOT,input=original,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,check=True)
|
||||
report['used_missing_restored_from_original']=c.call('GET','/api/v1/attachments/'+missing_used['id']+'/content',actor=b)['bytes']==original
|
||||
report['remaining_fresh_orphan_protected']=fresh_orphan
|
||||
(ROOT/'evidence/consistency.json').write_text(json.dumps(report,indent=2)+'\n');print('PASS: faults, private bucket, dry-run, safe repair, repeated repair and preservation')
|
||||
if __name__=='__main__':main()
|
||||
Reference in New Issue
Block a user