Implement lab4 private S3 attachments, safe reconciliation and defense guide

This commit is contained in:
2026-10-29 21:36:49 +03:00
parent ec540a1a72
commit 6039524214
61 changed files with 5029 additions and 23 deletions
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
import json,os,subprocess,sys,time
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'))
from client import Client,Failure,check
c=Client('http://localhost:8084');a,b,e,chat=c.bootstrap();original=(ROOT/'tests/fixtures/sample.png').read_bytes()
upload=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=failover.png',201,actor=a,raw=original,headers={'Content-Type':'image/png'},schema='Attachment')
alias=upload['headers']['X-Instance-Id'];ids=subprocess.check_output(['docker','compose','ps','-q','api'],cwd=ROOT,text=True).splitlines()
matched=[id for id in ids if json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]['Config']['Hostname']==alias];check(len(matched)==1,'alias mapping')
started=time.monotonic();failures=0
try:
subprocess.run([str(ROOT/'scripts/stop-one.sh')],cwd=ROOT,env=dict(os.environ,TARGET_INSTANCE_ID=alias),check=True,stdout=subprocess.DEVNULL)
while True:
try:r=c.call('GET','/api/v1/attachments/'+upload['json']['id']+'/content',actor=b);break
except Failure:failures+=1;check(time.monotonic()-started<10,'download recovery >10s');time.sleep(.1)
check(r['bytes']==original and r['headers']['X-Instance-Id']!=alias,'download not preserved through another process')
stopped=json.loads(subprocess.check_output(['docker','inspect',matched[0]],text=True))[0];check(not stopped['State']['Running'],'target not stopped')
result={'upload_instance':alias,'stopped_container':stopped['Name'],'download_instance':r['headers']['X-Instance-Id'],'byte_equal':True,'first_recovery_seconds':time.monotonic()-started,'errors':failures}
(ROOT/'evidence/attachment-failover.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: exact uploader stopped; another API returned identical original')
finally:subprocess.run(['docker','compose','up','-d','--wait'],cwd=ROOT,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
import concurrent.futures as futures
import hashlib,json,os,struct,subprocess,sys,time,urllib.parse,uuid,zlib
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'))
from client import Client,arguments,check
def png(width,height):
def chunk(tag,data):return struct.pack('!I',len(data))+tag+data+struct.pack('!I',zlib.crc32(tag+data)&0xffffffff)
# Synthetic noise compresses poorly and makes >=2MiB fixtures without Pillow.
pixels=b''.join(b'\0'+os.urandom(width*3) for _ in range(height))
return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!IIBBBBB',width,height,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(pixels,1))+chunk(b'IEND',b'')
def dc(*a):return subprocess.check_output(['docker','compose',*a],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
def stats():
result={}
for id in dc('ps','-q','api').splitlines():
raw=dc('exec','-T','--index',str(json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]['Config']['Labels']['com.docker.compose.container-number']),'api','sh','-c','cat /sys/fs/cgroup/memory.current /sys/fs/cgroup/memory.peak')
result[id[:12]]=[int(x) for x in raw.split()]
return result
def main():
args=arguments('Attachment boundaries and concurrent memory experiment');c=Client(args.base_url or 'http://localhost:8084');a,b,e,chat=c.bootstrap();path='/api/v1/chats/'+chat['id']+'/attachments'
original=(ROOT/'tests/fixtures/sample.png').read_bytes()
def upload(raw=original,name='valid.png',mime='image/png',expected=201,actor=a):
return c.call('POST',path+'?filename='+urllib.parse.quote(name,safe=''),expected,actor=actor,raw=raw,headers={'Content-Type':mime},schema='Attachment' if expected==201 else None)
for name in ['../x.png','a\\b.png','bad\x00.png','bad\n.png',''] :upload(name=name,expected=400)
upload(raw=b'not image',expected=415);upload(mime='image/jpeg',expected=415);upload(raw=original[:40],expected=415)
upload(raw=b'x'*(10*1024*1024+1),expected=413)
# Valid PNG header + CRC, too many pixels; rejection precedes decompression.
def chunk(tag,data):return struct.pack('!I',len(data))+tag+data+struct.pack('!I',zlib.crc32(tag+data)&0xffffffff)
huge=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!IIBBBBB',10000,10000,8,2,0,0,0))+chunk(b'IDAT',b'')
upload(raw=huge,expected=413)
att=upload()['json'];key=uuid.uuid4().hex
c.message(a,chat,'',key=key,attachments=[att['id']])
other=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Other','member_ids':[a['id']]},schema='Chat')['json']
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=a,body={'text':'wrong chat','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',404,actor=a,body={'text':'unknown','attachment_ids':[str(uuid.uuid4())]},headers={'Idempotency-Key':uuid.uuid4().hex})
for suffix in ['', '/content']:c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=e)
# Same semantic body, reordered keys and optional [] omitted.
first=c.message(a,chat,'normalized',key='normalize-'+key)['json']
second=c.message(a,chat,'normalized',key='normalize-'+key,attachments=[])['json'];check(first==second,'optional [] changed idempotency')
fixture=png(1024,768);before=stats();start=time.monotonic();snapshots=[]
with futures.ThreadPoolExecutor(max_workers=10) as pool:
pending=[pool.submit(upload,fixture,'concurrent.png') for _ in range(10)]
while not all(f.done() for f in pending):snapshots.append(stats());time.sleep(.1)
responses=[f.result() for f in pending]
for r in responses:
download=c.call('GET','/api/v1/attachments/'+r['json']['id']+'/content',actor=b)
check(hashlib.sha256(download['bytes']).hexdigest()==r['json']['sha256'],'checksum mismatch')
after=stats()
result={'negative_cases':15,'simultaneous_clients':10,'fixture_bytes':len(fixture),'fixture_pixels':1024*768,'duration_seconds':time.monotonic()-start,'before_memory_current_peak_bytes':before,'after_memory_current_peak_bytes':after,'sampled_memory_current_peak_bytes':snapshots,'all_sha256_match':True,'per_api_upload_slots':1}
(ROOT/'evidence/attachments.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: file boundaries, ACL, normalization and 10 simultaneous uploads')
if __name__=='__main__':main()
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Run committed solution from a real local clone, new credentials and volumes."""
import json,os,socket,subprocess,tempfile,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
lab=json.loads((ROOT/'lab.json').read_text())['number']
project='verify-lab'+str(lab)+'-'+uuid.uuid4().hex[:10]
with socket.socket() as sock:sock.bind(('127.0.0.1',0));port=sock.getsockname()[1]
with tempfile.TemporaryDirectory(prefix=project+'-') as directory:
clone=Path(directory)/'repo';subprocess.run(['git','clone','--no-hardlinks',str(ROOT),str(clone)],check=True)
env=dict(os.environ,COMPOSE_PROJECT_NAME=project,APP_PORT=str(port),API_REPLICAS='2',SESSION_TTL_SECONDS='3600')
def run(*args):subprocess.run(args,cwd=clone,env=env,check=True)
def snapshots():
ids=subprocess.check_output(['docker','compose','ps','-q'],cwd=clone,env=env,text=True).splitlines()
result={}
for id in ids:
item=json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]
service=item['Config']['Labels']['com.docker.compose.service']
if service in ['api','postgres','valkey','s3']:result[item['Name']]={'service':service,'started_at':item['State']['StartedAt'],'image_id':item['Image'],'user':item['Config'].get('User',''),'pid1':item['Path']}
return result
try:
run('make','up');run('make','check');run('make','test','BASE_URL=http://localhost:'+str(port))
before=snapshots();run('make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL=http://localhost:'+str(port));after=snapshots()
for name,item in before.items():assert after[name]['started_at']!=item['started_at'],name+' was not restarted'
for item in after.values():
if item['service']=='api':assert item['user']=='10001:10001' and item['pid1']=='/usr/local/bin/messenger'
(ROOT/'evidence/persistence-processes.json').write_text(json.dumps({'scope':'disposable real clean clone','before':before,'after':after},indent=2)+'\n')
print('PASS: real clean clone, fresh secrets/volumes, smoke, same-session persistence, actual store/API restart, non-root PID1')
finally:
# Only this unique synthetic project, never the working lab volumes.
run('docker','compose','down','-v','--remove-orphans')
+72
View File
@@ -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()
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
"""Measure dry-run inventory cost at +0/+100/+1000 synthetic private keys."""
import json,subprocess,tempfile,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
def dc(*args):return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
prefix='originals/cost-'+uuid.uuid4().hex
setup='mc alias set local http://s3:9000 "$(cat /run/secrets/s3_root_user)" "$(cat /run/secrets/s3_root_password)" >/dev/null; '
results=[]
def measure(extra):
raw=dc('run','--rm','--no-deps','api','reconcile')
r=json.loads(raw.splitlines()[-1]);r['extra_synthetic_objects']=extra;results.append(r)
with tempfile.TemporaryDirectory(prefix='lab4-inventory-') as folder:
try:
measure(0)
for count in [100,1000]:
for i in range(count):(Path(folder)/str(i)).write_text('synthetic-inventory-only\n')
dc('run','--rm','--no-deps','--volume',folder+':/probe:ro','--entrypoint','/bin/sh','s3-init','-c',setup+'mc mirror --quiet /probe local/messenger-attachments/'+prefix+' >/dev/null')
measure(count)
finally:
dc('run','--rm','--no-deps','--entrypoint','/bin/sh','s3-init','-c',setup+'mc rm --recursive --force local/messenger-attachments/'+prefix+' >/dev/null')
assert all(r['deleted_objects']==0 and r['deleted_metadata']==0 for r in results)
(ROOT/'evidence/inventory-cost.json').write_text(json.dumps({'method':'same existing dataset plus 0/100/1000 fresh synthetic keys; dry-run; CLI API limits; no metadata mutation; temporary prefix removed','runs':results},indent=2)+'\n')
print('PASS: dry-run costs measured at +0/+100/+1000 keys, probe prefix removed')
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Stop each real container, then replace them in sequence under writes."""
import json,os,subprocess,sys,threading,time,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client,Failure,check
BASE=os.environ.get('BASE_URL','http://localhost:8084')
def dc(*args):return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
def inspect(id):return json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]
def ready():
deadline=time.monotonic()+45
while time.monotonic()<deadline:
try:
dc('up','-d','--no-deps','--wait','api');time.sleep(2);return
except subprocess.CalledProcessError:time.sleep(1)
raise AssertionError('API did not recover')
def run_phase(c,actor,chat,action,seconds=7):
results=[];failed=0;stop=threading.Event();events=[];seen=set()
def write():
nonlocal failed
client=Client(BASE,timeout=2);key=uuid.uuid4().hex
while not stop.is_set():
try:
response=client.message(actor,chat,'operation probe '+key,key=key)
results.append((time.monotonic(),response['json']['id']))
seen.add(response['headers']['X-Instance-Id']);key=uuid.uuid4().hex
except Failure:failed+=1
time.sleep(.02)
worker=threading.Thread(target=write);worker.start();time.sleep(1)
started=time.monotonic();action();action_done=time.monotonic();time.sleep(seconds);stop.set();worker.join()
history=[];path='/api/v1/chats/'+chat['id']+'/messages?limit=100'
from urllib.parse import quote
while True:
page=c.call('GET',path,actor=actor,schema='MessagePage')['json'];history+=page['items']
if page['next_cursor'] is None:break
path='/api/v1/chats/'+chat['id']+'/messages?limit=100&cursor='+quote(page['next_cursor'],safe='')
ids=[m['id'] for m in history];check(len(ids)==len(set(ids)),'duplicate IDs')
check({i for _,i in results}.issubset(set(ids)),'lost confirmed message')
successes_after=[t for t,_ in results if t>=action_done]
check(successes_after,'no successful write after action')
recovery=successes_after[0]-started
return {'successful_writes':len(results),'errors':failed,'successful_rps':len(results)/(time.monotonic()-started+1),'first_recovery_seconds':round(recovery,3),'action_seconds':round(action_done-started,3),'instances':sorted(seen),'confirmed_preserved':True}
def main():
ready();c=Client(BASE);a,b,e,chat=c.bootstrap();results={'failures':[]}
ids=dc('ps','-q','api').splitlines();check(len(ids)==2,'requires two API containers')
for id in ids:
alias=inspect(id)['Config']['Hostname']
env=dict(os.environ,TARGET_INSTANCE_ID=alias)
def action():subprocess.run([str(ROOT/'scripts/stop-one.sh')],env=env,check=True,stdout=subprocess.DEVNULL)
try:
result=run_phase(c,a,chat,action);result['stopped_alias']=alias
check(not inspect(id)['State']['Running'],'target is still running')
check(result['first_recovery_seconds']<10,'recovery >10s')
results['failures'].append(result)
finally:ready()
results['rolling']=run_phase(c,a,chat,lambda:subprocess.run([str(ROOT/'scripts/rolling.sh')],check=True,stdout=subprocess.DEVNULL),seconds=2)
check(len(dc('ps','-q','api').splitlines())==2,'rolling lost replicas')
(ROOT/'evidence/operations.json').write_text(json.dumps(results,indent=2)+'\n')
print('PASS: each API stopped and rolling replacement completed; confirmed writes preserved')
if __name__=='__main__':main()
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Prove the app S3 identity cannot manage users or modify bucket policy."""
import json,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
prefix='mc alias set app http://s3:9000 "$(cat /run/secrets/s3_access_key_id)" "$(cat /run/secrets/s3_secret_access_key)" >/dev/null; '
checks={}
try:
for name,command in [('admin_denied','mc admin info app'),('policy_change_denied','mc anonymous set download app/messenger-attachments')]:
r=subprocess.run(['docker','compose','run','--rm','--no-deps','--entrypoint','/bin/sh','s3-init','-c',prefix+command],cwd=ROOT,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
checks[name]=r.returncode!=0 and ('denied' in r.stdout.lower() or 'not allowed' in r.stdout.lower())
assert checks[name],name+' was unexpectedly permitted'
finally:
# Always re-apply private policy with the bootstrap identity, including failure.
subprocess.run(['docker','compose','run','--rm','--no-deps','s3-init'],cwd=ROOT,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
(ROOT/'evidence/permissions.json').write_text(json.dumps(checks,indent=2)+'\n');print('PASS: S3 application identity denied admin and bucket-policy changes')
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env python3
"""Small sanitized runtime manifest; no environment, passwords or tokens."""
import json,platform,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
ids=subprocess.check_output(['docker','compose','ps','-q'],cwd=ROOT,text=True).splitlines()
result={'platform':platform.platform(),'containers':[]}
for id in ids:
item=json.loads(subprocess.check_output(['docker','inspect',id],text=True))[0]
result['containers'].append({'service':item['Config']['Labels']['com.docker.compose.service'],'name':item['Name'],'alias':item['Config']['Hostname'],'image':item['Config']['Image'],'image_id':item['Image'],'user':item['Config']['User'],'pid1_path':item['Path'],'started_at':item['State']['StartedAt'],'memory_limit_bytes':item['HostConfig']['Memory'],'nano_cpus_limit':item['HostConfig']['NanoCpus'],'published_ports':item['NetworkSettings']['Ports'],'health':item['State'].get('Health',{}).get('Status'),'mount_targets':[m['Destination'] for m in item['Mounts']]})
result['postgres_durability']=subprocess.check_output(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atqc',"SELECT name||'='||setting FROM pg_settings WHERE name IN ('fsync','synchronous_commit','full_page_writes','max_connections') ORDER BY name"],cwd=ROOT,text=True).splitlines()
(ROOT/'evidence/runtime.json').write_text(json.dumps(result,indent=2)+'\n')
print('Saved sanitized runtime manifest: resources, images, PID1, ports, durability')