Files
mtusi2026lab4/tests/attachments_negative.py
T
2026-11-06 17:03:03 +03:00

64 lines
3.9 KiB
Python
Executable File

#!/usr/bin/env python3
"""Negative attachment authorization and validation checks against a running lab4 API."""
from urllib.parse import quote, urlsplit
from client import Client, LAB, arguments, check, run
from pathlib import Path
from uuid import uuid4
import http.client, json, ssl, struct, zlib
def check_oversize_rejected(base_url, actor, path):
parts=urlsplit(base_url or 'http://localhost:8080')
conn_cls=http.client.HTTPSConnection if parts.scheme=='https' else http.client.HTTPConnection
kwargs={'timeout':120}
if parts.scheme=='https': kwargs['context']=ssl.create_default_context()
conn=conn_cls(parts.hostname,parts.port,**kwargs)
target=path
conn.putrequest('POST',target)
conn.putheader('Host',parts.netloc)
conn.putheader('Accept','application/json')
conn.putheader('Authorization','Bearer '+actor['token'])
conn.putheader('Content-Type','image/png')
conn.putheader('Content-Length',str(10485761))
conn.putheader('Connection','close')
conn.endheaders()
response=conn.getresponse(); payload=json.loads(response.read())
check(response.status==413,'10 MiB plus one byte was not rejected with 413')
check(response.getheader('X-Request-Id')==payload['error']['request_id'],'oversize response request_id mismatch')
conn.close()
def pixel_limit_fixture(width=6401,height=6401):
def chunk(tag,data): return struct.pack('>I',len(data))+tag+data+struct.pack('>I',zlib.crc32(tag+data)&0xffffffff)
encoder=zlib.compressobj(1); compressed=bytearray(); row=b'\0'+bytes(width*3)
for _ in range(height): compressed.extend(encoder.compress(row))
compressed.extend(encoder.flush())
header=struct.pack('>IIBBBBB',width,height,8,2,0,0,0)
return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',header)+chunk(b'IDAT',compressed)+chunk(b'IEND',b'')
def main():
a=arguments('Attachment negative checks; creates synthetic users, chats, messages')
check(LAB==4,'this scenario targets synchronous lab4 attachments')
c=Client(a.base_url,a.ca_file,timeout=120); alice,bob,eve,chat=c.bootstrap()
base='/api/v1/chats/'+chat['id']+'/attachments?filename='
c.call('POST',base+quote('../bad.png'),400,actor=alice,raw=b'bad',headers={'Content-Type':'image/png'})
fixture=(Path(__file__).parent/'fixtures/sample.png').read_bytes()
for content,mime,expected,label in [(b'not an image','image/png',415,'corrupt bytes'),(fixture,'image/jpeg',415,'spoofed MIME')]:
print('checking '+label,flush=True)
r=c.call('POST',base+quote('bad.png'),expected,actor=alice,raw=content,headers={'Content-Type':mime})
print('checking too large',flush=True)
check_oversize_rejected(a.base_url,alice,base+quote('bad.png'))
print('checking too many pixels',flush=True)
c.call('POST',base+quote('bad.png'),413,actor=alice,raw=pixel_limit_fixture(),headers={'Content-Type':'image/png'})
# Upload real file, then verify outsider and wrong-chat references are hidden.
print('uploading valid image',flush=True)
att=c.call('POST',base+quote('sample.png'),201,actor=alice,raw=fixture,headers={'Content-Type':'image/png'},schema='Attachment')['json']
jpeg=(Path(__file__).parent/'fixtures/sample.jpg').read_bytes()
jpeg_att=c.call('POST',base+quote('sample.jpg'),201,actor=alice,raw=jpeg,headers={'Content-Type':'image/jpeg'},schema='Attachment')['json']
downloaded=c.call('GET','/api/v1/attachments/'+jpeg_att['id']+'/content',actor=bob)
check(downloaded['bytes']==jpeg and jpeg_att['content_type']=='image/jpeg','real JPEG round-trip mismatch')
c.call('GET','/api/v1/attachments/'+att['id'],404,actor=eve)
c.call('GET','/api/v1/attachments/'+att['id']+'/content',404,actor=eve)
other=c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Другой чат','member_ids':[alice['id'],bob['id']]},schema='Chat')['json']
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=bob,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid4().hex})
print('PASS: real PNG/JPEG, pixel/byte limits, corrupt image, MIME spoof, outsider access, and cross-chat binding checked')
if __name__=='__main__': run(main)