"""Extra black-box, failure and reconciliation checks; no public tests modified.""" import concurrent.futures as cf import hashlib import io import json import os from pathlib import Path import socket import struct import sys import time import urllib.error import urllib.request import uuid import zlib 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 botocore.exceptions import ClientError from src.storage import BUCKET, PREFIX, STORAGE_LOCK, db, s3, setting from src.reconcile import reconcile def png(width,height): def chunk(kind,content): return struct.pack('!I',len(content))+kind+content+struct.pack('!I',zlib.crc32(kind+content)) 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\0\0\0'))+chunk(b'IEND',b'') def main(): c = Client('http://lb:8080',timeout=40) a,b,e,chat = c.bootstrap() content = (Path('tests/fixtures/sample.png')).read_bytes() path = '/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png' def upload(raw=content,mime='image/png',expected=201,actor=a,url=path,client=c): return client.call('POST',url,expected,actor=actor,raw=raw, headers={'Content-Type':mime},schema='Attachment' if expected==201 else None) for label,raw,mime,expected in ( ('oversize',b'x'*(10485760+1),'image/png',413), ('corrupt',b'not an image','image/png',415), ('truncated_png',content[:70],'image/png',415), ('mime_mismatch',content,'image/jpeg',415), ('pixel_limit',png(10000,5000),'image/png',413)): upload(raw,mime,expected) for name in ('..%2Fx.png','..%5Cx.png','a%00.png','a%0A.png'): upload(expected=400,url=path.split('?')[0]+'?filename='+name) # No Content-Length: the limit is enforced while receiving chunked transfer. upload(raw=(b'x'*65536 for _ in range(161)),expected=413) jpeg = io.BytesIO() Image.new('RGB',(64,48),(10,30,80)).save(jpeg,format='JPEG') jpeg_bytes = jpeg.getvalue() jpeg_att = upload(jpeg_bytes,'image/jpeg')['json'] check(c.call('GET','/api/v1/attachments/'+jpeg_att['id']+'/content',actor=b)['bytes']==jpeg_bytes,'JPEG byte mismatch') upload(jpeg_bytes[:-20],'image/jpeg',415) att = upload()['json'] upload(actor=e,expected=404) 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':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex}) c.call('POST','/api/v1/chats/'+chat['id']+'/messages',404,actor=a, body={'text':'','attachment_ids':[str(uuid.uuid4())]},headers={'Idempotency-Key':uuid.uuid4().hex}) c.call('POST','/api/v1/chats/'+chat['id']+'/messages',404,actor=e, body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex}) # Concurrent same-key requests distributed across two real API processes. key = uuid.uuid4().hex with cf.ThreadPoolExecutor(max_workers=12) as executor: replies = list(executor.map(lambda _: c.message(a,chat,'race',key=key),range(12))) check(len({r['json']['id'] for r in replies})==1,'idempotency race duplicated message') check(len({r['headers']['X-Instance-Id'] for r in replies})==2,'race did not cross replicas') cid = replies[0]['json']['id'] c.call('POST','/api/v1/chats/'+chat['id']+'/messages',201,actor=a, body={'attachment_ids':[],'text':'race'},headers={'Idempotency-Key':key},schema='Message') for value in ({'text':123},{'text':'a','sender_id':a['id']}, {'text':'a','attachment_ids':[att['id'],att['id']]}): c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400,actor=a, body=value,headers={'Idempotency-Key':uuid.uuid4().hex}) c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400,actor=a, raw=b'{"text":"\\ud800"}',headers={'Content-Type':'application/json','Idempotency-Key':uuid.uuid4().hex}) c.call('GET','/api/v1/attachments/invalid-uuid',400,actor=a) c.call('GET','/api/v1/attachments/invalid-uuid',401) # Private bucket and application IAM tested from inside isolated network. with db() as conn: row = conn.execute('SELECT * FROM attachments WHERE id=%s',(att['id'],)).fetchone() url = 'http://s3:9000/'+BUCKET+'/'+row['object_key'] try: urllib.request.urlopen(url) raise AssertionError('Anonymous bucket access succeeded') except urllib.error.HTTPError as exc: check(exc.code==403,'private bucket must deny anonymous GET') try: s3().delete_object(Bucket=BUCKET,Key=row['object_key']) raise AssertionError('API user can delete objects') except ClientError as exc: check(exc.response['Error']['Code']=='AccessDenied','unexpected IAM error') try: s3().put_object(Bucket=BUCKET,Key='outside-prefix',Body=b'no') raise AssertionError('API user can write outside prefix') except ClientError as exc: check(exc.response['Error']['Code']=='AccessDenied','prefix IAM denial expected') # Disconnect before completing body: no object or metadata is persisted. with db() as conn: before = conn.execute('SELECT count(*) AS n FROM attachments').fetchone()['n'] sock = socket.create_connection(('api1',8080)) req = ('POST '+path+' HTTP/1.1\r\nHost: api1\r\nAuthorization: Bearer '+a['token']+ '\r\nContent-Type: image/png\r\nContent-Length: 100000\r\n\r\n').encode()+content[:20] sock.sendall(req) sock.close() time.sleep(.5) with db() as conn: check(conn.execute('SELECT count(*) AS n FROM attachments').fetchone()['n']==before,'disconnect persisted attachment') print(json.dumps({'status':'PASS','negative_cases':21,'jpeg_roundtrip':True, 'idempotency_concurrency':12,'idempotency_instances':2,'private_bucket':True, 'api_delete_denied':True,'prefix_write_denied':True,'interrupted_upload':True})) if __name__ == '__main__': main()