[+] Completed lab 4

This commit is contained in:
Антон Архипов
2026-11-16 16:23:32 +03:00
parent ec540a1a72
commit 06f0a9f31e
60 changed files with 7160 additions and 53 deletions
+46
View File
@@ -0,0 +1,46 @@
"""Stop the exact process that served an upload and retrieve the original."""
from hashlib import sha256
import os
from pathlib import Path
import subprocess
import sys
from time import monotonic, sleep
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, arguments, check, run
def main():
args = arguments('Download after stopping the uploading replica',
lambda parser: parser.add_argument('--action-script', required=True))
client = Client(args.base_url, args.ca_file, timeout=2)
alice, bob, _, chat = client.bootstrap()
png = (ROOT / 'tests/fixtures/sample.png').read_bytes()
response = client.call('POST', f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png",
201, actor=alice, headers={'Content-Type': 'image/png'},
raw=png, schema='Attachment')
target = response['headers']['X-Instance-Id']
attachment = response['json']
script = Path(args.action_script).resolve()
check(script.is_file() and os.access(script, os.X_OK), 'action script is not executable')
start = monotonic()
subprocess.run([str(script)], env={**os.environ, 'TARGET_INSTANCE_ID': target}, check=True, timeout=10)
while monotonic() - start < 10:
try:
downloaded = client.call('GET', f"/api/v1/attachments/{attachment['id']}/content", actor=bob)
except Failure:
sleep(0.1)
continue
actual = downloaded['headers']['X-Instance-Id']
check(actual != target, 'uploader still serves requests')
check(downloaded['bytes'] == png and sha256(downloaded['bytes']).hexdigest() == attachment['sha256'],
'download failed checksum or byte comparison')
print(f'PASS: upload on {target}; same bytes downloaded through {actual} after {monotonic() - start:.3f}s')
return
raise Failure('another replica did not return the original within 10 seconds')
if __name__ == '__main__':
run(main)
+62
View File
@@ -0,0 +1,62 @@
"""Verify limits, actual image type and chat-scoped attachments."""
from pathlib import Path
import struct
import sys
from urllib.parse import quote
import uuid
import zlib
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments('Student checks: attachment byte/pixel limits and access')
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
path = '/api/v1/chats/' + chat['id']
upload = path + '/attachments?filename='
png = (ROOT / 'tests/fixtures/sample.png').read_bytes()
jpeg = (ROOT / 'student-tests/sample.jpg').read_bytes()
png_type = {'Content-Type': 'image/png'}
jpeg_type = {'Content-Type': 'image/jpeg'}
header = b'IHDR' + struct.pack('>II', 8000, 8000) + png[24:29]
oversized_pixels = png[:12] + header + struct.pack('>I', zlib.crc32(header)) + png[33:]
cases = [
(413, png_type, b'x' * (10 * 1024 * 1024 + 1)),
(413, png_type, oversized_pixels),
(415, png_type, png[:len(png) // 2]),
(415, jpeg_type, png),
(415, png_type, b'text disguised as an image'),
]
for expected, headers, content in cases:
client.call('POST', upload + 'sample.png', expected, actor=alice, headers=headers, raw=content)
for filename in ('../sample.png', 'x\\sample.png', 'x\x00.png'):
client.call('POST', upload + quote(filename, safe=''), 400,
actor=alice, headers=png_type, raw=png)
client.call('POST', upload + 'sample.png', 404, actor=eve, headers=png_type, raw=png)
attachment = client.call('POST', upload + quote('Снимок.jpg'), 201,
actor=alice, headers=jpeg_type, raw=jpeg, schema='Attachment')['json']
check(attachment['filename'] == 'Снимок.jpg', 'display filename changed')
route = '/api/v1/attachments/' + attachment['id']
response = client.call('GET', route + '/content', actor=bob)
check(response['bytes'] == jpeg, 'JPEG bytes changed')
check(response['headers'].get_content_type() == 'image/jpeg', 'JPEG MIME changed')
client.call('GET', route + '/content', 404, actor=eve)
other_chat = client.call('POST', '/api/v1/chats', 201, actor=alice, schema='Chat',
body={'title': 'Другой чат', 'member_ids': [alice['id']]})['json']
client.call('POST', '/api/v1/chats/' + other_chat['id'] + '/messages', 404,
actor=alice, headers={'Idempotency-Key': uuid.uuid4().hex},
body={'text': '', 'attachment_ids': [attachment['id']]})
key = uuid.uuid4().hex
message = client.message(alice, chat, 'Текст', key=key)['json']
replay = client.message(alice, chat, 'Текст', key=key, attachments=[])['json']
check(message == replay, 'omitted attachment_ids and [] were treated differently')
print('PASS: JPEG, unsafe filenames, byte/pixel limits, malformed image, MIME mismatch and chat ACL')
if __name__ == '__main__':
run(main)
+47
View File
@@ -0,0 +1,47 @@
"""Test UTF-8 Basic credentials, exact JSON validation and chat membership."""
import base64
from pathlib import Path
import sys
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments('Student checks: Basic and chat validation')
client = Client(args.base_url, args.ca_file)
username = 'u_colon_' + uuid.uuid4().hex[:12]
password = 'Пароль:🔑' * 3
user = client.call('POST', '/api/v1/users', 201, schema='User',
body={'username': username, 'display_name': 'Студент', 'password': password})['json']
basic = base64.b64encode(f'{username}:{password}'.encode()).decode()
auth = {'Authorization': 'Basic ' + basic}
session = client.call('POST', '/api/v1/auth/sessions', 201,
headers=auth, schema='Session')['json']
check(session['user'] == user, 'UTF-8 password with colon failed')
client.call('POST', '/api/v1/auth/sessions', 400, headers=auth, body={})
alice = {'id': user['id'], 'token': session['token']}
bob = client.user('bob')
path = '/api/v1/chats'
title = 'Проверка участников'
members = [alice['id'], bob['id']]
for body in (
{'title': title, 'member_ids': [alice['id'], str(uuid.uuid4())]},
{'title': title, 'member_ids': [alice['id'], alice['id'].upper()]},
{'title': title, 'member_ids': [bob['id']]},
{'title': 123, 'member_ids': members},
{'title': title, 'member_ids': members, 'unexpected': True},
):
client.call('POST', path, 400, actor=alice, body=body)
page = client.call('GET', path, actor=alice, schema='ChatPage')['json']
check(page['items'] == [], 'invalid creation left a visible chat')
chat = client.call('POST', path, 201, actor=alice,
body={'title': title, 'member_ids': members}, schema='Chat')['json']
listed = client.call('GET', path, actor=bob, schema='ChatPage')['json']
check(listed['items'] == [chat], 'valid chat or membership is missing')
print('PASS: UTF-8 password with colon, strict JSON, and atomic chat creation')
if __name__ == '__main__':
run(main)
+37
View File
@@ -0,0 +1,37 @@
"""Exercise concurrent retries through the shared load balancer."""
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import sys
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, arguments, check, run
def main():
args = arguments('Student checks: concurrent idempotency on two replicas')
client = Client(args.base_url, args.ca_file)
alice, bob, _, chat = client.bootstrap()
key = uuid.uuid4().hex
def send(_):
return Client(args.base_url, args.ca_file).message(alice, chat, 'Повтор', key=key)
with ThreadPoolExecutor(max_workers=8) as executor:
responses = list(executor.map(send, range(16)))
first = responses[0]['json']
instances = {item['headers']['X-Instance-Id'] for item in responses}
check(len(instances) >= 2, 'concurrent requests did not reach two API replicas')
check(all(item['json'] == first for item in responses), 'replays differ')
path = '/api/v1/chats/' + chat['id'] + '/messages'
page = client.call('GET', path, actor=bob, schema='MessagePage')['json']
check(page['items'] == [first], 'duplicate persisted message')
client.call('POST', path, 409, actor=alice, body={'text': 'Другой текст'},
headers={'Idempotency-Key': key})
independent = client.message(bob, chat, 'Повтор', key=key)['json']
check(independent['id'] != first['id'], 'key incorrectly shared between users')
print(f'PASS: {len(responses)} concurrent requests on {len(instances)} replicas yielded one message')
if __name__ == '__main__':
run(main)
Binary file not shown.

After

Width:  |  Height:  |  Size: 633 B