105 lines
6.3 KiB
Python
105 lines
6.3 KiB
Python
"""Black-box grade 4 checks; public tests stay untouched. Standard library only."""
|
|
import hashlib
|
|
import http.client
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import socket
|
|
import struct
|
|
import sys
|
|
import time
|
|
import uuid
|
|
import zlib
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from urllib.parse import quote, urlsplit
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
|
from client import Client, check
|
|
|
|
|
|
def png(width, height, pixels=None):
|
|
def chunk(kind, data):
|
|
return struct.pack('!I', len(data)) + kind + data + struct.pack('!I', zlib.crc32(kind + data))
|
|
raw = pixels if pixels is not None else b'\0' * ((width * 3 + 1) * height)
|
|
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(raw)) + chunk(b'IEND', b'')
|
|
|
|
|
|
def main():
|
|
c = Client(os.getenv('BASE_URL', 'http://localhost:8084'), timeout=45)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
base = '/api/v1/chats/' + chat['id']
|
|
path = base + '/attachments?filename='
|
|
image = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
|
passed = []
|
|
def upload(name, data, status, mime='image/png'):
|
|
return c.call('POST', path + quote(name, safe=''), status, actor=alice, raw=data, headers={'Content-Type': mime}, schema='Attachment' if status == 201 else None)
|
|
cases = [('bytes_over_10MiB', 'large.png', b'x' * (10485760 + 1), 413, 'image/png'),
|
|
('pixels_over_40M', 'bomb.png', png(40000001, 1, b'\0'), 413, 'image/png'),
|
|
('broken_png', 'broken.png', image[:70], 415, 'image/png'),
|
|
('broken_jpeg', 'broken.jpg', b'\xff\xd8\xff\xe0truncated', 415, 'image/jpeg'),
|
|
('mime_mismatch', 'wrong.jpg', image, 415, 'image/jpeg'),
|
|
('invalid_format', 'bad.png', b'plain text', 415, 'image/png'),
|
|
('multipart_rejected', 'bad.png', image, 415, 'multipart/form-data')]
|
|
for name, filename, data, status, mime in cases:
|
|
upload(filename, data, status, mime)
|
|
passed.append(name)
|
|
for filename in ('../x.png', 'x\\y.png', 'x\0.png', 'x\n.png', '\x7f.png', '', 'x' * 256):
|
|
upload(filename, image, 400)
|
|
passed.append('dangerous_filenames')
|
|
att, data = c.attachment(alice, chat)
|
|
for actor in (alice, bob):
|
|
got = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=actor)['bytes']
|
|
check(hashlib.sha256(got).hexdigest() == att['sha256'] and got == data, 'checksum mismatch')
|
|
passed.append('original_checksum_and_shared_access')
|
|
jpeg = (Path(__file__).resolve().parent / 'fixtures/sample.jpg').read_bytes()
|
|
jpeg_att = upload('original.jpg', jpeg, 201, 'image/jpeg')['json']
|
|
downloaded = c.call('GET', '/api/v1/attachments/' + jpeg_att['id'] + '/content', actor=bob)
|
|
check(downloaded['bytes'] == jpeg and downloaded['headers'].get_content_type() == 'image/jpeg', 'JPEG original changed')
|
|
check(jpeg_att['sha256'] == hashlib.sha256(jpeg).hexdigest(), 'JPEG checksum mismatch')
|
|
passed.append('JPEG_success_and_checksum')
|
|
for suffix in ('', '/content'):
|
|
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 401)
|
|
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)
|
|
passed.append('download_auth_and_acl')
|
|
other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
|
foreign = c.call('POST', '/api/v1/chats', 201, actor=eve, body={'title': 'private', 'member_ids': [eve['id']]}, schema='Chat')['json']
|
|
foreign_att, _ = c.attachment(eve, foreign)
|
|
for ids in ([str(uuid.uuid4())], [foreign_att['id']]):
|
|
c.call('POST', base + '/messages', 404, actor=alice, body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
|
c.call('POST', '/api/v1/chats/' + other['id'] + '/messages', 404, actor=alice, body={'text': '', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
|
passed.append('unknown_foreign_and_other_chat_attachment')
|
|
for ids in ([att['id']] * 2, [str(uuid.uuid4()) for _ in range(11)], 'invalid', [None]):
|
|
c.call('POST', base + '/messages', 400, actor=alice, body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
|
passed.append('attachment_id_validation')
|
|
key = uuid.uuid4().hex
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
messages = list(pool.map(lambda _: Client(c.base, timeout=30).message(alice, chat, '', key=key, attachments=[att['id']])['json'], range(10)))
|
|
check(all(x == messages[0] for x in messages), 'concurrent replay differs')
|
|
c.call('POST', base + '/messages', 409, actor=alice, body={'text': 'changed', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': key})
|
|
key = uuid.uuid4().hex
|
|
first = c.message(alice, chat, 'old text', key=key)['json']
|
|
check(first == c.message(alice, chat, 'old text', key=key, attachments=[])['json'], 'default [] differs')
|
|
passed.append('attachment_idempotency_across_replicas')
|
|
# Actual chunked request without Content-Length exercises incremental byte limit.
|
|
url = urlsplit(c.base)
|
|
con = http.client.HTTPConnection(url.hostname, url.port, timeout=30)
|
|
con.request('POST', path + 'chunked.png', body=iter([b'x' * 65536] * 161), headers={'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'}, encode_chunked=True)
|
|
response = con.getresponse()
|
|
check(response.status == 413, 'chunked limit failed')
|
|
response.read()
|
|
con.close()
|
|
passed.append('chunked_body_limit')
|
|
# Close mid-body before image validation / S3 PUT.
|
|
con = socket.create_connection((url.hostname, url.port))
|
|
headers = f'POST {path}interrupted.png HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer {alice["token"]}\r\nContent-Type: image/png\r\nContent-Length: {len(image)}\r\n\r\n'.encode()
|
|
con.sendall(headers + image[:100])
|
|
con.close()
|
|
time.sleep(1)
|
|
c.call('GET', '/health/ready', schema='Health')
|
|
passed.append('client_disconnect_server_survives')
|
|
output = {'passed': passed, 'count': len(passed), 'note': 'Fault/orphan checks are separate in faults.py'}
|
|
print(json.dumps(output, ensure_ascii=False, indent=2))
|
|
|
|
if __name__ == '__main__':
|
|
main()
|