Перенести реализацию лабораторной 4

This commit is contained in:
2026-11-16 13:57:52 +03:00
parent 276dbdad8a
commit 4d54ba3848
67 changed files with 3393 additions and 0 deletions
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Stop the API replica that accepted upload and download through another replica."""
import hashlib
import os
from pathlib import Path
import subprocess
import time
from client import Client, ROOT, arguments, check, run
def main():
def configure(parser):
parser.add_argument('--action-script', required=True)
args = arguments('Attachment API-replica failover', configure)
script = Path(args.action_script).expanduser().resolve()
check(script.is_file() and os.access(script, os.X_OK), 'action script must be executable')
client = Client(args.base_url, args.ca_file, timeout=3)
alice, bob, _eve, chat = client.bootstrap()
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
uploaded = client.call(
'POST',
f'/api/v1/chats/{chat["id"]}/attachments?filename=failover.png',
201,
actor=alice,
raw=content,
headers={'Content-Type': 'image/png'},
schema='Attachment',
)
target = uploaded['headers']['X-Instance-Id']
env = dict(os.environ)
env['TARGET_INSTANCE_ID'] = target
started = time.monotonic()
subprocess.run([str(script)], env=env, check=True)
deadline = time.monotonic() + 15
failures = 0
while True:
try:
downloaded = client.call(
'GET',
f'/api/v1/attachments/{uploaded["json"]["id"]}/content',
actor=bob,
)
if downloaded['headers']['X-Instance-Id'] != target:
break
except Exception:
failures += 1
check(time.monotonic() < deadline, 'download did not recover through another replica')
time.sleep(0.2)
check(downloaded['bytes'] == content, 'downloaded file differs after replica failure')
print(
'PASS: upload_instance=%s download_instance=%s recovery_seconds=%.3f failures=%d sha256=%s'
% (
target,
downloaded['headers']['X-Instance-Id'],
time.monotonic() - started,
failures,
hashlib.sha256(content).hexdigest(),
)
)
if __name__ == '__main__':
run(main)
+153
View File
@@ -0,0 +1,153 @@
"""Негативные интеграционные проверки вложений для уровня 4."""
import struct
from urllib.parse import quote
import uuid
import zlib
import pytest
from tests.client import Client, ROOT
@pytest.fixture(scope='module')
def scenario():
client = Client()
alice, bob, eve, chat = client.bootstrap()
return client, alice, bob, eve, chat
def upload(client, actor, chat, content, *, filename='sample.png', content_type='image/png', expected=201):
return client.call(
'POST',
f'/api/v1/chats/{chat["id"]}/attachments?filename={quote(filename, safe="")}',
expected,
actor=actor,
raw=content,
headers={'Content-Type': content_type},
schema='Attachment' if expected == 201 else None,
)
def oversized_dimensions_png(content: bytes) -> bytes:
data = bytearray(content)
data[16:20] = struct.pack('>I', 10_000)
data[20:24] = struct.pack('>I', 5_000)
data[29:33] = struct.pack('>I', zlib.crc32(data[12:29]) & 0xFFFFFFFF)
return bytes(data)
def test_file_larger_than_10_mib_is_rejected(scenario):
"""Отклоняет файл размером больше 10 MiB."""
client, alice, _bob, _eve, chat = scenario
upload(client, alice, chat, b'x' * (10 * 1024 * 1024 + 1), expected=413)
def test_corrupted_image_is_rejected(scenario):
"""Отклоняет повреждённое изображение."""
client, alice, _bob, _eve, chat = scenario
upload(client, alice, chat, b'not-a-png', expected=415)
def test_mime_mismatch_is_rejected(scenario):
"""Отклоняет MIME, не совпадающий с содержимым."""
client, alice, _bob, _eve, chat = scenario
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
upload(client, alice, chat, content, content_type='image/jpeg', expected=415)
def test_pixel_limit_is_checked_before_decode(scenario):
"""Проверяет лимит пикселей до полной декомпрессии."""
client, alice, _bob, _eve, chat = scenario
content = oversized_dimensions_png((ROOT / 'tests/fixtures/sample.png').read_bytes())
upload(client, alice, chat, content, expected=413)
@pytest.mark.parametrize(
'filename',
['../escape.png', 'folder\\escape.png', 'bad\x00name.png', 'bad\x85name.png'],
)
def test_dangerous_filename_is_rejected(scenario, filename):
"""Отклоняет опасное отображаемое имя файла."""
client, alice, _bob, _eve, chat = scenario
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
upload(client, alice, chat, content, filename=filename, expected=400)
def test_outsider_cannot_read_attachment(scenario):
"""Скрывает метаданные и содержимое от постороннего пользователя."""
client, alice, _bob, eve, chat = scenario
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
attachment = upload(client, alice, chat, content)['json']
client.call('GET', f'/api/v1/attachments/{attachment["id"]}', 404, actor=eve)
client.call('GET', f'/api/v1/attachments/{attachment["id"]}/content', 404, actor=eve)
def test_attachment_from_another_chat_cannot_be_linked(scenario):
"""Запрещает прикреплять вложение другого чата."""
client, alice, bob, _eve, chat = scenario
other_chat = client.call(
'POST',
'/api/v1/chats',
201,
actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]},
schema='Chat',
)['json']
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
attachment = upload(client, alice, other_chat, content)['json']
client.call(
'POST',
f'/api/v1/chats/{chat["id"]}/messages',
404,
actor=alice,
body={'text': 'чужое вложение', 'attachment_ids': [attachment['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex},
)
def test_idempotency_distinguishes_attachment_list(scenario):
"""Включает список вложений в сравнение идемпотентного запроса."""
client, alice, _bob, _eve, chat = scenario
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
attachment = upload(client, alice, chat, content)['json']
key = uuid.uuid4().hex
first = client.message(
alice,
chat,
'идемпотентное вложение',
key=key,
attachments=[attachment['id']],
)['json']
replay = client.message(
alice,
chat,
'идемпотентное вложение',
key=key,
attachments=[attachment['id']],
)['json']
assert replay == first
client.call(
'POST',
f'/api/v1/chats/{chat["id"]}/messages',
409,
actor=alice,
body={'text': 'идемпотентное вложение', 'attachment_ids': []},
headers={'Idempotency-Key': key},
)
def test_missing_attachment_ids_equals_empty_list_for_idempotency(scenario):
"""Считает отсутствие attachment_ids эквивалентным пустому списку."""
client, alice, _bob, _eve, chat = scenario
key = uuid.uuid4().hex
first = client.message(alice, chat, 'обычный текст', key=key)['json']
replay = client.call(
'POST',
f'/api/v1/chats/{chat["id"]}/messages',
201,
actor=alice,
body={'text': 'обычный текст', 'attachment_ids': []},
headers={'Idempotency-Key': key},
schema='Message',
)['json']
assert replay == first