Files
mtusi2026lab4-fork/student-tests/attachments.py
T

85 lines
4.6 KiB
Python

"""Black-box validation of attachment security and message compatibility."""
import concurrent.futures
import hashlib
import json
import struct
import urllib.parse
import uuid
import zlib
from common import ROOT, Client, check, save
def chunk(kind, data):
return struct.pack('!I',len(data))+kind+data+struct.pack('!I',zlib.crc32(kind+data)&0xffffffff)
def png(width=32, height=32):
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((b'\0'+bytes([43,100,201])*width)*height))+chunk(b'IEND',b''))
def main():
c=Client(timeout=40)
alice,bob,eve,chat=c.bootstrap()
path='/api/v1/chats/'+chat['id']
payload=(ROOT/'tests/fixtures/sample.png').read_bytes()
passed=[]
def upload(data, status, name='image.png', mime='image/png', actor=alice):
result=c.call('POST',path+'/attachments?filename='+urllib.parse.quote(name,safe=''),status,
actor=actor,raw=data,headers={'Content-Type':mime},schema='Attachment' if status==201 else None)
return result
upload(b'x'*(10485760+1),413);passed.append('byte limit before decode')
upload(b'not an image',415)
upload(payload[:40],415)
upload(payload,415,mime='image/jpeg')
upload(payload,415,mime='text/plain')
upload(b'',415);passed.append('corrupt, empty, MIME spoof')
# Valid header with impossible dimensions: rejection precedes allocation.
huge=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!IIBBBBB',40000001,1,8,2,0,0,0))
upload(huge,413);passed.append('pixel limit before full decode')
for name in ('../a.png','a/b.png','a\\b.png','x\x00.png','x\n.png','x\x7f.png',' '*4,'a'*256):
upload(payload,400,name=name)
passed.append('unsafe filename')
upload(payload,404,actor=eve)
c.call('POST',path+'/attachments?filename=a.png',401,raw=payload,headers={'Content-Type':'image/png'})
att=upload(payload,201,name='Фотография 😀.png')['json']
check(att['sha256']==hashlib.sha256(payload).hexdigest(),'bad original hash')
for suffix in ('','/content'):
c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=eve)
c.call('GET','/api/v1/attachments/'+str(uuid.uuid4())+suffix,404,actor=alice)
foreign=c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'other','member_ids':[alice['id'],bob['id']]},schema='Chat')['json']
c.call('POST','/api/v1/chats/'+foreign['id']+'/messages',404,actor=alice,
body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
passed.append('foreign attachment and chat ACL')
for body in ({'text':'','attachment_ids':[att['id'],att['id']]},
{'text':'','attachment_ids':None}, {'text':'x','attachment_ids':['not-uuid']},
{'text':'x','sender_id':eve['id']}, {'text':' '}):
c.call('POST',path+'/messages',400,actor=alice,body=body,headers={'Idempotency-Key':uuid.uuid4().hex})
key=uuid.uuid4().hex
first=c.message(alice,chat,'',key,[att['id']])['json']
repeat=c.message(alice,chat,'',key,[att['id']])['json']
check(first==repeat,'attachment message replay changed')
c.call('POST',path+'/messages',409,actor=alice,body={'text':'changed','attachment_ids':[att['id']]},headers={'Idempotency-Key':key})
key=uuid.uuid4().hex
plain=c.message(alice,chat,'text only',key)['json']
check(plain==c.message(alice,chat,'text only',key,[])['json'],'omitted != empty attachment_ids')
key=uuid.uuid4().hex
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
messages=list(pool.map(lambda _:Client().message(alice,chat,'concurrent',key,[att['id']])['json'],range(12)))
check(len({m['id'] for m in messages})==1,'concurrent idempotency created duplicates')
response=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)
check(response['bytes']==payload,'download changed bytes')
check(response['headers'].get_content_type()=='image/png','wrong download MIME')
c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=thumbnail',404,actor=alice)
passed.append('attachment-only, text-only, replay, concurrent replay, exact download')
jpeg=(ROOT/'student-tests/fixtures/sample.jpg').read_bytes()
item=upload(jpeg,201,name='valid.jpg',mime='image/jpeg')['json']
check(c.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=bob)['bytes']==jpeg,'JPEG changed')
passed.append('real JPEG exact download')
save('attachments.json',{'complete':True,'passed':passed})
print('PASS attachment validation, ACL and compatibility')
if __name__=='__main__':
main()