Implement lab4 grade 3: private S3 attachments and persistence checks

This commit is contained in:
2026-11-16 15:25:12 +03:00
parent ec540a1a72
commit 586b142ace
48 changed files with 2458 additions and 14 deletions
+136
View File
@@ -0,0 +1,136 @@
"""Required original-file, replica-switch, bucket and S3-outage demonstrations."""
import hashlib
from io import BytesIO
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import urllib.error
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(ROOT / 'tests'), str(ROOT / 'scripts')]
from client import Client, check
from labctl import containers, restore, save
def compose(*args, payload=None):
process = subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
input=payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, encoding='utf-8')
if process.returncode:
raise RuntimeError('Compose action failed: ' + args[0])
return process.stdout.strip()
def wait_ready(c):
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
try:
c.call('GET', '/health/ready', schema='Health')
return
except AssertionError:
time.sleep(.5)
raise RuntimeError('Readiness did not recover')
def inside_probe():
"""Called in one API container with existing synthetic actors over stdin."""
sys.path.insert(0, str(ROOT / 'src'))
from messenger.core import Config, Store
from PIL import Image
data = json.load(sys.stdin)
c = Client('http://localhost:8080')
alice, bob, eve, chat, att = (data[x] for x in ('alice', 'bob', 'eve', 'chat', 'att'))
if data['mode'] == 'private':
store = Store(Config.from_env())
try:
row = store.attachments.get(alice['id'], att['id'])
url = os.environ['S3_ENDPOINT'] + '/' + os.environ['S3_BUCKET'] + '/' + row['object_key']
try:
urllib.request.urlopen(url, timeout=3)
raise AssertionError('Anonymous object read succeeded')
except urllib.error.HTTPError as error:
check(error.code == 403, 'Expected anonymous S3 403')
images = []
for fmt, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]:
buf = BytesIO()
Image.new('RGB', (32, 24), 'blue').save(buf, format=fmt)
raw = buf.getvalue()
uploaded = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=real.' + fmt.lower(),
201, actor=alice, raw=raw, headers={'Content-Type': mime}, schema='Attachment')['json']
downloaded = c.call('GET', '/api/v1/attachments/' + uploaded['id'] + '/content', actor=bob)
check(downloaded['bytes'] == raw, 'Original changed')
images.append(dict(format=fmt, bytes=len(raw), sha256=uploaded['sha256']))
print(json.dumps(dict(anonymous_get=403, real_images=images)))
finally:
store.close()
else:
c.call('GET', '/health/live', schema='Health')
c.call('GET', '/health/ready', 503)
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=outage.png',
503, actor=alice, raw=raw, headers={'Content-Type': 'image/png'})
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', 503, actor=bob)
c.call('GET', '/api/v1/attachments/' + att['id'], actor=bob, schema='Attachment')
print(json.dumps(dict(live=200, ready=503, upload=503, content=503, metadata=200)))
def main():
c = Client(os.getenv('BASE_URL', 'http://127.0.0.1:8084'))
alice, bob, eve, chat = c.bootstrap()
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png',
201, actor=alice, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment')
att, uploader = response['json'], response['headers']['X-Instance-Id']
message = c.message(alice, chat, '', attachments=[att['id']])['json']
before = containers('api')
target = next(x for x in before if uploader.startswith(x['hostname'] + '-'))
try:
subprocess.run(['docker', 'stop', '--time', '8', target['id']], check=True, stdout=subprocess.PIPE)
after = containers('api', True)
check(next(x for x in after if x['id'] == target['id'])['status'] == 'exited', 'Uploader not stopped')
wait_ready(c)
downloaded = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
reader = downloaded['headers']['X-Instance-Id']
check(reader != uploader and downloaded['bytes'] == raw, 'Replica-switch original mismatch')
page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=bob, schema='MessagePage')['json']
check(message in page['items'], 'Attached message missing from history')
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
result = dict(uploader=uploader, downloader=reader, before=before, after=after,
bytes=len(raw), sha256=hashlib.sha256(raw).hexdigest(),
same_original=True, attached_message_read=True, stranger_metadata=404, stranger_content=404)
save('upload-failover.json', result)
print('PASS: uploading API stopped; another API returned identical original and attached message.')
finally:
restore()
data = dict(alice=alice, bob=bob, eve=eve, chat=chat, att=att, mode='private')
result = compose('exec', '-T', 'api', 'python', 'student-tests/grade3.py', '--inside',
payload=json.dumps(data))
save('private-and-formats.json', json.loads(result))
print('PASS: real PNG/JPEG originals and anonymous S3 403.')
before = containers('s3')
started = time.monotonic()
try:
compose('stop', '--timeout', '8', 's3')
check(not containers('s3'), 'MinIO still running')
data['mode'] = 'outage'
result = compose('exec', '-T', 'api', 'python', 'student-tests/grade3.py', '--inside',
payload=json.dumps(data))
observation = json.loads(result)
finally:
compose('start', 's3')
wait_ready(c)
downloaded = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
check(downloaded['bytes'] == raw, 'Original changed after S3 outage')
save('s3-outage.json', dict(before=before, after=containers('s3'), observation=observation,
recovered_within_seconds=round(time.monotonic() - started, 3),
original_preserved=True))
print('PASS: unavailable S3 yields 503; restart restores the same original and existing session.')
if __name__ == '__main__':
inside_probe() if '--inside' in sys.argv else main()
+55
View File
@@ -0,0 +1,55 @@
"""Run inside API network: same session and simultaneous requests at distinct processes."""
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import socket
import sys
import threading
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, check
def main():
clients = [Client('http://' + ip + ':8080') for ip in sorted(set(socket.gethostbyname_ex('api')[2]))]
check(len(clients) == 2, 'Expected two API addresses in Docker DNS')
c = clients[0]
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/messages'
key = uuid.uuid4().hex
barrier = threading.Barrier(16)
def send(n):
barrier.wait(timeout=10)
return clients[n % 2].call('POST', path, 201, actor=alice,
body={'attachment_ids': [], 'text': 'Параллельный повтор'} if n % 2 else
{'text': 'Параллельный повтор'},
headers={'Idempotency-Key': key}, schema='Message')
with ThreadPoolExecutor(max_workers=16) as pool:
responses = list(pool.map(send, range(16)))
messages = [x['json'] for x in responses]
instances = sorted({x['headers']['X-Instance-Id'] for x in responses})
check(len(instances) == 2, 'Requests did not reach distinct API processes')
check(all(x == messages[0] for x in messages), 'Concurrent responses differ')
history = clients[1].call('GET', path, actor=bob, schema='MessagePage')['json']['items']
check(history == [messages[0]], 'Concurrent requests created duplicates')
clients[1].call('POST', path, 409, actor=alice, body={'text': 'Другой body'}, headers={'Idempotency-Key': key})
# Scope is user + chat; an independent user and another chat may reuse the key.
other = clients[1].message(bob, chat, 'Другой пользователь', key=key)['json']
chat2 = c.call('POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id']]}, schema='Chat')['json']
third = clients[1].message(alice, chat2, 'Другой чат', key=key)['json']
check(len({messages[0]['id'], other['id'], third['id']}) == 3, 'Incorrect idempotency scope')
for invalid in ('', 'contains space', 'x' * 129):
c.call('POST', path, 400, actor=alice, body={'text': 'Invalid key'}, headers={'Idempotency-Key': invalid})
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
clients[1].call('POST', path, 401, actor=alice, body={'text': 'Параллельный повтор'},
headers={'Idempotency-Key': key})
print(json.dumps(dict(result='PASS', parallel_requests=16, api_instances=instances,
unique_messages=1, scope_conflict_logout='PASS'), ensure_ascii=False))
if __name__ == '__main__':
main()
+71
View File
@@ -0,0 +1,71 @@
"""Check the upload limits required by grade 3 before body reading/decoding."""
from email.message import Message
from io import BytesIO
from pathlib import Path
import struct
import sys
from types import SimpleNamespace
import zlib
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
from messenger.attachments import filename_value, validate_image
from messenger.core import APIError
from messenger.server import Handler
def rejected(status, action):
try:
action()
except APIError as error:
check(error.status == status, 'Unexpected rejection code')
else:
raise AssertionError('Expected rejection')
class NeverRead:
def read(self, *_):
raise AssertionError('Oversized body was read')
def main():
headers = Message()
headers['Content-Length'] = '10485761'
headers['Content-Type'] = 'image/png'
handler = SimpleNamespace(headers=headers, rfile=NeverRead())
rejected(413, lambda: Handler.read_body(handler, 10485760, ('image/png',)))
original = (ROOT / 'tests/fixtures/sample.png').read_bytes()
# Header-only dimension change: rejection must happen before decoding pixels.
header = original[12:16] + struct.pack('!IIBBBBB', 8000, 5001, 8, 2, 0, 0, 0)
huge = original[:12] + header + struct.pack('!I', zlib.crc32(header)) + original[33:]
rejected(413, lambda: validate_image(huge, 'image/png', 40000000))
for name in ('../x.png', 'a\\x.png', 'a\0.png', 'a\n.png'):
rejected(400, lambda: filename_value(name))
check(filename_value('фото.png') == 'фото.png', 'Unicode display filename changed')
c = Client('http://lb:8080')
alice, bob, _, chat = c.bootstrap()
# Exact byte limit is legal; trailing PNG bytes must be returned unchanged.
raw = original + b'\0' * (10485760 - len(original))
att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=limit.png',
201, actor=alice, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == raw,
'10 MiB original changed')
del raw
# Exact pixel limit: valid image, checked in one request without concurrency.
buffer = BytesIO()
with Image.new('RGB', (8000, 5000), 'black') as image:
image.save(buffer, format='PNG')
raw = buffer.getvalue()
att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=pixels.png',
201, actor=alice, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == raw,
'40 million pixel original changed')
print('PASS: 10 MiB and 40,000,000 pixels accepted; excess bytes rejected before read;')
print('excess dimensions rejected before decode; unsafe filenames rejected; Unicode filename accepted.')
if __name__ == '__main__':
main()