144 lines
8.5 KiB
Python
144 lines
8.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Негативные и граничные сценарии вложений (уровень 4).
|
|
|
|
Покрывает: слишком большой файл (по Content-Length и по пикселям), «бомбу»,
|
|
повреждённое изображение, подмену MIME, чужой формат, опасные filename,
|
|
чужое attachment_id, вложение другого чата, правила text/attachment_ids,
|
|
идемпотентность с вложениями, варианты. Любой 500 — провал (Client проверяет код).
|
|
"""
|
|
import hashlib
|
|
import uuid
|
|
from labutil import bomb_png, fixture, noise_png, png, raw_post, wait_status
|
|
from client import Client, arguments, check, run
|
|
|
|
MAX = 10 * 1024 * 1024
|
|
|
|
|
|
def main():
|
|
args = arguments('Attachment negative suite (lab4 level 4)')
|
|
c = Client(args.base_url, args.ca_file)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
|
body={'title': 'Другой чат', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
|
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
|
|
results = []
|
|
|
|
def up(name, data, ctype, expected, chat_path=path, actor=alice):
|
|
r = c.call('POST', chat_path + name, expected, actor=actor, raw=data, headers={'Content-Type': ctype},
|
|
schema='Attachment' if expected == 202 else None)
|
|
results.append((name[:40], ctype, len(data), r['status']))
|
|
return r
|
|
|
|
small_png, small_jpg = fixture('small.png'), fixture('small.jpg')
|
|
|
|
# --- корректные файлы ---
|
|
a_png = up('ok.png', small_png, 'image/png', 202)['json']
|
|
a_jpg = up('ok.jpg', small_jpg, 'image/jpeg', 202)['json']
|
|
check(a_jpg['content_type'] == 'image/jpeg' and a_jpg['sha256'] == hashlib.sha256(small_jpg).hexdigest(), 'jpeg metadata')
|
|
uni = up('%D1%84%D0%BE%D1%82%D0%BE%20%F0%9F%98%80.png', small_png, 'image/png', 202)['json']
|
|
check(uni['filename'] == 'фото 😀.png', 'unicode filename not preserved')
|
|
up('params.png', small_png, 'image/png; charset=binary', 202)
|
|
near = noise_png(MAX - 200_000)
|
|
check(len(near) <= MAX, 'generator produced too large file')
|
|
big_ok = up('near-limit.png', near, 'image/png', 202)['json']
|
|
wait_status(c, bob, big_ok['id'], ('ready',), timeout=180)
|
|
got = c.call('GET', '/api/v1/attachments/' + big_ok['id'] + '/content', actor=bob)
|
|
check(got['bytes'] == near, 'near-limit file changed on download')
|
|
|
|
# --- размер и пиксели ---
|
|
# Content-Length больше лимита: 413 сразу, без чтения тела.
|
|
hdr = {'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'}
|
|
st, _ = raw_post(c.base, path + 'too-big.png', dict(hdr, **{'Content-Length': str(MAX + 1)}),
|
|
(b'\x89PNG\r\n\x1a\n' + b'\0' * 65528 for _ in range(1)))
|
|
check(st == 413, 'Content-Length > limit: expected 413, got %s' % st)
|
|
results.append(('too-big.png (Content-Length)', 'image/png', MAX + 1, st))
|
|
# Без Content-Length (chunked), реально 11 MiB: сервер читает не больше лимита + 1 байт.
|
|
def chunked(total=11 * 1024 * 1024, part=256 * 1024):
|
|
yield b'%x\r\n\x89PNG\r\n\x1a\n\r\n' % 8
|
|
sent = 8
|
|
while sent < total:
|
|
yield b'%x\r\n' % part + b'\0' * part + b'\r\n'
|
|
sent += part
|
|
yield b'0\r\n\r\n'
|
|
st, _ = raw_post(c.base, path + 'too-big-chunked.png', dict(hdr, **{'Transfer-Encoding': 'chunked'}), chunked())
|
|
check(st == 413, 'chunked > limit: expected 413, got %s' % st)
|
|
results.append(('too-big-chunked.png (no Content-Length)', 'image/png', 11 * 1024 * 1024, st))
|
|
up('bomb.png', bomb_png(), 'image/png', 413)
|
|
up('over-pixels.png', bomb_png(8000, 5001), 'image/png', 413)
|
|
|
|
# --- содержимое и MIME ---
|
|
up('truncated.png', small_png[:len(small_png) // 2], 'image/png', 415)
|
|
broken = bytearray(small_png)
|
|
broken[len(broken) // 2] ^= 0xFF
|
|
up('corrupt.png', bytes(broken), 'image/png', 415)
|
|
up('truncated.jpg', small_jpg[:len(small_jpg) - 2], 'image/jpeg', 415)
|
|
up('mime-swap.png', small_png, 'image/jpeg', 415) # PNG, объявлен как JPEG
|
|
up('mime-swap.jpg', small_jpg, 'image/png', 415)
|
|
up('text.png', b'definitely not an image', 'image/png', 415)
|
|
up('gif.gif', b'GIF89a\x01\x00\x01\x00\x00\x00\x00;', 'image/gif', 415)
|
|
up('ctype-missing.png', small_png, 'application/octet-stream', 415)
|
|
up('empty.png', b'', 'image/png', 415)
|
|
up('short-data.png', png(8, 8, raw=b'\x00' * 10), 'image/png', 415)
|
|
|
|
# --- filename ---
|
|
for bad in ('..%2Fetc%2Fpasswd', 'a%5Cb.png', 'nul%00.png', 'bell%07.png', '%20%20%20', 'x' * 256, ''):
|
|
up(bad, small_png, 'image/png', 400)
|
|
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments', 400, actor=alice, raw=small_png,
|
|
headers={'Content-Type': 'image/png'})
|
|
c.call('POST', path + 'a.png&filename=b.png', 400, actor=alice, raw=small_png, headers={'Content-Type': 'image/png'})
|
|
|
|
# --- доступ ---
|
|
up('eve.png', small_png, 'image/png', 404, actor=eve)
|
|
c.call('POST', path + 'anon.png', 401, raw=small_png, headers={'Content-Type': 'image/png'})
|
|
for suffix in ('', '/content'):
|
|
c.call('GET', '/api/v1/attachments/' + a_png['id'] + suffix, 404, actor=eve)
|
|
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=alice)
|
|
c.call('GET', '/api/v1/attachments/not-a-uuid' + suffix, 400, actor=alice)
|
|
wait_status(c, bob, a_png['id'], ('ready',))
|
|
wait_status(c, bob, a_jpg['id'], ('ready',))
|
|
th = c.call('GET', '/api/v1/attachments/' + a_png['id'] + '/content?variant=thumbnail', actor=bob)
|
|
check(th['headers'].get_content_type() == 'image/jpeg', 'thumbnail of small png')
|
|
c.call('GET', '/api/v1/attachments/' + a_png['id'] + '/content?variant=bogus', 400, actor=bob)
|
|
orig = c.call('GET', '/api/v1/attachments/' + a_png['id'] + '/content?variant=original', actor=bob)
|
|
check(orig['bytes'] == small_png and orig['headers'].get_content_type() == 'image/png', 'original variant')
|
|
|
|
# --- сообщения с вложениями ---
|
|
foreign = up('foreign.png', small_png, 'image/png', 202,
|
|
chat_path='/api/v1/chats/' + other['id'] + '/attachments?filename=')['json']
|
|
mpath = '/api/v1/chats/' + chat['id'] + '/messages'
|
|
|
|
def msg(body, expected, key=None, actor=alice):
|
|
return c.call('POST', mpath, expected, actor=actor, body=body,
|
|
headers={'Idempotency-Key': key or uuid.uuid4().hex},
|
|
schema='Message' if expected == 201 else None)
|
|
|
|
msg({'text': '', 'attachment_ids': [foreign['id']]}, 404) # вложение другого чата
|
|
msg({'text': '', 'attachment_ids': [str(uuid.uuid4())]}, 404) # неизвестное
|
|
msg({'text': 'x', 'attachment_ids': ['nope']}, 400)
|
|
msg({'text': 'x', 'attachment_ids': [a_png['id'], a_png['id']]}, 400)
|
|
msg({'text': 'x', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]}, 400)
|
|
msg({'text': ''}, 400)
|
|
msg({'text': ' ', 'attachment_ids': []}, 400)
|
|
msg({'attachment_ids': [a_png['id']]}, 400) # text обязателен
|
|
msg({'text': '', 'attachment_ids': [a_png['id']]}, 404, actor=eve)
|
|
key = uuid.uuid4().hex
|
|
m1 = msg({'text': '', 'attachment_ids': [a_png['id'], a_jpg['id']]}, 201, key=key)['json']
|
|
check(m1['attachment_ids'] == [a_png['id'], a_jpg['id']] and m1['text'] == '', 'attachment order/text')
|
|
m2 = msg({'attachment_ids': [a_png['id'], a_jpg['id']], 'text': ''}, 201, key=key)['json']
|
|
check(m2 == m1, 'idempotent replay with attachments differs')
|
|
msg({'text': '', 'attachment_ids': [a_jpg['id'], a_png['id']]}, 409, key=key) # другой порядок = другое тело
|
|
plain = msg({'text': 'без вложений'}, 201)['json']
|
|
check(plain['attachment_ids'] == [], 'missing attachment_ids must be []')
|
|
hist = c.call('GET', mpath + '?limit=100', actor=bob, schema='MessagePage')['json']['items']
|
|
check(any(m == m1 for m in hist), 'message with attachments not in history')
|
|
# Bob (участник) прикрепляет вложение Alice — допустимо.
|
|
msg({'text': 'и я', 'attachment_ids': [a_png['id']]}, 201, actor=bob)
|
|
|
|
for row in results:
|
|
print('%-42s %-28s %9d -> %d' % row)
|
|
print('PASS: attachment negative suite (%d upload cases, no 5xx)' % len(results))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
run(main)
|