#!/usr/bin/env python3 """Real S3/API negative cases and failures; only synthetic lab data.""" import hashlib import http.client import json import os from pathlib import Path import subprocess import time import uuid from urllib.parse import urlsplit from helpers import Client, Probe, ROOT, STACK, check, containers, docker, png, oversized_dimensions, save, sql, upload, wait_ready def main(): c = Client(timeout=55) alice, bob, eve, chat = c.bootstrap() data = png() result = {'negative_cases': [], 'failures': {}, 'checksums': {}} for name, body, mime, filename, status in ( ('oversized_bytes', b'x'*(10*1024*1024+1), 'image/png', 'large.png', 413), ('damaged_png', data[:50], 'image/png', 'broken.png', 415), ('corrupt_crc', data[:-16]+b'\xff'*16, 'image/png', 'crc.png', 415), ('mime_spoof', data, 'image/jpeg', 'fake.jpg', 415), ('not_image', b'plain text', 'image/png', 'fake.png', 415), ('unsupported_mime', data, 'application/octet-stream', 'file.png', 415), ('pixel_budget', oversized_dimensions(), 'image/png', 'large-dimensions.png', 413), ('unsafe_slash', data, 'image/png', '../file.png', 400), ('unsafe_backslash', data, 'image/png', 'x\\y.png', 400), ('unsafe_control', data, 'image/png', 'x\x00.png', 400), ('empty_filename', data, 'image/png', '', 400), ): upload(c, alice, chat, body, filename, mime, status) result['negative_cases'].append({'case': name, 'status': status}) for content, filename, mime in ((data, 'изображение.png', 'image/png'), ((ROOT/'tests/own/fixtures/sample.jpg').read_bytes(), 'photo.jpg', 'image/jpeg')): att = upload(c, alice, chat, content, filename, mime)['json'] downloaded = c.call('GET', '/api/v1/attachments/'+att['id']+'/content', actor=bob) check(downloaded['bytes'] == content, 'original bytes changed') check(att['sha256'] == hashlib.sha256(content).hexdigest(), 'incorrect SHA256') check(downloaded['headers'].get_content_type() == mime, 'incorrect content MIME') result['checksums'][mime] = att['sha256'] att = upload(c, alice, chat, data)['json'] 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) c.call('GET', '/api/v1/attachments/'+att['id']+suffix, 401) upload(c, eve, chat, data, expected=404) c.call('GET', '/api/v1/attachments/'+att['id']+'/content?variant=thumbnail', 404, actor=bob) other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title':'other chat', 'member_ids':[alice['id'], bob['id']]}, schema='Chat')['json'] path = '/api/v1/chats/'+other['id']+'/messages' for ids, status in (([att['id']], 404), ([str(uuid.uuid4())], 404), ([att['id'],att['id']], 400)): c.call('POST', path, status, actor=alice, body={'text':'', 'attachment_ids':ids}, headers={'Idempotency-Key':uuid.uuid4().hex}) result['negative_cases'] += [{'case': x, 'status': s} for x,s in ( ('foreign_attachment',404), ('foreign_chat_link',404), ('unknown_attachment',404), ('duplicate_ids',400), ('missing_authentication',401), ('unknown_variant',404))] # The proxy must stop oversized chunked bodies even without Content-Length. address = urlsplit(c.base) conn = http.client.HTTPConnection(address.hostname, address.port, timeout=55) conn.request('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename=chunked.png', body=iter([b'x'*65536]*161), encode_chunked=True, headers={'Authorization':'Bearer '+alice['token'], 'Content-Type':'image/png'}) response = conn.getresponse() check(response.status == 413, 'chunked upload bypassed byte limit') response.read(); conn.close() result['negative_cases'].append({'case':'chunked_oversized', 'status':413}) # Disconnect halfway through the declared body. No object/metadata can be published. before = int(sql('SELECT count(*) FROM attachments;')) conn = http.client.HTTPConnection(address.hostname, address.port, timeout=5) conn.putrequest('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename=aborted.png') conn.putheader('Authorization', 'Bearer '+alice['token']) conn.putheader('Content-Type', 'image/png') conn.putheader('Content-Length', str(len(data)+10000)) conn.endheaders(); conn.send(data[:40]); conn.close() time.sleep(1) check(int(sql('SELECT count(*) FROM attachments;')) == before, 'aborted upload published metadata') leftovers = [docker('exec', container, 'find', '/tmp', '-maxdepth', '1', '-name', 'messenger-upload-*').stdout.decode() for container in containers('api')] check(not any(leftovers), 'aborted upload left spool files') result['failures']['client_disconnect'] = {'metadata_added':0, 'spool_files_remaining':0} with Probe() as probe: key = sql("SELECT object_key FROM attachments WHERE id='"+att['id']+"';") raw = docker('exec', containers('minio')[0], 'wget', '-S', '-O', '/dev/null', 'http://127.0.0.1:9000/attachments/'+key, check_result=False) check(b'403' in raw.stderr, 'unauthenticated direct S3 GET was not forbidden') probe.mc('stat', 'local/attachments/'+key) probe.mc('mb', 'local/forbidden-'+uuid.uuid4().hex[:8], expected=1) probe.mc('pipe', 'local/attachments/outside-prefix', data=b'x', expected=1) result['bucket_security'] = {'anonymous_get_status':403, 'create_bucket_denied':True, 'write_outside_prefix_denied':True, 'console_published':False} service = json.loads(docker('service', 'inspect', STACK+'_minio').stdout)[0] check(not service['Spec'].get('EndpointSpec', {}).get('Ports'), 'MinIO publishes an external port') for _ in range(2): subprocess.run(['python3', str(ROOT/'scripts/swarm.py'), 'bootstrap-s3'], check=True, stdout=subprocess.DEVNULL) check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==data, 'repeated bucket bootstrap changed data') result['bucket_security']['bootstrap_repeats'] = 2 # Stop the replica that accepted THIS upload, then read through another one. accepted = upload(c,alice,chat,data) source = accepted['headers']['X-Instance-Id'] env = dict(os.environ, TARGET_INSTANCE_ID=source) started = time.monotonic() subprocess.run(['python3',str(ROOT/'scripts/swarm.py'),'stop-one'],env=env,check=True, stdout=subprocess.DEVNULL) deadline = time.monotonic()+10 while True: try: downloaded = Client(timeout=2).call('GET','/api/v1/attachments/'+accepted['json']['id']+'/content',actor=bob) check(downloaded['headers']['X-Instance-Id']!=source,'stopped upload replica still serves bytes') check(downloaded['bytes']==data,'cross-replica original changed') break except AssertionError: check(time.monotonic()