lab4: S3-вложения, presigned upload и проверки

This commit is contained in:
Vladislav Kunetskiy
2026-10-21 22:42:48 +03:00
parent d342b2a227
commit 49c2fe3071
79 changed files with 12266 additions and 910 deletions
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""Upload through one API replica, stop it, download through another.
Run against a live stand:
python3 student-tests/attachment_failover.py --base-url http://localhost:8080
"""
import hashlib
import os
import subprocess
import sys
import time
from pathlib import Path
from urllib.parse import quote
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
sys.path.insert(0, str(Path(__file__).resolve().parent))
from client import Client, Failure, arguments, check, run # noqa: E402
from tests_helpers import ROOT, compose # noqa: E402
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
def main():
args = arguments('Attachment failover across API replicas (lab4)')
client = Client(args.base_url, args.ca_file)
alice, bob, _, chat = client.bootstrap()
content = FIXTURE.read_bytes()
response = client.call(
'POST',
'/api/v1/chats/' + chat['id'] + '/attachments?filename=' + quote('failover.png'),
201,
actor=alice,
raw=content,
headers={'Content-Type': 'image/png'},
schema='Attachment',
)
attachment = response['json']
instance = response['headers'].get('X-Instance-Id')
check(bool(instance), 'upload response has no X-Instance-Id')
check(attachment['sha256'] == hashlib.sha256(content).hexdigest(), 'upload checksum mismatch')
stop = subprocess.run(
[str(ROOT / 'scripts/stop-one.sh')],
cwd=ROOT,
env={**os.environ, 'TARGET_INSTANCE_ID': instance},
capture_output=True,
text=True,
)
check(stop.returncode == 0, 'stop-one.sh failed: ' + stop.stderr.strip())
deadline = time.monotonic() + 30
last_error = None
while time.monotonic() < deadline:
try:
download = client.call(
'GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob,
)
if download['bytes'] == content:
metadata = client.call(
'GET', '/api/v1/attachments/' + attachment['id'], actor=bob, schema='Attachment',
)['json']
check(metadata['sha256'] == attachment['sha256'], 'metadata changed after failover')
print('PASS: lab4 attachment failover; served by', instance)
return
last_error = 'downloaded bytes differ from the original'
except Failure as error:
last_error = str(error)
time.sleep(1)
raise Failure('download did not recover within 30s: ' + str(last_error))
if __name__ == '__main__':
try:
run(main)
finally:
compose('up', '-d', '--no-deps', 'api', check=False)
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Negative attachment scenarios required by lab4 level 4.
Run against a live stand:
python3 student-tests/attachments_negative.py --base-url http://localhost:8080
"""
import hashlib
import sys
import urllib.error
import urllib.request
import uuid
from pathlib import Path
from urllib.parse import quote
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, Failure, arguments, check, run # noqa: E402
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
def upload(client, actor, chat, content, filename='sample.png', content_type='image/png', expected=201):
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + quote(filename, safe='')
return client.call('POST', path, expected, actor=actor, raw=content, headers={'Content-Type': content_type})
def main():
args = arguments('Attachment negative scenarios (lab4)')
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
fixture = FIXTURE.read_bytes()
# Oversized body: rejected before any image parsing.
upload(client, alice, chat, b'\x00' * (10 * 1024 * 1024 + 1), expected=413)
# Empty body is not a valid image.
upload(client, alice, chat, b'', expected=415)
# Corrupt PNG: flip one IDAT payload byte, CRC no longer matches.
corrupt = bytearray(fixture)
index = corrupt.index(b'IDAT') + 8
corrupt[index] ^= 0xFF
upload(client, alice, chat, bytes(corrupt), expected=415)
# Declared JPEG but the bytes are PNG.
upload(client, alice, chat, fixture, filename='photo.jpg', content_type='image/jpeg', expected=415)
# Dangerous display names.
for name in ('../x.png', 'a/b.png', 'a\\b.png', 'a\x00.png', 'a\n.png'):
upload(client, alice, chat, fixture, filename=name, expected=400)
# A member of one chat cannot read an attachment of another chat.
other = client.call(
'POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Другой чат', 'member_ids': [alice['id'], eve['id']]}, schema='Chat',
)['json']
foreign, foreign_content = client.attachment(eve, other)
client.call('GET', '/api/v1/attachments/' + foreign['id'], 404, actor=bob)
client.call('GET', '/api/v1/attachments/' + foreign['id'] + '/content', 404, actor=bob)
# Message rules: empty text without attachments, attachment from another chat.
client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
body={'text': ''}, headers={'Idempotency-Key': uuid.uuid4().hex},
)
client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 404, actor=alice,
body={'text': 'чужое', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex},
)
# Contract limits: 11 unique IDs and duplicate IDs are rejected by the schema.
client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
body={'text': 'много', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]},
headers={'Idempotency-Key': uuid.uuid4().hex},
)
duplicate = str(uuid.uuid4())
client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/messages', 400, actor=alice,
body={'text': 'дубликат', 'attachment_ids': [duplicate, duplicate]},
headers={'Idempotency-Key': uuid.uuid4().hex},
)
# The only variant in the lab4 contract is original; other values are 400.
own, content = client.attachment(alice, chat)
client.call('GET', '/api/v1/attachments/' + own['id'] + '/content?variant=thumbnail', 400, actor=alice)
# Attachment-only message is valid.
client.message(alice, chat, '', attachments=[own['id']])
# Object keys are server-generated; anonymous direct access must be denied.
key = 'attachments/' + chat['id'] + '/' + own['id']
request = urllib.request.Request('http://127.0.0.1:8333/messenger-attachments/' + key, method='GET')
try:
urllib.request.urlopen(request, timeout=5)
except urllib.error.HTTPError as error:
check(error.code == 403, 'anonymous S3 GET must be 403, got ' + str(error.code))
else:
raise Failure('anonymous S3 GET unexpectedly succeeded')
check(hashlib.sha256(content).hexdigest() == own['sha256'], 'fixture checksum mismatch')
print('PASS: lab4 attachment negative scenarios')
if __name__ == '__main__':
run(main)
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Presigned direct-upload track (lab4 level 5).
The mandatory proxy endpoint stays available; this script exercises the
optional extension: presign -> direct PUT to S3 -> complete -> message.
Run against a live stand:
python3 student-tests/presign_flow.py --base-url http://localhost:8080
Set PRESIGN_EXPIRY_WAIT=seconds to also verify that an expired URL is rejected
(the stand must run with a matching S3_PRESIGN_TTL).
"""
import hashlib
import json
import os
import sys
import time
import urllib.error
import urllib.request
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, Failure, arguments, check, run # noqa: E402
FIXTURE = Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png'
def presign(client, actor, chat, content, filename='presigned.png', content_type='image/png'):
body = {
'filename': filename,
'content_type': content_type,
'size_bytes': len(content),
'sha256': hashlib.sha256(content).hexdigest(),
}
response = client.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments/presign', 201,
actor=actor, body=body,
)
return json.loads(response['bytes'])
def put(url, content, content_type='image/png'):
request = urllib.request.Request(
url, data=content, method='PUT', headers={'Content-Type': content_type},
)
try:
with urllib.request.urlopen(request, timeout=15) as response:
return response.status
except urllib.error.HTTPError as error:
return error.code
def complete(client, actor, attachment_id, digest, expected=200):
return client.call(
'POST', '/api/v1/attachments/' + attachment_id + '/complete', expected,
actor=actor, body={'sha256': digest}, schema='Attachment' if expected == 200 else None,
)
def main():
args = arguments('Presigned upload flow (lab4 track 1)')
client = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = client.bootstrap()
content = FIXTURE.read_bytes()
digest = hashlib.sha256(content).hexdigest()
# Happy path: direct PUT, completion, message, download.
presigned = presign(client, alice, chat, content)
check(presigned['method'] == 'PUT', 'presign method must be PUT')
check(put(presigned['upload_url'], content) == 200, 'direct PUT failed')
attachment = complete(client, alice, presigned['attachment_id'], digest)['json']
check(attachment['sha256'] == digest and attachment['size_bytes'] == len(content), 'completed metadata mismatch')
client.message(alice, chat, '', attachments=[attachment['id']])
download = client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)
check(download['bytes'] == content, 'download differs from the presigned original')
# Completion is idempotent.
again = complete(client, alice, presigned['attachment_id'], digest)['json']
check(again['id'] == attachment['id'], 'repeated complete returned another attachment')
# A foreign user cannot complete someone else's pending upload.
pending = presign(client, alice, chat, content)
complete(client, bob, pending['attachment_id'], digest, expected=404)
# Incomplete upload: complete before PUT.
incomplete = presign(client, alice, chat, content)
complete(client, alice, incomplete['attachment_id'], digest, expected=409)
# Wrong checksum: the object is rejected and removed.
mismatch = presign(client, alice, chat, content)
check(put(mismatch['upload_url'], content) == 200, 'direct PUT failed')
complete(client, alice, mismatch['attachment_id'], '0' * 64, expected=409)
# Declared size is enforced at completion, after the direct PUT.
oversized = presign(client, alice, chat, content)
check(put(oversized['upload_url'], content + b'x') == 200, 'direct PUT failed')
complete(client, alice, oversized['attachment_id'], digest, expected=400)
# Last PUT wins before completion; the declared checksum must describe it.
overwrite = presign(client, alice, chat, content)
check(put(overwrite['upload_url'], b'not an image') == 200, 'first PUT failed')
check(put(overwrite['upload_url'], content) == 200, 'second PUT failed')
overwritten = complete(client, alice, overwrite['attachment_id'], digest)['json']
check(overwritten['sha256'] == digest, 'last PUT was not the completed object')
# A user outside the chat cannot obtain a presigned URL.
other = client.call(
'POST', '/api/v1/chats', 201, actor=alice,
body={'title': 'Приватный чат', 'member_ids': [alice['id'], eve['id']]}, schema='Chat',
)['json']
client.call(
'POST', '/api/v1/chats/' + other['id'] + '/attachments/presign', 404,
actor=bob,
body={
'filename': 'x.png', 'content_type': 'image/png',
'size_bytes': len(content), 'sha256': digest,
},
)
wait = float(os.environ.get('PRESIGN_EXPIRY_WAIT', '0'))
if wait > 0:
expired = presign(client, alice, chat, content)
time.sleep(wait)
status = put(expired['upload_url'], content)
check(status == 403, 'expired presigned URL must be 403, got ' + str(status))
print('EXPIRED: presigned URL rejected after', wait, 'seconds')
print('PASS: lab4 presigned upload flow')
if __name__ == '__main__':
run(main)
+1 -1
View File
@@ -18,7 +18,7 @@ def compose(*args, check=True):
def containers_by_hostname(service='api'):
"""{hostname: {id, name, status}} для контейнеров сервиса."""
project = os.environ.get('COMPOSE_PROJECT_NAME', 'mtusi-messenger-lab3')
project = os.environ.get('COMPOSE_PROJECT_NAME', 'mtusi-messenger-lab4')
listed = subprocess.run(
[
'docker', 'ps', '-q',