Store private attachments in S3 with bounded uploads and safe reconciliation

This commit is contained in:
2026-10-16 17:16:07 +03:00
parent ec540a1a72
commit 5af28139c3
37 changed files with 2645 additions and 38 deletions
+32
View File
@@ -0,0 +1,32 @@
"""Create separate local DB, API and S3 administration credentials once, without printing them."""
import json
from pathlib import Path
import secrets
root=Path(__file__).resolve().parents[1]
target=root/'.env'
if target.exists():
required=['.env.api','.env.storage-admin','secrets/s3.json']
if not all((root/p).exists() for p in required):
raise SystemExit('Incomplete bootstrap: preserve existing secrets and restore the missing local files')
print('Existing local configuration preserved')
else:
password=secrets.token_hex(24)
admin_key,admin_secret=secrets.token_hex(12),secrets.token_hex(32)
api_key,api_secret=secrets.token_hex(12),secrets.token_hex(32)
(root/'secrets').mkdir(exist_ok=True)
files={
'.env':f'POSTGRES_PASSWORD={password}\n',
'.env.api':f'DATABASE_URL=postgresql://messenger:{password}@db:5432/messenger\nREDIS_URL=redis://cache:6379/0\nCURSOR_SECRET={secrets.token_hex(32)}\nSESSION_TTL_SECONDS=3600\nS3_ENDPOINT=http://s3:8333\nS3_BUCKET=messenger\nS3_ACCESS_KEY={api_key}\nS3_SECRET_KEY={api_secret}\n',
'.env.storage-admin':f'S3_ENDPOINT=http://s3:8333\nS3_BUCKET=messenger\nS3_ACCESS_KEY={admin_key}\nS3_SECRET_KEY={admin_secret}\n',
'secrets/s3.json':json.dumps({'identities':[
{'name':'bootstrap-admin','credentials':[{'accessKey':admin_key,'secretKey':admin_secret}],
'actions':['Admin','Read','Write','List','Tagging']},
{'name':'messenger-api','credentials':[{'accessKey':api_key,'secretKey':api_secret}],
'actions':['Read:messenger/originals/*','Write:messenger/originals/*','List:messenger']}
]},indent=2)+'\n'}
for name,content in files.items():
with (root/name).open('x',encoding='utf-8') as f: f.write(content)
try: (root/name).chmod(0o600)
except OSError: pass
print('Created separate local API and storage-admin configuration; no values displayed')
+120
View File
@@ -0,0 +1,120 @@
"""Inject a real S3/DB split, missing object, dry-run/apply/repeat and age safety."""
import base64
import hashlib
import json
import subprocess
import time
import uuid
import httpx
from stack import ROOT, docker, ready
OUT=ROOT/'evidence'
OUT.mkdir(exist_ok=True)
result={}
def sql(q): return docker('compose','exec','-T','db','psql','-U','messenger','-d','messenger','-Atc',q)
def inside(code):
return subprocess.check_output(['docker','compose','exec','-T','api','python','-'],
input=code,cwd=ROOT,text=True,encoding='utf-8',stderr=subprocess.PIPE).strip()
def reconcile(apply=False):
args=['compose','exec','-T','api','python','-m','src.reconcile','--grace-seconds','60']
if apply: args.append('--apply')
return json.loads(docker(*args))
def objects():
return set(json.loads(inside("from src.storage import Storage\nimport json\ns=Storage(); print(json.dumps([o['Key'] for p in s.client.get_paginator('list_objects_v2').paginate(Bucket=s.bucket,Prefix='originals/') for o in p.get('Contents',[])]))")))
data=(ROOT/'tests/fixtures/sample.png').read_bytes()
encoded=base64.b64encode(data).decode()
digest=hashlib.sha256(data).hexdigest()
with httpx.Client(base_url='http://127.0.0.1:8080',timeout=35) as c:
ready(c)
name='reconcile_'+uuid.uuid4().hex[:18]
password='reconciliation-test-123'
r=c.post('/api/v1/users',json={'username':name,'display_name':'Reconcile','password':password}); assert r.status_code==201,r.text
uid=r.json()['id']
r=c.post('/api/v1/auth/sessions',auth=(name,password)); assert r.status_code==201
h={'Authorization':'Bearer '+r.json()['token']}
r=c.post('/api/v1/chats',headers=h,json={'title':'Reconciliation','member_ids':[uid]}); assert r.status_code==201
chat=r.json()['id']
def upload(filename):
return c.post(f'/api/v1/chats/{chat}/attachments',headers={**h,'Content-Type':'image/png'},params={'filename':filename},content=data)
used=upload('used.png'); missing=upload('missing.png')
assert used.status_code==missing.status_code==201
used,missing=used.json(),missing.json()
r=c.post(f'/api/v1/chats/{chat}/messages',headers={**h,'Idempotency-Key':uuid.uuid4().hex},json={'text':'','attachment_ids':[used['id']]})
assert r.status_code==201
used_key=sql("SELECT object_key FROM attachments WHERE id='"+used['id']+"'")
missing_key=sql("SELECT object_key FROM attachments WHERE id='"+missing['id']+"'")
filename='fault_'+uuid.uuid4().hex+'.png'
trigger='fault_'+uuid.uuid4().hex
before=objects()
# Scope is one unique synthetic filename; unrelated requests remain unaffected.
sql(f"CREATE FUNCTION {trigger}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='{filename}' THEN RAISE EXCEPTION 'synthetic transient failure' USING ERRCODE='40001'; END IF; RETURN NEW; END $$; CREATE TRIGGER {trigger} BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION {trigger}();")
try:
failed=upload(filename)
assert failed.status_code==503,(failed.status_code,failed.text)
finally:
sql(f'DROP TRIGGER {trigger} ON attachments; DROP FUNCTION {trigger}();')
orphaned=objects()-before
assert len(orphaned)==1,orphaned
orphan=next(iter(orphaned)); orphan_created=time.monotonic()
assert sql("SELECT count(*) FROM attachments WHERE filename='"+filename+"'")=='0'
result['put_before_database_failure']={'http_status':503,'orphan':orphan,'metadata_rows':0}
# Fresh orphan must remain even with --apply.
fresh_run=reconcile(True)
assert orphan in objects()
result['fresh_orphan_preserved']=fresh_run
# Generate 200 real object/metadata pairs for a measurable traversal; no mock S3.
setup_code=f'''import base64,io,uuid,os,psycopg
from src.storage import Storage
s=Storage(); data=base64.b64decode({encoded!r})
with psycopg.connect(os.environ['DATABASE_URL']) as db:
for n in range(200):
aid=uuid.uuid4(); key='originals/'+str(aid)
s.put(key,io.BytesIO(data),len(data),'image/png',{digest!r})
db.execute('INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)',(aid,{chat!r},{uid!r},'scan-fixture.png',key,'image/png',len(data),{digest!r}))
print('Created 200 synthetic object/metadata pairs')'''
result['dataset']=inside(setup_code)
inside("from src.storage import Storage; Storage().delete("+repr(missing_key)+")")
before_objects=objects()
dry=reconcile(False)
assert objects()==before_objects
assert sql("SELECT storage_state FROM attachments WHERE id='"+missing['id']+"'")=='ready'
assert any(a['action']=='quarantine_missing' and a['id']==missing['id'] for a in dry['actions'])
result['missing_dry_run']=dry
applied=reconcile(True)
assert sql("SELECT storage_state FROM attachments WHERE id='"+missing['id']+"'")=='missing'
assert c.get('/api/v1/attachments/'+missing['id'],headers=h).status_code==503
assert c.get('/api/v1/attachments/'+used['id']+'/content',headers=h).content==data
result['missing_quarantined']=applied
# Restore from the known test fixture (in reality from backup), then verify byte checksum before publishing ready.
inside("from src.storage import Storage; import io,base64; data=base64.b64decode("+repr(encoded)+"); Storage().put("+repr(missing_key)+",io.BytesIO(data),len(data),'image/png',"+repr(digest)+")")
result['restored_from_fixture']=reconcile(True)
assert c.get('/api/v1/attachments/'+missing['id']+'/content',headers=h).content==data
# Real elapsed grace, not backdated timestamps or a monkeypatched clock.
while time.monotonic()-orphan_created<65:
time.sleep(min(5,65-(time.monotonic()-orphan_created)))
fresh_key='originals/'+str(uuid.uuid4())
inside("from src.storage import Storage; import io,base64; data=base64.b64decode("+repr(encoded)+"); Storage().put("+repr(fresh_key)+",io.BytesIO(data),len(data),'image/png',"+repr(digest)+")")
before_objects=objects()
dry=reconcile(False)
assert objects()==before_objects
assert any(a=={'action':'delete_orphan','key':orphan} for a in dry['actions'])
assert not any(a.get('key') in (fresh_key,used_key,missing_key) for a in dry['actions'])
result['aged_orphan_dry_run']=dry
result['aged_orphan_apply']=reconcile(True)
after=objects()
assert orphan not in after and fresh_key in after and used_key in after and missing_key in after
repeated=reconcile(True)
assert repeated['actions']==[],repeated
result['repeat_noop']=repeated
assert c.get('/api/v1/attachments/'+used['id']+'/content',headers=h).content==data
result['used_and_fresh_preserved']=True
result['actual_grace_elapsed_seconds']=round(time.monotonic()-orphan_created,3)
result['passed']=True
# Remove only the known test-only fresh orphan after the assertions; not application data.
inside("from src.storage import Storage; Storage().delete("+repr(fresh_key)+")")
(OUT/'reconciliation.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,indent=2))
+13
View File
@@ -0,0 +1,13 @@
"""Restart every running replica and dependency, preserving durable volumes."""
import json
from stack import ROOT, docker, state
before = state()
docker('compose', 'restart', 'api', 'db', 'cache', 'lb', 's3', 'reconciler')
after = state()
assert set(before) == set(after)
assert all(before[c]['state']['StartedAt'] != after[c]['state']['StartedAt'] for c in before)
(ROOT / 'evidence').mkdir(exist_ok=True)
(ROOT / 'evidence/restart-processes.json').write_text(
json.dumps({'before': before, 'after': after, 'volumes_removed': False}, indent=2) + '\n',
encoding='utf-8')
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
python3 scripts/restart.py
+35
View File
@@ -0,0 +1,35 @@
"""Shared bounded Docker helpers for reproducible, scoped failure experiments."""
import json
from pathlib import Path
import subprocess
import time
ROOT=Path(__file__).resolve().parents[1]
def docker(*args):
return subprocess.check_output(['docker',*args],cwd=ROOT,text=True,encoding='utf-8',stderr=subprocess.PIPE).strip()
def replicas(): return docker('compose','ps','-q','api').splitlines()
def ready_replicas(count=2,timeout=60):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
ids=replicas()
if len(ids)==count:
states=[json.loads(docker('inspect','--format','{{json .State}}',cid)) for cid in ids]
if all(s['Running'] and s.get('Health',{}).get('Status')=='healthy' for s in states): return
time.sleep(.5)
raise AssertionError('Actual replica health did not recover within timeout')
def instance(cid):
return docker('exec',cid,'python','-c',"import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8080/health/live',timeout=2).headers['X-Instance-Id'])")
def state():
result={}
for service in ('api','db','cache','lb','s3','reconciler'):
for cid in docker('compose','ps','-q',service).splitlines():
result[cid]={'service':service,'state':json.loads(docker('inspect','--format','{{json .State}}',cid))}
return result
def ready(client,timeout=60):
deadline=time.monotonic()+timeout
while time.monotonic()<deadline:
try:
if client.get('/health/ready').status_code==200: return
except Exception: pass
time.sleep(.2)
raise AssertionError('Readiness timeout')
+12
View File
@@ -0,0 +1,12 @@
"""Stop the real process selected by X-Instance-Id; do not stop any dependency."""
import json
import os
from stack import ROOT, docker, instance, replicas
target=os.environ['TARGET_INSTANCE_ID']
matches=[cid for cid in replicas() if instance(cid)==target]
assert len(matches)==1,'Target does not uniquely identify a running API'
before=replicas()
docker('stop','--time','5',matches[0])
assert docker('inspect','--format','{{.State.Running}}',matches[0])=='false'
(ROOT/'evidence').mkdir(exist_ok=True)
(ROOT/'evidence/stop-one.json').write_text(json.dumps({'target_instance':target,'stopped_container':matches[0],'before_containers':before,'after_running_containers':replicas()},indent=2)+'\n',encoding='utf-8')
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
exec python3 scripts/stop-one.py
+178
View File
@@ -0,0 +1,178 @@
"""Black-box attachment checks against real PostgreSQL and private SeaweedFS."""
from concurrent.futures import ThreadPoolExecutor
import base64
import hashlib
import json
import os
from pathlib import Path
import socket
import struct
import subprocess
import sys
import tempfile
import threading
import time
import uuid
import zlib
import httpx
from stack import ROOT, docker, instance, ready, ready_replicas, replicas
OUT=ROOT/'evidence'
OUT.mkdir(exist_ok=True)
result={}
def sql(q): return docker('compose','exec','-T','db','psql','-U','messenger','-d','messenger','-Atc',q)
def inside(code): return docker('compose','exec','-T','api','python','-c',code)
def user(c):
name='test_'+uuid.uuid4().hex[:20]
password='synthetic-password-123'
r=c.post('/api/v1/users',json={'username':name,'display_name':'Files','password':password}); assert r.status_code==201,r.text
uid=r.json()['id']
r=c.post('/api/v1/auth/sessions',auth=(name,password)); assert r.status_code==201,r.text
return uid,{'Authorization':'Bearer '+r.json()['token']}
def newchat(c,h,members):
r=c.post('/api/v1/chats',headers=h,json={'title':'Attachments','member_ids':members})
assert r.status_code==201,r.text
return r.json()['id']
def restore(c):
docker('compose','up','-d','--no-deps','--scale','api=2','api'); ready_replicas(); ready(c)
deadline=time.monotonic()+15
while time.monotonic()<deadline:
ids={c.get('/health/ready').headers.get('X-Instance-Id') for _ in range(12)}-{None}
if len(ids)==2: return
time.sleep(.3)
raise AssertionError('LB did not recover two replicas')
def public(mode):
name='restart' if mode=='persistence' else 'stop-one'
with tempfile.TemporaryDirectory() as tmp:
if os.name=='nt':
hook=Path(tmp)/(name+'.cmd')
hook.write_text('@echo off\n"'+sys.executable+'" "'+str(ROOT/('scripts/'+name+'.py'))+'"\n',encoding='utf-8')
else: hook=ROOT/('scripts/'+name+'.sh')
run=subprocess.run([sys.executable,'-X','utf8','tests/resilience.py','--mode',mode,'--action-script',str(hook)],cwd=ROOT,text=True,encoding='utf-8',capture_output=True)
if run.returncode: raise AssertionError(run.stdout+run.stderr)
return run.stdout.strip()
def png(width,height,raw):
def chunk(kind,data): return struct.pack('!I',len(data))+kind+data+struct.pack('!I',zlib.crc32(kind+data)&0xffffffff)
return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!2I5B',width,height,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(raw,1))+chunk(b'IEND',b'')
def memory():
data={}
for cid in replicas():
status=docker('exec',cid,'python','-c',"print(open('/proc/1/status').read())")
data[cid]={k:int(next(line.split()[1] for line in status.splitlines() if line.startswith(k+':'))) for k in ('VmRSS','VmHWM')}
limits=json.loads(docker('exec',cid,'python','-c',"import json,pathlib; p=pathlib.Path('/sys/fs/cgroup'); print(json.dumps({'peak_bytes':int((p/'memory.peak').read_text()),'events':dict(line.split() for line in (p/'memory.events').read_text().splitlines())}))"))
data[cid]['cgroup']=limits
return data
with httpx.Client(base_url='http://127.0.0.1:8080',timeout=35) as c:
restore(c)
result['public_smoke']=subprocess.check_output([sys.executable,'-X','utf8','tests/smoke.py'],cwd=ROOT,text=True).strip()
uid,h=user(c); bob,bh=user(c); eve,eh=user(c)
chat=newchat(c,h,[uid,bob]); path=f'/api/v1/chats/{chat}/attachments'
data=(ROOT/'tests/fixtures/sample.png').read_bytes()
def upload(body=data,mime='image/png',filename='sample.png',headers=h):
return c.post(path,params={'filename':filename},headers={**headers,'Content-Type':mime},content=body)
r=upload(); assert r.status_code==201,r.text
att=r.json(); serving=r.headers['X-Instance-Id']
ap='/api/v1/attachments/'+att['id']
assert att['sha256']==hashlib.sha256(data).hexdigest()
assert c.get(ap+'/content',headers=bh).content==data
for suffix in ('','/content'): assert c.get(ap+suffix,headers=eh).status_code==404
assert upload(headers=eh).status_code==404
statuses={}
for label,body,mime,filename,expected in [
('oversize',data+b'x'*(10485761-len(data)),'image/png','big.png',413),
('corrupt',b'not an image','image/png','bad.png',415),
('truncated',data[:50],'image/png','cut.png',415),
('mismatch',data,'image/jpeg','fake.jpg',415),
('unsupported',data,'text/plain','plain.png',415),
('path',data,'image/png','../secret.png',400),
('backslash',data,'image/png','a\\b.png',400),
('control',data,'image/png','a\x00.png',400),
('pixels',png(8000,6000,b'\x00'),'image/png','bomb.png',413)]:
r=upload(body,mime,filename); statuses[label]=r.status_code
assert r.status_code==expected,(label,r.status_code,r.text[:100])
result['negative_uploads']=statuses
jpeg=base64.b64decode(inside("from PIL import Image; import io,base64; f=io.BytesIO(); Image.new('RGB',(320,200),'white').save(f,format='JPEG'); print(base64.b64encode(f.getvalue()).decode())"))
r=upload(jpeg,'image/jpeg','valid.jpg'); assert r.status_code==201,r.text
assert c.get('/api/v1/attachments/'+r.json()['id']+'/content',headers=bh).content==jpeg
r=upload(jpeg[:-32],'image/jpeg','truncated.jpg'); assert r.status_code==415,r.text
result['jpeg_validation']='valid JPEG returned byte-for-byte; truncated entropy stream rejected with 415'
other=newchat(c,h,[uid])
r=c.post(f'/api/v1/chats/{other}/messages',headers={**h,'Idempotency-Key':uuid.uuid4().hex},json={'text':'','attachment_ids':[att['id']]})
assert r.status_code==404
r=c.post(f'/api/v1/chats/{chat}/messages',headers={**h,'Idempotency-Key':uuid.uuid4().hex},json={'text':'','attachment_ids':[str(uuid.uuid4())]})
assert r.status_code==404
key=uuid.uuid4().hex
msgpath=f'/api/v1/chats/{chat}/messages'
one=c.post(msgpath,headers={**h,'Idempotency-Key':key},json={'text':'Canonical'})
two=c.post(msgpath,headers={**h,'Idempotency-Key':key},json={'attachment_ids':[],'text':'Canonical'})
assert one.status_code==two.status_code==201 and one.json()==two.json()
result['attachment_acl_and_canonical_body']='foreign/unknown attachments 404; absent and [] attachment_ids replay same message'
key=sql("SELECT object_key FROM attachments WHERE id='"+att['id']+"'")
private=inside("import urllib.request,urllib.error\ntry:\n urllib.request.urlopen('http://s3:8333/messenger/"+key+"'); print(200)\nexcept urllib.error.HTTPError as e: print(e.code)")
assert private=='403',private
denied=inside("from src.storage import Storage\nfrom botocore.exceptions import ClientError\ns=Storage()\ntry:\n s.client.create_bucket(Bucket='denied-"+uuid.uuid4().hex+"'); print(200)\nexcept ClientError as e: print(e.response['ResponseMetadata']['HTTPStatusCode'])")
assert denied=='403',denied
denied_prefix=inside("from src.storage import Storage\nfrom botocore.exceptions import ClientError\ns=Storage()\ntry:\n s.client.put_object(Bucket=s.bucket,Key='forbidden/outside-prefix',Body=b'x'); print(200)\nexcept ClientError as e: print(e.response['ResponseMetadata']['HTTPStatusCode'])")
assert denied_prefix=='403',denied_prefix
result['private_bucket']={'anonymous_get':403,'api_create_other_bucket':403,'api_write_outside_prefix':403}
target=next(cid for cid in replicas() if instance(cid)==serving)
docker('stop','-t','5',target)
try:
deadline=time.monotonic()+10
while True:
r=c.get(ap+'/content',headers=bh)
if r.status_code==200: break
assert time.monotonic()<deadline
time.sleep(.2)
assert r.content==data and r.headers['X-Instance-Id']!=serving
result['upload_then_stop_download']={'stopped_container':target,'uploader_instance':serving,'downloader_instance':r.headers['X-Instance-Id'],'sha256_matches':True}
finally: restore(c)
# Abort a partially transmitted upload before S3 is touched.
before=sql('SELECT count(*) FROM attachments')
with socket.create_connection(('127.0.0.1',8080),timeout=3) as sock:
request=(f'POST {path}?filename=interrupted.png HTTP/1.1\r\nHost: localhost\r\nAuthorization: {h["Authorization"]}\r\nContent-Type: image/png\r\nContent-Length: 1000000\r\n\r\n').encode()
sock.sendall(request+data[:64])
time.sleep(.5)
assert sql('SELECT count(*) FROM attachments')==before
result['interrupted_upload']='partial body closed: no attachment metadata'
docker('compose','stop','s3')
try:
r=upload(); assert r.status_code==503,r.text
result['s3_down_status']=r.status_code
finally: docker('compose','start','s3')
ready(c); restore(c)
result['bootstrap_repeat']=docker('compose','run','--rm','--no-deps','storage-init')
result['public_persistence']=public('persistence'); restore(c)
result['public_failover']=public('failover'); restore(c)
# Ten simultaneous HTTP uploads, bounded admission with retries on explicit 503.
large=png(1800,1500,b''.join(b'\x00'+os.urandom(1800*3) for _ in range(1500)))
assert 7_000_000<len(large)<10485760
barrier=threading.Barrier(10)
before_memory=memory()
def concurrent(i):
with httpx.Client(base_url='http://127.0.0.1:8080',timeout=35) as client:
barrier.wait(); started=time.perf_counter(); attempts=[]
for attempt in range(50):
r=client.post(path,params={'filename':f'load-{i}.png'},headers={**h,'Content-Type':'image/png'},content=large)
attempts.append(r.status_code)
if r.status_code==201:
assert r.json()['sha256']==hashlib.sha256(large).hexdigest()
return {'i':i,'seconds':round(time.perf_counter()-started,3),'statuses':attempts}
assert r.status_code==503,r.text
time.sleep(.2)
raise AssertionError('Upload did not complete within bounded retries')
with ThreadPoolExecutor(max_workers=10) as pool: uploads=list(pool.map(concurrent,range(10)))
result['concurrent_uploads']={'clients':10,'bytes_each':len(large),'before_memory_kib':before_memory,'after_memory_kib':memory(),'uploads':uploads}
result['passed']=True
(OUT/'integration.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,ensure_ascii=False,indent=2))