forked from mtusi2026/mtusi2026lab4
54 lines
4.2 KiB
Python
54 lines
4.2 KiB
Python
#!/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()
|