forked from mtusi2026/mtusi2026lab4
feat(lab4): private S3 attachments and safe storage reconciliation
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
"""Additional contract, image, concurrency and private-bucket tests; run inside api1."""
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
from client import Client, check
|
||||
from PIL import Image
|
||||
from src.storage import BUCKET, db, s3
|
||||
|
||||
|
||||
def main():
|
||||
c = Client('http://lb:8080',timeout=30)
|
||||
alice,bob,eve,chat = c.bootstrap()
|
||||
path = '/api/v1/chats/'+chat['id']
|
||||
fixture = Path('tests/fixtures/sample.png').read_bytes()
|
||||
def upload(raw=fixture,mime='image/png',filename='photo.png',expected=201):
|
||||
return c.call('POST',path+'/attachments?filename='+filename,expected,actor=alice,
|
||||
raw=raw,headers={'Content-Type':mime},schema='Attachment' if expected==201 else None)
|
||||
upload(raw=b'broken',expected=415)
|
||||
upload(mime='image/jpeg',expected=415)
|
||||
upload(filename='..%2Fsecret.png',expected=400)
|
||||
upload(filename='bad%00.png',expected=400)
|
||||
upload(raw=b'x'*(10485760+1),expected=413)
|
||||
out = io.BytesIO()
|
||||
Image.new('RGB',(7000,6000)).save(out,format='PNG')
|
||||
upload(raw=out.getvalue(),expected=413)
|
||||
out = io.BytesIO()
|
||||
Image.new('RGB',(40,30)).save(out,format='JPEG')
|
||||
jpeg = upload(raw=out.getvalue(),mime='image/jpeg')['json']
|
||||
check(c.call('GET','/api/v1/attachments/'+jpeg['id']+'/content',actor=bob)['bytes']==out.getvalue(),'JPEG changed')
|
||||
att = upload()['json']
|
||||
c.call('GET','/api/v1/attachments/'+att['id'],404,actor=eve)
|
||||
other = c.call('POST','/api/v1/chats',201,actor=alice,
|
||||
body={'title':'other','member_ids':[alice['id']]},schema='Chat')['json']
|
||||
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=alice,
|
||||
body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
c.call('POST',path+'/messages',404,actor=alice,
|
||||
body={'text':'','attachment_ids':[str(uuid.uuid4())]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
c.call('POST',path+'/messages',400,actor=alice,body={'text':'x','sender_id':eve['id']})
|
||||
c.call('GET','/api/v1/chats/not-a-uuid',400,actor=alice)
|
||||
c.call('GET',path+'/messages?cursor=invalid',400,actor=alice)
|
||||
m1 = c.message(alice,chat,'one')['json']
|
||||
c.message(alice,chat,'two')
|
||||
cursor = c.call('GET',path+'/messages?limit=1',actor=alice,schema='MessagePage')['json']['next_cursor']
|
||||
c.call('GET','/api/v1/chats/'+other['id']+'/messages?cursor='+cursor,400,actor=alice)
|
||||
key = uuid.uuid4().hex
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
|
||||
rows = list(pool.map(lambda _:c.message(alice,chat,'same',key=key)['json'],range(12)))
|
||||
check(len({r['id'] for r in rows})==1,'concurrent duplicate message')
|
||||
c.call('POST',path+'/messages',201,actor=alice,body={'attachment_ids':[],'text':'same'},
|
||||
headers={'Idempotency-Key':key},schema='Message')
|
||||
with db() as con:
|
||||
objkey = con.execute('SELECT object_key FROM attachments WHERE id=%s',(att['id'],)).fetchone()['object_key']
|
||||
before = con.execute('SELECT count(*) n FROM attachments').fetchone()['n']
|
||||
try:
|
||||
urllib.request.urlopen('http://s3:9000/'+BUCKET+'/'+objkey)
|
||||
except urllib.error.HTTPError as exc:
|
||||
check(exc.code==403,'unexpected anonymous S3 status')
|
||||
else:
|
||||
raise AssertionError('bucket public')
|
||||
try:
|
||||
s3().create_bucket(Bucket='forbidden-'+uuid.uuid4().hex)
|
||||
except Exception as exc:
|
||||
check(getattr(exc,'response',{}).get('Error',{}).get('Code')=='AccessDenied','scope test failed')
|
||||
else:
|
||||
raise AssertionError('application has admin S3 rights')
|
||||
# Abandon binary request before declared end; it must never reach PUT.
|
||||
sock = socket.create_connection(('api2',8080))
|
||||
headers = ('POST '+path+'/attachments?filename=partial.png HTTP/1.1\r\nHost: api2\r\n'
|
||||
'Authorization: Bearer '+alice['token']+'\r\nContent-Type: image/png\r\n'
|
||||
'Content-Length: 100000\r\n\r\n').encode()
|
||||
sock.sendall(headers+fixture[:80])
|
||||
sock.close()
|
||||
time.sleep(1)
|
||||
with db() as con:
|
||||
check(con.execute('SELECT count(*) n FROM attachments').fetchone()['n']==before,'partial upload committed')
|
||||
print(json.dumps({'result':'PASS','negative_image_and_acl':True,'private_bucket_status':403,
|
||||
'scoped_credentials':True,'parallel_idempotency_requests':12,
|
||||
'unique_messages':1,'interrupted_upload_no_metadata':True}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user