forked from mtusi2026/mtusi2026lab4
Реализовать ЛР 4 на 3: приватное S3 и вложения — Гавриленко БПИ2303
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
"""Stop exactly the replica that accepted the upload; repeat for both replicas."""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, Failure, arguments
|
||||
|
||||
args = arguments('Upload replica failover')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
a, b, eve, chat = c.bootstrap()
|
||||
data = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
ids = subprocess.check_output(['docker', 'compose', 'ps', '-q', 'api'], text=True).split()
|
||||
assert len(ids) == 2
|
||||
for container in ids:
|
||||
target = subprocess.check_output(['docker', 'inspect', '--format', '{{.Config.Hostname}}', container], text=True).strip()
|
||||
try:
|
||||
for attempt in range(30):
|
||||
result = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=failover.png', 201,
|
||||
actor=a, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
if result['headers']['X-Instance-Id'] == target:
|
||||
break
|
||||
else:
|
||||
raise AssertionError('Upload did not reach target replica')
|
||||
subprocess.run(['scripts/stop-one.sh'], env={**os.environ, 'TARGET_INSTANCE_ID': target}, check=True, stdout=subprocess.DEVNULL)
|
||||
deadline = time.monotonic() + 10
|
||||
while True:
|
||||
try:
|
||||
download = c.call('GET', '/api/v1/attachments/' + result['json']['id'] + '/content', actor=b)
|
||||
break
|
||||
except Failure:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.2)
|
||||
assert download['headers']['X-Instance-Id'] != target
|
||||
assert download['bytes'] == data
|
||||
state = subprocess.check_output(['docker', 'inspect', '--format', '{{.State.Running}}', container], text=True).strip()
|
||||
assert state == 'false'
|
||||
print('PASS: upload on ' + target + ', stopped that container, identical download on ' + download['headers']['X-Instance-Id'])
|
||||
finally:
|
||||
subprocess.run(['docker', 'compose', 'up', '-d', '--wait'], check=True)
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Run with .venv/bin/python against the real Compose stack."""
|
||||
import hashlib
|
||||
import io
|
||||
import struct
|
||||
import sys
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
from PIL import Image
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments
|
||||
|
||||
args = arguments('Attachment limits, formats, ACL and message retries')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
a, b, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
|
||||
png = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
def upload(data, status=201, mime='image/png', filename='photo.png', actor=a):
|
||||
return c.call('POST', path + quote(filename, safe=''), status, actor=actor,
|
||||
raw=data, headers={'Content-Type': mime}, schema='Attachment' if status == 201 else None)
|
||||
|
||||
att = upload(png, filename='Фото.png')['json']
|
||||
for actor in (a, b):
|
||||
result = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=actor)
|
||||
assert result['bytes'] == png and result['headers'].get_content_type() == 'image/png'
|
||||
assert hashlib.sha256(result['bytes']).hexdigest() == att['sha256']
|
||||
for suffix in ('', '/content'):
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 401)
|
||||
upload(png, 404, actor=eve)
|
||||
for filename in ('../a.png', 'a/b.png', 'a\\b.png', 'a\x00.png', 'a\n.png', 'a\x7f.png', '', 'a' * 256):
|
||||
upload(png, 400, filename=filename)
|
||||
upload(png, 415, mime='image/jpeg')
|
||||
upload(b'not an image', 415)
|
||||
upload(png[:50], 415)
|
||||
upload(b'GIF89a' + b'\0' * 100, 415)
|
||||
upload(png, 415, mime='application/octet-stream')
|
||||
# Header-only request exercises rejection before reading an oversized body.
|
||||
c.call('POST', path + 'huge.png', 413, actor=a, raw=b'',
|
||||
headers={'Content-Type': 'image/png', 'Content-Length': str(10485761)})
|
||||
|
||||
def chunk(name, data):
|
||||
return struct.pack('>I', len(data)) + name + data + struct.pack('>I', zlib.crc32(name + data))
|
||||
|
||||
huge = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 8000, 5001, 8, 2, 0, 0, 0)) + chunk(b'IDAT', b'') + chunk(b'IEND', b'')
|
||||
upload(huge, 413)
|
||||
# Both valid formats, byte and pixel boundaries; bounded compressed fixtures.
|
||||
for size, fmt, mime in (((40, 20), 'JPEG', 'image/jpeg'), ((8000, 5000), 'PNG', 'image/png')):
|
||||
output = io.BytesIO()
|
||||
Image.new('RGB', size).save(output, format=fmt)
|
||||
data = output.getvalue()
|
||||
item = upload(data, mime=mime)['json']
|
||||
assert c.call('GET', '/api/v1/attachments/' + item['id'] + '/content', actor=b)['bytes'] == data
|
||||
padded = png + bytes(10485760 - len(png))
|
||||
assert upload(padded)['json']['size_bytes'] == 10485760
|
||||
|
||||
message = c.message(a, chat, '', key='attachment-retry', attachments=[att['id']])['json']
|
||||
assert c.message(a, chat, '', key='attachment-retry', attachments=[att['id']])['json'] == message
|
||||
assert message['attachment_ids'] == [att['id']]
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=a,
|
||||
body={'text': 'changed', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': 'attachment-retry'})
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=a, body={'title': 'other', 'member_ids': [a['id']]}, schema='Chat')['json']
|
||||
for ids, status in (([att['id']], 404), ([str(uuid.uuid4())], 404), ([att['id']] * 2, 400), (['bad'], 400)):
|
||||
c.call('POST', '/api/v1/chats/' + other['id'] + '/messages', status, actor=a,
|
||||
body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', 404, actor=a)
|
||||
print('PASS: PNG/JPEG byte equality, ACL, unsafe filenames, MIME/corruption, 10 MiB and 40M pixel boundaries, attachment-only messages and retries')
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Additional checks against a running lab4 server."""
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments
|
||||
|
||||
args = arguments('Additional validation checks')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
a, b, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
c.call('POST', '/api/v1/users', 400, body={'username': 'BAD', 'display_name': 'X'})
|
||||
c.call('POST', '/api/v1/users', 400, body={'username': 'valid_name', 'display_name': ' '})
|
||||
c.call('POST', '/api/v1/users', 400, body=dict(a['registration'], extra=True))
|
||||
c.call('POST', path, 400, actor=a, body={'text': ' '}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
c.call('POST', path, 400, actor=a, body={'text': 'ok', 'sender_id': b['id']}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
c.call('GET', path, 404, actor=eve)
|
||||
c.call('GET', path + '?cursor=bad', 400, actor=a)
|
||||
c.call('GET', path + '?limit=1.5', 400, actor=a)
|
||||
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': str(uuid.uuid4())})
|
||||
for i in range(5):
|
||||
c.message(a, chat, 'Юникод 👋 ' + str(i))
|
||||
p = c.call('GET', path + '?limit=2', actor=b, schema='MessagePage')['json']
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=a, body={'title': 'other', 'member_ids': [a['id']]}, schema='Chat')['json']
|
||||
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + p['next_cursor'], 400, actor=a)
|
||||
items = p['items']
|
||||
while p['next_cursor']:
|
||||
p = c.call('GET', path + '?limit=2&cursor=' + p['next_cursor'], actor=b, schema='MessagePage')['json']
|
||||
items += p['items']
|
||||
assert len(items) == len({x['id'] for x in items}) == 5
|
||||
print('PASS: validation, access, Unicode, pagination and cursor scope')
|
||||
c.call('POST', '/api/v1/users', 400, raw=b'{', headers={'Content-Type': 'application/json'})
|
||||
c.call('POST', '/api/v1/users', 409, body=a['registration'])
|
||||
print('PASS: malformed JSON and duplicate username')
|
||||
import base64
|
||||
# All 128 Unicode code points, including colon, must survive KDF without truncation.
|
||||
registration = {'username': 'unicode_' + uuid.uuid4().hex[:12], 'display_name': 'Unicode', 'password': ':' + '🔐' * 127}
|
||||
u = c.call('POST', '/api/v1/users', 201, body=registration, schema='User')['json']
|
||||
credential = base64.b64encode((u['username'] + ':' + registration['password']).encode()).decode()
|
||||
session = c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
|
||||
assert session['user'] == u
|
||||
c.call('POST', '/api/v1/users', 400, body=dict(registration, password='a' * 11))
|
||||
c.call('POST', '/api/v1/users', 400, body=dict(registration, password='a' * 129))
|
||||
# Creating a chat with a missing participant must leave no visible chat behind.
|
||||
before = c.call('GET', '/api/v1/chats?limit=100', actor=a, schema='ChatPage')['json']
|
||||
for members in ([a['id'], str(uuid.uuid4())], [a['id'], a['id']], [b['id']]):
|
||||
c.call('POST', '/api/v1/chats', 400, actor=a, body={'title': 'invalid', 'member_ids': members})
|
||||
assert c.call('GET', '/api/v1/chats?limit=100', actor=a, schema='ChatPage')['json'] == before
|
||||
print('PASS: Unicode/colon passwords, length boundaries, invalid chat creation')
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Run inside API container: migrations, constraints, rollback and password storage."""
|
||||
import sys
|
||||
import uuid
|
||||
sys.path.insert(0, '/app/src')
|
||||
import psycopg
|
||||
from db import connect, migrate
|
||||
|
||||
|
||||
def counts():
|
||||
with connect() as db:
|
||||
return {name: db.execute('SELECT count(*) AS n FROM ' + name).fetchone()['n']
|
||||
for name in ('users', 'chats', 'chat_members', 'messages', 'sessions', 'message_keys', 'attachments', 'schema_migrations')}
|
||||
|
||||
|
||||
before = counts()
|
||||
migrate()
|
||||
migrate()
|
||||
assert counts() == before
|
||||
with connect() as db:
|
||||
assert db.execute('SELECT count(*) AS n FROM users').fetchone()['n'] > 0
|
||||
assert db.execute('SELECT 1 FROM users WHERE octet_length(password_salt) != 16 OR octet_length(password_hash) != 64').fetchone() is None
|
||||
assert db.execute('SELECT 1 FROM sessions WHERE octet_length(token_hash) != 32').fetchone() is None
|
||||
chat_id = uuid.uuid4()
|
||||
try:
|
||||
with connect() as db:
|
||||
db.execute('INSERT INTO chats (id,title) VALUES (%s,%s)', (chat_id, 'rollback check'))
|
||||
db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat_id, uuid.uuid4()))
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Foreign key did not reject missing member')
|
||||
with connect() as db:
|
||||
assert db.execute('SELECT 1 FROM chats WHERE id=%s', (chat_id,)).fetchone() is None
|
||||
assert counts() == before
|
||||
print('PASS: repeated migrations preserve row counts; scrypt/token digests; FK and transaction rollback')
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Run against an API started with SESSION_TTL_SECONDS=2; tokens never printed."""
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments
|
||||
|
||||
args = arguments('Short-TTL session expiry')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
a = c.user('expiry')
|
||||
c.call('GET', '/api/v1/users/me', actor=a, schema='User')
|
||||
time.sleep(3)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=a)
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=a)
|
||||
print('PASS: session expires with TTL=2; expired token cannot read or logout')
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Concurrent retries through the LB must reach different real API processes."""
|
||||
import sys
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments
|
||||
|
||||
args = arguments('Shared idempotency across replicas')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
a, b, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
key = uuid.uuid4().hex
|
||||
|
||||
|
||||
def send(i):
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
body = {'text': 'Один результат 👋'}
|
||||
if i % 2:
|
||||
body['attachment_ids'] = []
|
||||
return client.call('POST', path, 201, actor=a, body=body,
|
||||
headers={'Idempotency-Key': key}, schema='Message')
|
||||
|
||||
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
responses = list(pool.map(send, range(32)))
|
||||
assert len({r['headers']['X-Instance-Id'] for r in responses}) >= 2
|
||||
assert all(r['json'] == responses[0]['json'] for r in responses)
|
||||
page = c.call('GET', path, actor=b, schema='MessagePage')['json']
|
||||
assert page['items'] == [responses[0]['json']]
|
||||
c.call('POST', path, 409, actor=a, body={'text': 'Другой текст'}, headers={'Idempotency-Key': key})
|
||||
c.call('POST', path, 404, actor=eve, body={'text': 'Один результат 👋'}, headers={'Idempotency-Key': key})
|
||||
other = c.message(b, chat, 'Другой пользователь', key=key)['json']
|
||||
assert other['id'] != responses[0]['json']['id']
|
||||
second_chat = c.call('POST', '/api/v1/chats', 201, actor=a,
|
||||
body={'title': 'Другой чат', 'member_ids': [a['id']]}, schema='Chat')['json']
|
||||
assert c.message(a, second_chat, 'Другой чат', key=key)['json']['id'] != other['id']
|
||||
for bad_key in ('', 'has spaces', 'x' * 129):
|
||||
c.call('POST', path, 400, actor=a, body={'text': 'Invalid key'}, headers={'Idempotency-Key': bad_key})
|
||||
print('PASS: 32 concurrent retries across >=2 replicas: one message; conflict, access, key scope and validation')
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Stop the actual S3 container, probe API directly internally, then restore S3."""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments
|
||||
|
||||
args = arguments('Real S3 outage')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
a, b, eve, chat = c.bootstrap()
|
||||
att, data = c.attachment(a, chat)
|
||||
probe = r'''
|
||||
import json, sys, urllib.request, urllib.error
|
||||
sys.path.insert(0, '/app/src')
|
||||
from db import connect
|
||||
info = json.load(sys.stdin)
|
||||
def call(method, path, expected, data=None, mime=None):
|
||||
headers = {'Authorization': 'Bearer ' + info['token']}
|
||||
if mime: headers['Content-Type'] = mime
|
||||
request = urllib.request.Request('http://localhost:8080' + path, method=method, data=data, headers=headers)
|
||||
try: response = urllib.request.urlopen(request, timeout=10)
|
||||
except urllib.error.HTTPError as exc: response = exc
|
||||
with response:
|
||||
body = json.load(response)
|
||||
assert response.code == expected, (path, response.code)
|
||||
assert response.headers['X-Request-Id']
|
||||
if expected >= 400:
|
||||
assert body['error']['code'] == 'unavailable'
|
||||
assert body['error']['request_id'] == response.headers['X-Request-Id']
|
||||
with connect() as db:
|
||||
before = db.execute('SELECT count(*) AS n FROM attachments').fetchone()['n']
|
||||
call('GET', '/health/live', 200)
|
||||
call('GET', '/health/ready', 503)
|
||||
call('GET', '/api/v1/attachments/' + info['attachment'] + '/content', 503)
|
||||
# Small valid PNG copied from test fixture through stdin, no host path mount.
|
||||
import base64
|
||||
call('POST', '/api/v1/chats/' + info['chat'] + '/attachments?filename=outage.png', 503,
|
||||
base64.b64decode(info['data']), 'image/png')
|
||||
with connect() as db:
|
||||
assert db.execute('SELECT count(*) AS n FROM attachments').fetchone()['n'] == before
|
||||
print('PASS: actual S3 stop -> live 200, ready/upload/content 503 with request IDs; no new metadata')
|
||||
'''
|
||||
import base64
|
||||
try:
|
||||
subprocess.run(['docker', 'compose', 'stop', 's3'], check=True)
|
||||
subprocess.run(['docker', 'compose', 'exec', '-T', '--index', '1', 'api', 'python', '-c', probe],
|
||||
input=json.dumps({'token': a['token'], 'chat': chat['id'], 'attachment': att['id'], 'data': base64.b64encode(data).decode()}).encode(), check=True)
|
||||
finally:
|
||||
subprocess.run(['docker', 'compose', 'up', '-d', '--wait'], check=True)
|
||||
assert c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=b)['bytes'] == data
|
||||
print('PASS: S3 recovery preserves original bytes')
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Run in an API container: python - < student-tests/storage.py."""
|
||||
import hashlib
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
sys.path.insert(0, '/app/src')
|
||||
from db import connect
|
||||
from storage import s3, BUCKET
|
||||
|
||||
with connect() as db:
|
||||
rows = db.execute('SELECT object_key, size_bytes, sha256 FROM attachments').fetchall()
|
||||
assert rows
|
||||
for row in rows:
|
||||
response = s3.get_object(Bucket=BUCKET, Key=row['object_key'])
|
||||
with response['Body'] as stream:
|
||||
data = stream.read(10485761)
|
||||
assert len(data) == row['size_bytes'] and hashlib.sha256(data).hexdigest() == row['sha256']
|
||||
try:
|
||||
urllib.request.urlopen(s3.meta.endpoint_url + '/' + BUCKET + '/' + row['object_key'], timeout=5)
|
||||
except urllib.error.HTTPError as exc:
|
||||
assert exc.code == 403
|
||||
else:
|
||||
raise AssertionError('Anonymous download succeeded')
|
||||
print('PASS: all persisted attachments match S3 size/SHA256; anonymous GET of every known object returns 403')
|
||||
Reference in New Issue
Block a user