forked from mtusi2026/mtusi2026lab4
159 lines
7.8 KiB
Python
159 lines
7.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Black-box attachment tests. --faults explicitly stops/restarts only this Compose project."""
|
|
import argparse
|
|
import binascii
|
|
import json
|
|
from pathlib import Path
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
from urllib.parse import quote
|
|
import uuid
|
|
import zlib
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
from client import Client, check, run
|
|
|
|
|
|
def docker(*args):
|
|
return subprocess.check_output(['docker', 'compose', '--env-file', '.env', *args],
|
|
cwd=ROOT, stderr=subprocess.STDOUT, text=True)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--base-url', default='http://localhost:8080')
|
|
parser.add_argument('--faults', action='store_true')
|
|
args = parser.parse_args()
|
|
c = Client(args.base_url, timeout=20)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
path = '/api/v1/chats/' + chat['id']
|
|
png = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
|
|
|
def upload(raw=png, mime='image/png', name='sample.png', actor=alice, expected=201):
|
|
return c.call('POST', path+'/attachments?filename='+quote(name, safe=''), expected,
|
|
actor=actor, raw=raw, headers={'Content-Type': mime},
|
|
schema='Attachment' if expected == 201 else None)
|
|
|
|
uploaded = upload()
|
|
att = uploaded['json']
|
|
content_path = '/api/v1/attachments/'+att['id']+'/content'
|
|
check(att['status'] == 'ready' and att['variants'] == [] and att['error_code'] is None, 'invalid ready metadata')
|
|
check(c.call('GET', content_path, actor=bob)['bytes'] == png, 'original changed')
|
|
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)
|
|
upload(actor=eve, expected=404)
|
|
c.call('POST', path+'/attachments?filename=sample.png', 401, raw=png,
|
|
headers={'Content-Type': 'image/png'})
|
|
c.call('GET', content_path+'?variant=thumbnail', 404, actor=bob)
|
|
check(c.call('GET', content_path+'?variant=original', actor=bob)['bytes'] == png, 'original variant changed')
|
|
print('PASS: ready metadata, original bytes, authentication and chat ACL.')
|
|
|
|
jpeg = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes()
|
|
jpg_att = upload(jpeg, 'image/jpeg', 'sample.jpg')['json']
|
|
check(c.call('GET', '/api/v1/attachments/'+jpg_att['id']+'/content', actor=bob)['bytes'] == jpeg, 'JPEG changed')
|
|
upload(png, 'image/jpeg', expected=415)
|
|
upload(jpeg, 'image/png', expected=415)
|
|
upload(b'not an image', expected=415)
|
|
upload(b'', expected=415)
|
|
upload(png[:40], expected=415)
|
|
damaged = bytearray(png)
|
|
damaged[len(damaged)//2] ^= 1
|
|
upload(bytes(damaged), expected=415)
|
|
upload(jpeg[:-2], 'image/jpeg', expected=415)
|
|
upload(mime='application/octet-stream', expected=415)
|
|
for name in ('../x.png', 'x\\y.png', 'x\x00.png', 'x\n.png', '', 'a'*256):
|
|
upload(name=name, expected=400)
|
|
upload(b'x'*(10485760+1), expected=413)
|
|
|
|
def chunk(kind, data):
|
|
return struct.pack('>I', len(data))+kind+data+struct.pack('>I', binascii.crc32(kind+data)&0xffffffff)
|
|
huge = b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR', struct.pack('>IIBBBBB',10000,10000,8,2,0,0,0))
|
|
huge += chunk(b'IDAT',zlib.compress(b''))+chunk(b'IEND',b'')
|
|
upload(huge, expected=413)
|
|
bomb = b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',8,8,8,2,0,0,0))
|
|
bomb += chunk(b'IDAT',zlib.compress(b'\0'*(1024*1024)))+chunk(b'IEND',b'')
|
|
upload(bomb, expected=415)
|
|
print('PASS: PNG/JPEG, MIME spoofing, damaged files, filenames, byte and pixel limits.')
|
|
|
|
key = uuid.uuid4().hex
|
|
msg = c.message(bob, chat, '', key=key, attachments=[att['id']])['json']
|
|
check(c.message(bob, chat, '', key=key, attachments=[att['id']])['json'] == msg, 'replay changed')
|
|
c.call('POST',path+'/messages',409,actor=bob,body={'text':'','attachment_ids':[jpg_att['id']]},headers={'Idempotency-Key':key})
|
|
for ids, expected in (([att['id']]*2,400), ([att['id']]*11,400), ([str(uuid.uuid4())],404)):
|
|
c.call('POST',path+'/messages',expected,actor=alice,body={'text':'','attachment_ids':ids},headers={'Idempotency-Key':uuid.uuid4().hex})
|
|
another = c.call('POST','/api/v1/chats',201,actor=alice,
|
|
body={'title':'Another','member_ids':[alice['id']]},schema='Chat')['json']
|
|
c.call('POST','/api/v1/chats/'+another['id']+'/messages',404,actor=alice,
|
|
body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
|
items = c.call('GET',path+'/messages',actor=alice,schema='MessagePage')['json']['items']
|
|
check(msg in items, 'attachment message missing from history')
|
|
print('PASS: attachment-only messages, other uploader in same chat, idempotency and foreign attachment rejection.')
|
|
|
|
if not args.faults:
|
|
return
|
|
|
|
def wait_ready():
|
|
deadline = time.monotonic()+60
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
c.call('GET','/health/ready',schema='Health')
|
|
return
|
|
except AssertionError:
|
|
time.sleep(.5)
|
|
raise AssertionError('API did not recover')
|
|
|
|
instances = {c.call('GET',content_path,actor=bob)['headers']['X-Instance-Id'] for _ in range(12)}
|
|
check(len(instances)>=2, 'two replicas not observed')
|
|
target = uploaded['headers']['X-Instance-Id']
|
|
containers = docker('ps','-q','api').split()
|
|
matching = [cid for cid in containers if cid.startswith(target)]
|
|
check(len(matching)==1, 'uploading container not found')
|
|
target_id = matching[0]
|
|
try:
|
|
subprocess.check_output(['docker','stop','--time','5',target_id],stderr=subprocess.STDOUT)
|
|
downloaded = c.call('GET',content_path,actor=bob)
|
|
check(downloaded['bytes']==png and downloaded['headers']['X-Instance-Id']!=target, 'failover lost attachment')
|
|
print('PASS: stopping the uploading API replica preserves the file on another replica.')
|
|
finally:
|
|
subprocess.check_output(['docker','start',target_id],stderr=subprocess.STDOUT)
|
|
wait_ready()
|
|
try:
|
|
docker('stop','s3')
|
|
time.sleep(3)
|
|
try:
|
|
urllib.request.urlopen(args.base_url+'/health/ready',timeout=10)
|
|
raise AssertionError('S3 outage left readiness healthy')
|
|
except urllib.error.HTTPError as ex:
|
|
check(ex.code==503,'S3 outage must give 503')
|
|
for method, url, data in [('GET', content_path, None), ('POST',path+'/attachments?filename=outage.png',png)]:
|
|
request = urllib.request.Request(args.base_url+url,data=data,method=method,
|
|
headers={'Authorization':'Bearer '+alice['token'],'Content-Type':'image/png'})
|
|
try:
|
|
urllib.request.urlopen(request,timeout=10)
|
|
raise AssertionError('S3 outage unexpectedly served attachment')
|
|
except urllib.error.HTTPError as ex:
|
|
check(ex.code==503,'attachment route during S3 outage must give 503')
|
|
print('PASS: S3 outage makes readiness unavailable (503).')
|
|
finally:
|
|
docker('start','s3')
|
|
wait_ready()
|
|
check(c.call('GET',content_path,actor=bob)['bytes']==png, 'S3 restart lost file')
|
|
docker('restart','db','cache','s3','api','lb')
|
|
wait_ready()
|
|
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
|
check(c.call('GET',content_path,actor=bob)['bytes']==png,'stack restart lost original')
|
|
c.call('GET','/api/v1/attachments/'+att['id'],actor=bob,schema='Attachment')
|
|
items = c.call('GET',path+'/messages',actor=bob,schema='MessagePage')['json']['items']
|
|
check(msg in items,'stack restart lost attachment message')
|
|
print('PASS: restarting DB, cache, S3, API and LB preserves sessions, metadata, messages and original bytes.')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
run(main)
|