test(student):lab4 attachments negative cases

- 11 MiB body -> 413 payload_too_large
- truncated PNG -> 415 unsupported_media_type
- MIME mismatch (PNG bytes as image/jpeg) -> 201, content_type image/png
- outsider access to metadata and bytes -> 404
- foreign-chat attachment_id in message -> 404
- 11 attachment_ids -> 400 invalid_request
- duplicate attachment_ids -> 400 invalid_request
- empty filename -> 400
- path-traversal / backslash / NUL in filename -> 400
All rejections are 4xx; no 500 on user error.
This commit is contained in:
Голиков Maximillian Антон
2026-10-23 11:15:42 +03:00
parent 6c78efa17d
commit e799879f9e
2 changed files with 105 additions and 2 deletions
+1 -2
View File
@@ -5,8 +5,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parent
QUICK = ('test_cases.py', 'test_concurrency.py', 'test_auth.py')
QUICK = ('test_cases.py', 'test_concurrency.py', 'test_auth.py', 'test_attachments.py')
def main():
args = sys.argv[1:]
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
import sys
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run # noqa: E402
SAMPLE = (ROOT / 'tests/fixtures/sample.png').read_bytes()
MAX_UPLOAD = 10485760
def upload(c, actor, chat, content, content_type, filename='x.png', expected=201):
return c.call(
'POST',
f'/api/v1/chats/{chat["id"]}/attachments?filename={filename}',
expected,
actor=actor,
raw=content,
headers={'Content-Type': content_type},
)
def main():
args = arguments('Негативные сценарии вложений')
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
# 1. Слишком большой файл (11 MiB) -> 413
oversized = b'\x89PNG\r\n\x1a\n' + b'\x00' * (MAX_UPLOAD + 1024)
r = upload(c, alice, chat, oversized, 'image/png', expected=413)
check(r['json']['error']['code'] == 'payload_too_large',
'11 MiB: ожидался payload_too_large')
# 2. Битый PNG (обрезанный header) -> 415
broken = SAMPLE[:100]
r = upload(c, alice, chat, broken, 'image/png', expected=415)
check(r['json']['error']['code'] == 'unsupported_media_type',
'битый PNG: ожидался unsupported_media_type')
# 3. MIME-подмена: PNG-байты с Content-Type image/jpeg -> 201, но content_type image/png
r = upload(c, alice, chat, SAMPLE, 'image/jpeg')
check(r['json']['content_type'] == 'image/png',
'MIME-подмена: content_type должен определяться по содержимому')
# 4. Чужой attachment_id (не member чата) -> 404
att, _ = c.attachment(alice, chat)
c.call('GET', f'/api/v1/attachments/{att["id"]}', 404, actor=eve)
c.call('GET', f'/api/v1/attachments/{att["id"]}/content', 404, actor=eve)
# 5. attachment_id из другого чата -> 404 при попытке привязать
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]},
schema='Chat')['json']
key = uuid.uuid4().hex
r = c.call('POST', f'/api/v1/chats/{other["id"]}/messages', 404,
actor=alice,
body={'text': '', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': key})
check(r['json']['error']['code'] == 'not_found',
'чужой attachment_id в message: ожидался not_found')
# 6. 11 вложений в одном message -> 400 (binding max=10)
att_ids = [str(uuid.uuid4()) for _ in range(11)]
r = c.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 400,
actor=alice,
body={'text': '', 'attachment_ids': att_ids},
headers={'Idempotency-Key': uuid.uuid4().hex})
check(r['json']['error']['code'] == 'invalid_request',
'11 вложений: ожидался invalid_request')
# 7. Дубликаты attachment_ids в одном message -> 400
r = c.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 400,
actor=alice,
body={'text': '', 'attachment_ids': [att['id'], att['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex})
check(r['json']['error']['code'] == 'invalid_request',
'дубликаты attachment_ids: ожидался invalid_request')
# 8. Пустое имя файла -> 400
r = c.call('POST', f'/api/v1/chats/{chat["id"]}/attachments?filename=',
400, actor=alice, raw=SAMPLE, headers={'Content-Type': 'image/png'})
check(r['json']['error']['code'] == 'invalid_request',
'пустой filename: ожидался invalid_request')
# 9. Опасный filename -> 400
for bad in ('../etc/passwd.png', 'a\\b.png', 'x\x00.png'):
q = bad.replace('\\', '%5C').replace('/', '%2F').replace('\x00', '%00')
r = c.call('POST', f'/api/v1/chats/{chat["id"]}/attachments?filename={q}',
400, actor=alice, raw=SAMPLE, headers={'Content-Type': 'image/png'})
check(r['json']['error']['code'] == 'invalid_request',
f'опасный filename {bad!r}: ожидался invalid_request')
# 10. Failed-вложение нельзя прикрепить -> 409
# (симулируем прямо в БД — только для этого стенда)
c.call('GET', '/health/ready', schema='Health')
print('PASS: негативные сценарии вложений (413/415/404/400) прошли без 500')
if __name__ == '__main__':
run(main)