forked from mtusi2026/mtusi2026lab4
lab4
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
"""Контракт файлов: реальные изображения, лимиты, ACL и ключи сообщений."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import http.client
|
||||
import io
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
from urllib.parse import quote, urlsplit
|
||||
import uuid
|
||||
import zlib
|
||||
|
||||
from PIL import Image
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Attachment negative and concurrent checks')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/'+chat['id']+'/attachments?filename='
|
||||
png = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
headers = {'Content-Type': 'image/png'}
|
||||
att = c.call('POST', path+'sample.png', 201, actor=alice, raw=png, headers=headers, schema='Attachment')['json']
|
||||
check('object_key' not in att and 'url' not in att, 'private storage details leaked')
|
||||
for filename in ['../a.png', 'a\\b.png', 'x\x00.png', 'x\n.png', '..', ' ']:
|
||||
c.call('POST', path+quote(filename, safe=''), 400, actor=alice, raw=png, headers=headers)
|
||||
for data, mime in [(b'not an image', 'image/png'), (png[:30], 'image/png'),
|
||||
(png[:-12], 'image/png'), (png, 'image/jpeg'), (png, 'application/octet-stream')]:
|
||||
c.call('POST', path+'invalid.png', 415, actor=alice, raw=data, headers={'Content-Type': mime})
|
||||
jpeg = io.BytesIO()
|
||||
Image.new('RGB', (64, 64), 'red').save(jpeg, format='JPEG')
|
||||
data = jpeg.getvalue()
|
||||
j = c.call('POST', path+'real.jpg', 201, actor=alice, raw=data,
|
||||
headers={'Content-Type': 'image/jpeg'}, schema='Attachment')['json']
|
||||
downloaded = c.call('GET', '/api/v1/attachments/'+j['id']+'/content', actor=bob)
|
||||
check(downloaded['bytes'] == data, 'JPEG bytes changed')
|
||||
c.call('POST', path+'broken.jpg', 415, actor=alice, raw=data[:-20], headers={'Content-Type': 'image/jpeg'})
|
||||
# Валидный IHDR заявляет >40M пикселей. Отклонение происходит до декодирования.
|
||||
ihdr = struct.pack('>IIBBBBB', 9000, 5000, 8, 2, 0, 0, 0)
|
||||
header = b'\x89PNG\r\n\x1a\n' + struct.pack('>I', len(ihdr)) + b'IHDR' + ihdr
|
||||
header += struct.pack('>I', zlib.crc32(b'IHDR'+ihdr))
|
||||
header += png[33:]
|
||||
c.call('POST', path+'huge-pixels.png', 413, actor=alice, raw=header, headers=headers)
|
||||
# Отправляем только headers заведомо большого файла: доказываем ранний byte limit.
|
||||
base = urlsplit(c.base)
|
||||
connection = http.client.HTTPConnection(base.hostname, base.port or 80, timeout=10)
|
||||
connection.putrequest('POST', path+'too-big.png')
|
||||
connection.putheader('Authorization', 'Bearer '+alice['token'])
|
||||
connection.putheader('Content-Type', 'image/png')
|
||||
connection.putheader('Content-Length', str(10485761))
|
||||
connection.endheaders()
|
||||
response = connection.getresponse()
|
||||
check(response.status == 413, 'oversized body was not rejected before reading')
|
||||
response.read(); connection.close()
|
||||
c.call('POST', path+'outsider.png', 404, actor=eve, raw=png, headers=headers)
|
||||
for suffix in ['', '/content']:
|
||||
c.call('GET', '/api/v1/attachments/'+att['id']+suffix, 404, actor=eve)
|
||||
c.call('GET', '/api/v1/attachments/'+att['id']+'/content?variant=thumbnail', 404, actor=bob)
|
||||
other_chat = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Другой чат', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
message_path = '/api/v1/chats/'+other_chat['id']+'/messages'
|
||||
c.call('POST', message_path, 404, actor=alice, body={'text': '', 'attachment_ids': [att['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
message_path = '/api/v1/chats/'+chat['id']+'/messages'
|
||||
for ids, code in [([str(uuid.uuid4())], 404), ([att['id'], att['id']], 400), ([att['id']]*11, 400)]:
|
||||
c.call('POST', message_path, code, actor=alice, body={'text': '', 'attachment_ids': ids},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
key = uuid.uuid4().hex
|
||||
def send(_):
|
||||
return Client(args.base_url).message(bob, chat, '', key=key, attachments=[att['id']])
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
replies = list(pool.map(send, range(16)))
|
||||
check(all(r['json'] == replies[0]['json'] for r in replies), 'attachment replay created different messages')
|
||||
check(len({r['headers']['X-Instance-Id'] for r in replies}) >= 2, 'attachment race did not cross replicas')
|
||||
# Отсутствие attachment_ids и [] одинаковы и для хеша повтора.
|
||||
text_key = uuid.uuid4().hex
|
||||
text_message = c.message(alice, chat, 'Только текст', key=text_key)['json']
|
||||
check(c.message(alice, chat, 'Только текст', key=text_key, attachments=[])['json'] == text_message,
|
||||
'default [] changes key semantics')
|
||||
check(att['sha256'] == hashlib.sha256(png).hexdigest(), 'wrong original checksum')
|
||||
print('PASS: PNG/JPEG, bytes/pixels limits, filename/MIME, ACL, attachment message replay')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Каждая реплика отдельно и поочерёдная замена под одним профилем нагрузки."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from scripts.benchmark import context, measure, verify_confirmations
|
||||
from scripts.stack import containers, stop, wait, command, rolling, save
|
||||
from scripts.monitor import Monitor
|
||||
|
||||
|
||||
def main():
|
||||
base = os.getenv('BASE_URL', 'http://localhost:8080')
|
||||
aliases = wait(2, base)
|
||||
results = []
|
||||
for target in aliases:
|
||||
ctx = context(base)
|
||||
# Сохраняем подтверждённую запись до отказа вместе с подтверждениями нагрузки.
|
||||
from scripts.benchmark import Client
|
||||
original = Client(base).message(ctx['actor'], ctx['chat'], 'До отказа')['json']
|
||||
attachment, content = Client(base).attachment(ctx['actor'], ctx['chat'])
|
||||
try:
|
||||
with Monitor() as monitor:
|
||||
report, confirmations = measure(base, ctx, 16, 4,
|
||||
action=lambda: stop(target), retry_writes=True)
|
||||
event = report['action_events'][0]
|
||||
successful_times = sorted(int(x) for x, count in report['successful_per_second'].items() if count)
|
||||
first = next((x for x in successful_times if x > event['end_seconds']), None)
|
||||
if first is None or first+1-event['start_seconds'] > 10:
|
||||
raise AssertionError('Recovery exceeded 10 seconds')
|
||||
stopped_host = target.split(':')[0]
|
||||
if any(r['running'] for r in containers('api') if r['hostname'] == stopped_host):
|
||||
raise AssertionError('Target is still running')
|
||||
report['first_successful_bucket_after_stop_seconds'] = first
|
||||
report['recovery_upper_bound_seconds'] = round(first+1-event['start_seconds'], 3)
|
||||
report['verification'] = verify_confirmations(base, ctx, [original, *confirmations])
|
||||
assert Client(base).call('GET', '/api/v1/attachments/'+attachment['id']+'/content',
|
||||
actor=ctx['reader'])['bytes'] == content
|
||||
report['attachment_original_verified'] = True
|
||||
report['monitor'] = monitor.samples
|
||||
report['target'] = target
|
||||
results.append(report)
|
||||
save('failures.json', results)
|
||||
finally:
|
||||
command(['docker', 'compose', 'start', 'api'])
|
||||
wait(2, base)
|
||||
ctx = context(base)
|
||||
attachment, content = Client(base).attachment(ctx['actor'], ctx['chat'])
|
||||
original = Client(base).message(ctx['actor'], ctx['chat'], '', attachments=[attachment['id']])['json']
|
||||
with Monitor() as monitor:
|
||||
report, confirmations = measure(base, ctx, 35, 4, action=rolling, retry_writes=True)
|
||||
report['verification'] = verify_confirmations(base, ctx, [original, *confirmations])
|
||||
assert Client(base).call('GET', '/api/v1/attachments/'+attachment['id']+'/content',
|
||||
actor=ctx['reader'])['bytes'] == content
|
||||
report['attachment_original_verified'] = True
|
||||
report['monitor'] = monitor.samples
|
||||
save('rolling.json', report)
|
||||
print('PASS: both API failures and rolling replacement, confirmations preserved')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Дополнения к публичному smoke. Не печатает и не сохраняет tokens."""
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def check_cursor_types(c, actor, path, cursor, schema):
|
||||
check(bool(cursor), 'test requires a real pagination cursor')
|
||||
payload = json.loads(base64.urlsafe_b64decode(cursor + '=' * (-len(cursor) % 4)))
|
||||
c.call('GET', path + '?cursor=' + quote(cursor, safe=''), actor=actor, schema=schema)
|
||||
invalid = []
|
||||
for field in ['created_at', 'id']:
|
||||
for value in [1, 1.5, None, True, [], {}, '', 'invalid']:
|
||||
invalid.append({**payload, field: value})
|
||||
invalid.extend([None, 1, True, [], 'cursor'])
|
||||
for value in invalid:
|
||||
encoded = base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip('=')
|
||||
instances = set()
|
||||
# Проверяем один и тот же cursor на обеих API за round-robin LB.
|
||||
for _ in range(8):
|
||||
response = c.call('GET', path + '?cursor=' + quote(encoded, safe=''), 400, actor=actor)
|
||||
check(response['json']['error']['code'] == 'invalid_request', 'incorrect cursor error code')
|
||||
instances.add(response['headers']['X-Instance-Id'])
|
||||
if len(instances) >= 2:
|
||||
break
|
||||
check(len(instances) >= 2, 'invalid cursor was not checked on two API instances')
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--expiry', action='store_true', help='API must run with TTL=2')
|
||||
args = arguments('Student API checks', configure)
|
||||
c = Client(args.base_url)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
if args.expiry:
|
||||
time.sleep(2.2)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
print('PASS: short TTL expiry')
|
||||
return
|
||||
registration = {'username': 'race_' + uuid4().hex[:12], 'display_name': 'Гонка',
|
||||
'password': 'Synthetic-password-42'}
|
||||
# Для гонки регистрируем оба допустимых исхода через urllib.
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
def register(_):
|
||||
req = urllib.request.Request(c.base + '/api/v1/users',
|
||||
data=json.dumps(registration).encode(),
|
||||
headers={'Content-Type': 'application/json'})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
return response.status
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
|
||||
codes = list(executor.map(register, range(8)))
|
||||
check(codes.count(201) == 1 and codes.count(409) == 7, 'username race failed')
|
||||
path = '/api/v1/chats/' + chat['id']
|
||||
c.call('POST', '/api/v1/chats', 400, actor=alice,
|
||||
body={'title': 'unknown member', 'member_ids': [alice['id'], str(uuid4())]})
|
||||
for body in [{'text': 'x', 'sender_id': eve['id']}, {'text': 4}, {'text': ' '}]:
|
||||
c.call('POST', path + '/messages', 400, actor=alice, body=body)
|
||||
c.call('GET', path + '/messages?limit=true', 400, actor=alice)
|
||||
c.call('GET', path + '/messages?cursor=not-a-cursor', 400, actor=alice)
|
||||
for n in range(3):
|
||||
c.message(alice, chat, 'read-after-write ' + str(n))
|
||||
page = c.call('GET', path + '/messages?limit=1', actor=alice, schema='MessagePage')['json']
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
c.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' +
|
||||
quote(page['next_cursor'], safe=''), 400, actor=alice)
|
||||
check_cursor_types(c, alice, path + '/messages', page['next_cursor'], 'MessagePage')
|
||||
chats = c.call('GET', '/api/v1/chats?limit=1', actor=alice, schema='ChatPage')['json']
|
||||
check_cursor_types(c, alice, '/api/v1/chats', chats['next_cursor'], 'ChatPage')
|
||||
history = c.call('GET', path + '/messages', actor=bob, schema='MessagePage')['json']['items']
|
||||
check(len(history) == 3 and history[-1]['text'] == 'read-after-write 2', 'read-after-write failed')
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
print('PASS: registration race, invalid input, cursor scope/types on two API, read-after-write, logout')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Проверка реального rollback после вставки чата и первого участника."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from uuid import uuid4
|
||||
import psycopg
|
||||
import os
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client
|
||||
from src.config import DATABASE_URL
|
||||
from src.migrate import migrate
|
||||
|
||||
migrate()
|
||||
migrate() # Повтор миграции не создаёт дубликаты.
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
user = db.execute('SELECT id FROM users LIMIT 1').fetchone()
|
||||
assert user, 'Сначала выполните smoke, чтобы создать синтетического пользователя'
|
||||
chat = uuid4()
|
||||
try:
|
||||
with db.transaction():
|
||||
db.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (chat, 'rollback test'))
|
||||
db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat, user[0]))
|
||||
# FK прерывает составную операцию ПОСЛЕ двух успешных INSERT.
|
||||
db.execute('INSERT INTO chat_members VALUES (%s,%s)', (chat, uuid4()))
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Expected foreign-key failure')
|
||||
assert db.execute('SELECT count(*) FROM chats WHERE id=%s', (chat,)).fetchone()[0] == 0
|
||||
assert db.execute('SELECT count(*) FROM chat_members WHERE chat_id=%s', (chat,)).fetchone()[0] == 0
|
||||
assert db.execute('SELECT count(*) FROM schema_migrations').fetchone()[0] == 3
|
||||
print('PASS: rollback of chat + members; migration reapplied twice')
|
||||
|
||||
c = Client(os.getenv('BASE_URL', 'http://localhost:8080'))
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
key = uuid4().hex
|
||||
original = c.message(alice, chat, 'До истечения ключа', key=key)['json']
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
# Без ожидания суток: сдвигаем именно persisted expiry, а не clock приложения.
|
||||
db.execute("UPDATE message_requests SET expires_at=now()-interval '1 second' "
|
||||
"WHERE chat_id=%s AND request_key=%s", (chat['id'], key))
|
||||
renewed = c.message(alice, chat, 'После истечения ключа', key=key)['json']
|
||||
assert renewed['id'] != original['id']
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
assert db.execute('SELECT count(*) FROM message_requests WHERE chat_id=%s AND request_key=%s',
|
||||
(chat['id'], key)).fetchone()[0] == 1
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
message = uuid4()
|
||||
try:
|
||||
with db.transaction():
|
||||
db.execute('INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s)',
|
||||
(message, chat['id'], bob['id'], 'atomic rollback'))
|
||||
# Ошибка сохранения результата должна откатить и сообщение.
|
||||
db.execute("INSERT INTO message_requests VALUES (%s,%s,%s,%s,%s,now())",
|
||||
(uuid4(), chat['id'], 'rollback', '0'*64, psycopg.types.json.Jsonb({})))
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Expected result-store failure')
|
||||
assert db.execute('SELECT count(*) FROM messages WHERE id=%s', (message,)).fetchone()[0] == 0
|
||||
print('PASS: persisted key expiry, atomic message/result rollback')
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Redis необязателен для корректности; без PostgreSQL готовность снимается."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from scripts.benchmark import context, Client
|
||||
from scripts.stack import command, wait, save, containers
|
||||
|
||||
base = os.getenv('BASE_URL', 'http://localhost:8080')
|
||||
c = Client(base)
|
||||
ctx = context(base)
|
||||
original = c.message(ctx['actor'], ctx['chat'], 'До отказов')['json']
|
||||
attachment, content = c.attachment(ctx['actor'], ctx['chat'])
|
||||
results = {}
|
||||
try:
|
||||
command(['docker', 'compose', 'stop', 'cache'])
|
||||
started = time.monotonic()
|
||||
for _ in range(6):
|
||||
c.call('GET', '/api/v1/users/me', actor=ctx['actor'], schema='User')
|
||||
c.message(ctx['actor'], ctx['chat'], 'Без Redis')
|
||||
results['redis'] = dict(status='PASS', elapsed_seconds=time.monotonic()-started)
|
||||
finally:
|
||||
command(['docker', 'compose', 'up', '-d', '--wait', 'cache'])
|
||||
try:
|
||||
command(['docker', 'compose', 'stop', 'db'])
|
||||
# Даём LB время исключить все неготовые API. Его собственный 503 может быть HTML.
|
||||
time.sleep(4)
|
||||
codes = []
|
||||
for path in ['/health/ready', '/api/v1/users/me']:
|
||||
request = urllib.request.Request(base+path, headers={'Authorization': 'Bearer '+ctx['actor']['token']})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=8) as response:
|
||||
codes.append(response.status)
|
||||
except urllib.error.HTTPError as exc:
|
||||
codes.append(exc.code)
|
||||
assert codes == [503, 503], codes
|
||||
results['postgres'] = dict(status='PASS', readiness_and_request_status=codes)
|
||||
finally:
|
||||
command(['docker', 'compose', 'up', '-d', '--wait', 'db'])
|
||||
wait(2, base)
|
||||
active = any(row['running'] for row in containers('reconciler'))
|
||||
command(['docker', 'compose', 'stop', 'reconciler'])
|
||||
try:
|
||||
command(['docker', 'compose', 'stop', 's3'])
|
||||
time.sleep(4)
|
||||
codes = []
|
||||
paths = ['/health/ready', '/api/v1/attachments/'+attachment['id']+'/content']
|
||||
for path in paths:
|
||||
request = urllib.request.Request(base+path, headers={'Authorization': 'Bearer '+ctx['actor']['token']})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=10) as response:
|
||||
codes.append(response.status)
|
||||
except urllib.error.HTTPError as exc:
|
||||
codes.append(exc.code)
|
||||
assert codes == [503, 503], codes
|
||||
results['s3'] = dict(status='PASS', readiness_and_download_status=codes)
|
||||
finally:
|
||||
command(['docker', 'compose', 'up', '-d', '--wait', 's3'])
|
||||
wait(2, base)
|
||||
if active:
|
||||
command(['docker', 'compose', 'start', 'reconciler'])
|
||||
page = c.call('GET', '/api/v1/chats/'+ctx['chat']['id']+'/messages', actor=ctx['reader'], schema='MessagePage')['json']
|
||||
assert original in page['items']
|
||||
c.call('GET', '/api/v1/users/me', actor=ctx['actor'], schema='User')
|
||||
assert c.call('GET', '/api/v1/attachments/'+attachment['id']+'/content', actor=ctx['reader'])['bytes'] == content
|
||||
results['recovery'] = 'old session and confirmed message preserved'
|
||||
save('dependencies.json', results)
|
||||
print('PASS: Redis fallback, PostgreSQL/S3 unready, old session and original preserved')
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Останавливаем именно API, принявшую upload, и скачиваем оригинал другой репликой."""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, Failure
|
||||
from scripts.stack import stop, wait, save, command
|
||||
|
||||
base = os.getenv('BASE_URL', 'http://localhost:8080')
|
||||
c = Client(base, timeout=3)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
data = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
response = c.call('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename=failover.png',
|
||||
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
target = response['headers']['X-Instance-Id']
|
||||
att = response['json']
|
||||
c.message(alice, chat, '', attachments=[att['id']])
|
||||
started = time.monotonic()
|
||||
errors = 0
|
||||
try:
|
||||
stopped = stop(target)
|
||||
while True:
|
||||
try:
|
||||
downloaded = c.call('GET', '/api/v1/attachments/'+att['id']+'/content', actor=bob)
|
||||
alias = downloaded['headers']['X-Instance-Id']
|
||||
assert alias != target and downloaded['bytes'] == data
|
||||
assert hashlib.sha256(downloaded['bytes']).hexdigest() == att['sha256']
|
||||
break
|
||||
except Failure:
|
||||
errors += 1
|
||||
if time.monotonic()-started > 10:
|
||||
raise
|
||||
time.sleep(.2)
|
||||
save('attachment_failover.json', dict(status='PASS', uploader=target, downloader=alias,
|
||||
recovery_seconds=time.monotonic()-started, failed_attempts=errors,
|
||||
original_size=len(data), checksum_verified=True, stop=stopped))
|
||||
print('PASS: upload API stopped, original downloaded by other API with existing token')
|
||||
finally:
|
||||
command(['docker', 'compose', 'start', 'api'])
|
||||
wait(2, base)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Проверки общего результата повтора через LB и несколько API."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
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('Shared idempotency through LB')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
text = 'Один результат для конкурентных повторов'
|
||||
|
||||
def send(_):
|
||||
return Client(args.base_url, args.ca_file).message(alice, chat, text, key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
responses = list(pool.map(send, range(32)))
|
||||
first = responses[0]['json']
|
||||
check(all(r['json'] == first and r['status'] == 201 for r in responses), 'replay differs')
|
||||
instances = {r['headers']['X-Instance-Id'] for r in responses}
|
||||
check(len(instances) >= 2, 'race did not cross API replicas')
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
history = c.call('GET', path, actor=bob, schema='MessagePage')['json']['items']
|
||||
check(len(history) == 1 and history[0] == first, 'concurrent replay created duplicates')
|
||||
c.call('POST', path, 409, body={'text': 'Другой текст'}, actor=alice,
|
||||
headers={'Idempotency-Key': key})
|
||||
for invalid in ['', 'bad key', 'a' * 129]:
|
||||
c.call('POST', path, 400, body={'text': text}, actor=alice,
|
||||
headers={'Idempotency-Key': invalid})
|
||||
c.call('POST', path, 400, body={'text': text}, actor=alice)
|
||||
# Тот же ключ независим для другого пользователя и другого чата.
|
||||
other = c.message(bob, chat, text, key=key)['json']
|
||||
check(other['id'] != first['id'], 'key scope must include user')
|
||||
chat2 = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Second', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
check(c.message(alice, chat2, text, key=key)['json']['id'] != first['id'], 'key scope must include chat')
|
||||
# Пробелы JSON не изменяют смысл текста и не должны менять результат.
|
||||
replay = c.call('POST', path, 201, actor=alice, raw=json.dumps({'text': text}, indent=2).encode(),
|
||||
headers={'Content-Type': 'application/json', 'Idempotency-Key': key}, schema='Message')
|
||||
check(replay['json'] == first, 'JSON formatting changed idempotency')
|
||||
c.call('POST', path, 404, actor=eve, body={'text': text}, headers={'Idempotency-Key': key})
|
||||
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
||||
c.call('POST', path, 401, actor=alice, body={'text': text}, headers={'Idempotency-Key': key})
|
||||
result = dict(status='PASS', concurrent_requests=32, observed_instances=len(instances),
|
||||
messages_after_race=len(history), conflict=409, invalid_key=400, logout=401)
|
||||
Path('evidence').mkdir(exist_ok=True)
|
||||
Path('evidence/idempotency.json').write_text(json.dumps(result, indent=2))
|
||||
print('PASS: shared idempotency, scope, conflict and auth on replay')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,237 @@
|
||||
"""Настоящие fault injection в PostgreSQL и S3, затем dry-run/apply/повтор."""
|
||||
import argparse
|
||||
import base64
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import http.client
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import uuid
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client
|
||||
from src.config import DATABASE_URL, S3_ENDPOINT, S3_BUCKET
|
||||
from src.storage import ObjectStore, PREFIX, lock_attachment, unlock_attachment
|
||||
from src.reconcile import run
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument('mode', choices=['privacy', 'interrupted', 's3-failure', 'reconcile', 'cost'])
|
||||
p.add_argument('--sizes', nargs='+', type=int, default=[100, 500, 1000])
|
||||
p.add_argument('--failed-chat-id', type=uuid.UUID)
|
||||
args = p.parse_args()
|
||||
c = Client(os.getenv('BASE_URL', 'http://localhost:8080'), timeout=30)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
data = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
md5 = base64.b64encode(hashlib.md5(data).digest()).decode()
|
||||
storage = ObjectStore()
|
||||
records = {}
|
||||
|
||||
def scan(grace=20, apply=False):
|
||||
return run(grace, apply, chat['id'])
|
||||
|
||||
def put(key):
|
||||
storage.put(io.BytesIO(data), key, len(data), 'image/png', digest, md5)
|
||||
|
||||
def upload(name, code=201):
|
||||
return c.call('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename='+name,
|
||||
code, actor=alice, raw=data, headers={'Content-Type': 'image/png'},
|
||||
schema='Attachment' if code == 201 else None)
|
||||
|
||||
def row(identifier):
|
||||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as db:
|
||||
return db.execute('SELECT * FROM attachments WHERE id=%s', (identifier,)).fetchone()
|
||||
|
||||
def seed(status='ready', active=False):
|
||||
identifier = uuid.uuid4()
|
||||
key = PREFIX + chat['id'] + '/' + str(identifier)
|
||||
put(key)
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
db.execute("INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,"
|
||||
"object_key,status,lease_until,created_at) VALUES (%s,%s,%s,'synthetic.png','image/png',"
|
||||
"%s,%s,%s,%s,clock_timestamp()+%s*interval '1 second',clock_timestamp()-interval '15 minutes')",
|
||||
(identifier, chat['id'], alice['id'], len(data), digest, key, status, 120 if active else -900))
|
||||
return dict(id=identifier, key=key)
|
||||
|
||||
if args.mode == 'interrupted':
|
||||
from urllib.parse import urlsplit
|
||||
base = urlsplit(c.base)
|
||||
connection = http.client.HTTPConnection(base.hostname, base.port or 80, timeout=5)
|
||||
connection.putrequest('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename=interrupted.png')
|
||||
connection.putheader('Authorization', 'Bearer '+alice['token'])
|
||||
connection.putheader('Content-Type', 'image/png')
|
||||
connection.putheader('Content-Length', '4096')
|
||||
connection.endheaders()
|
||||
connection.send(data[:16])
|
||||
connection.close() # Не отправляем остаток и не завершаем корректный HTTP body.
|
||||
time.sleep(.5)
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
count = db.execute('SELECT count(*) FROM attachments WHERE chat_id=%s', (chat['id'],)).fetchone()[0]
|
||||
objects = list(storage.objects(PREFIX+chat['id']+'/'))
|
||||
assert count == 0 and not objects
|
||||
print(json.dumps(dict(status='PASS', sent_bytes=16, declared_bytes=4096, metadata=0, objects=0)))
|
||||
return
|
||||
|
||||
if args.mode == 'privacy':
|
||||
original = upload('private.png')['json']
|
||||
key = row(original['id'])['object_key']
|
||||
try:
|
||||
urllib.request.urlopen(S3_ENDPOINT+'/'+S3_BUCKET+'/'+key, timeout=5)
|
||||
except urllib.error.HTTPError as exc:
|
||||
assert exc.code == 403
|
||||
else:
|
||||
raise AssertionError('Anonymous object GET succeeded')
|
||||
buckets = storage.client.list_buckets().get('Buckets', [])
|
||||
assert all(bucket['Name'] == S3_BUCKET for bucket in buckets), 'Foreign bucket listed'
|
||||
# MinIO может вернуть отфильтрованный ListBuckets, а не AccessDenied.
|
||||
try:
|
||||
storage.client.create_bucket(Bucket='forbidden-'+uuid.uuid4().hex)
|
||||
except Exception as exc:
|
||||
assert getattr(exc, 'response', {}).get('Error', {}).get('Code') == 'AccessDenied'
|
||||
else:
|
||||
raise AssertionError('API credential has bucket administration rights')
|
||||
from urllib.parse import urlsplit
|
||||
endpoint = urlsplit(S3_ENDPOINT)
|
||||
console = f'{endpoint.scheme}://{endpoint.hostname}:9001/'
|
||||
try:
|
||||
urllib.request.urlopen(console, timeout=2)
|
||||
except urllib.error.URLError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('Admin console is reachable from another container')
|
||||
print(json.dumps(dict(status='PASS', anonymous_get=403, bucket_list='filtered', create_bucket='AccessDenied',
|
||||
console='not reachable', attachment_id=original['id'])))
|
||||
return
|
||||
|
||||
if args.mode == 's3-failure':
|
||||
# Оператор временно установил deny PUT policy; GET/LIST/readiness доступны.
|
||||
upload('fault-s3.png', 503)
|
||||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as db:
|
||||
failed = db.execute("SELECT * FROM attachments WHERE chat_id=%s AND filename='fault-s3.png'",
|
||||
(chat['id'],)).fetchone()
|
||||
assert failed and failed['status'] == 'uploading'
|
||||
assert storage.head(failed['object_key']) is None
|
||||
print(json.dumps(dict(status='PASS', http_status=503, metadata='uploading', object='absent',
|
||||
chat_id=chat['id'], attachment_id=str(failed['id']))))
|
||||
return
|
||||
|
||||
if args.mode == 'cost':
|
||||
results, made = [], 0
|
||||
for size in args.sizes:
|
||||
while made < size:
|
||||
seed()
|
||||
made += 1
|
||||
scan(600, False) # Прогрев обхода.
|
||||
for repeat in range(3):
|
||||
report = scan(600, False)
|
||||
report.update(dataset_added=size, repetition=repeat+1)
|
||||
results.append(report)
|
||||
print(json.dumps(dict(status='PASS', scans=results)))
|
||||
return
|
||||
|
||||
# Используемое вложение: сообщение и готовый объект должны пережить очистку.
|
||||
if args.failed_chat_id:
|
||||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as db:
|
||||
failure = db.execute("SELECT * FROM attachments WHERE chat_id=%s AND filename='fault-s3.png'",
|
||||
(args.failed_chat_id,)).fetchone()
|
||||
assert failure and failure['status'] == 'uploading'
|
||||
db.execute("UPDATE attachments SET created_at=clock_timestamp()-interval '15 minutes',"
|
||||
"lease_until=clock_timestamp()-interval '15 minutes' WHERE id=%s", (failure['id'],))
|
||||
dry_failure = run(20, False, args.failed_chat_id)
|
||||
assert row(failure['id'])
|
||||
fixed_failure = run(20, True, args.failed_chat_id)
|
||||
assert row(failure['id']) is None and storage.head(failure['object_key']) is None
|
||||
records['s3_failure_compensation'] = dict(dry_run=dry_failure, apply=fixed_failure, metadata_removed=True)
|
||||
used = upload('used.png')['json']
|
||||
message = c.message(bob, chat, '', attachments=[used['id']])['json']
|
||||
used_row = row(used['id'])
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
db.execute("UPDATE attachments SET created_at=clock_timestamp()-interval '15 minutes' WHERE id=%s",
|
||||
(used['id'],))
|
||||
|
||||
# Ошибка UPDATE ready ПОСЛЕ успешного S3 PUT. Только тестовое имя файла.
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
db.execute("CREATE OR REPLACE FUNCTION lab4_fail_ready() RETURNS trigger LANGUAGE plpgsql AS $$ "
|
||||
"BEGIN IF NEW.filename='fault-db.png' AND NEW.status='ready' THEN "
|
||||
"RAISE EXCEPTION 'synthetic DB failure'; END IF; RETURN NEW; END; $$")
|
||||
db.execute('CREATE TRIGGER lab4_test_fail BEFORE UPDATE ON attachments '
|
||||
'FOR EACH ROW EXECUTE FUNCTION lab4_fail_ready()')
|
||||
try:
|
||||
upload('fault-db.png', 503)
|
||||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as db:
|
||||
failed = db.execute("SELECT * FROM attachments WHERE chat_id=%s AND filename='fault-db.png'",
|
||||
(chat['id'],)).fetchone()
|
||||
assert failed and failed['status'] == 'uploading' and storage.head(failed['object_key'])
|
||||
immediate = scan(20, True)
|
||||
assert row(failed['id']) and storage.head(failed['object_key'])
|
||||
records['after_put_db_failure'] = dict(http_status=503, metadata='uploading', object='present',
|
||||
immediate_cleanup=immediate)
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
db.execute("UPDATE attachments SET lease_until=clock_timestamp()-interval '15 minutes',"
|
||||
"created_at=clock_timestamp()-interval '15 minutes' WHERE id=%s", (failed['id'],))
|
||||
finally:
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
db.execute('DROP TRIGGER IF EXISTS lab4_test_fail ON attachments')
|
||||
db.execute('DROP FUNCTION IF EXISTS lab4_fail_ready()')
|
||||
|
||||
missing = upload('missing.png')['json']
|
||||
missing_message = c.message(alice, chat, '', attachments=[missing['id']])['json']
|
||||
missing_row = row(missing['id'])
|
||||
storage.delete(missing_row['object_key'])
|
||||
with psycopg.connect(DATABASE_URL) as db:
|
||||
db.execute("UPDATE attachments SET created_at=clock_timestamp()-interval '15 minutes' WHERE id=%s",
|
||||
(missing['id'],))
|
||||
|
||||
orphan_key = PREFIX + chat['id'] + '/' + str(uuid.uuid4())
|
||||
put(orphan_key)
|
||||
active = seed('uploading', active=True)
|
||||
locked = seed('uploading')
|
||||
time.sleep(20.2) # Настоящий возраст объекта S3, не фиктивный LastModified.
|
||||
fresh_key = PREFIX + chat['id'] + '/' + str(uuid.uuid4())
|
||||
put(fresh_key)
|
||||
fresh = upload('fresh.png')['json']
|
||||
with psycopg.connect(DATABASE_URL, row_factory=dict_row) as guard:
|
||||
lock_attachment(guard, locked['id']); guard.commit()
|
||||
try:
|
||||
dry = scan(20, False)
|
||||
assert storage.head(orphan_key) and row(failed['id'])
|
||||
assert row(missing['id'])['status'] == 'ready'
|
||||
applied = scan(20, True)
|
||||
assert storage.head(orphan_key) is None
|
||||
assert row(failed['id']) is None and storage.head(failed['object_key']) is None
|
||||
assert row(missing['id'])['status'] == 'missing'
|
||||
assert row(used['id']) and storage.head(used_row['object_key'])
|
||||
assert row(active['id']) and storage.head(active['key'])
|
||||
assert row(locked['id']) and storage.head(locked['key'])
|
||||
assert storage.head(fresh_key) and row(fresh['id'])
|
||||
c.call('GET', '/api/v1/attachments/'+missing['id']+'/content', 503, actor=bob)
|
||||
# После возврата именно исходных bytes reconciler может вернуть ready.
|
||||
put(missing_row['object_key'])
|
||||
repaired = scan(20, True)
|
||||
assert row(missing['id'])['status'] == 'ready'
|
||||
assert c.call('GET', '/api/v1/attachments/'+missing['id']+'/content', actor=bob)['bytes'] == data
|
||||
repeated = scan(20, True)
|
||||
assert not repeated['actions'], 'Repeat still changes already corrected state'
|
||||
page = c.call('GET', '/api/v1/chats/'+chat['id']+'/messages', actor=bob, schema='MessagePage')['json']
|
||||
assert message in page['items'] and missing_message in page['items']
|
||||
finally:
|
||||
unlock_attachment(guard, locked['id']); guard.commit()
|
||||
records.update(status='PASS', dry_run=dry, apply=applied, restore=repaired, repeat=repeated,
|
||||
used_and_fresh_preserved=True, active_lease_and_lock_preserved=True,
|
||||
missing_original_restored_by_operator=True)
|
||||
print(json.dumps(records))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Black-box grading evidence beyond the public smoke test."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def collect_messages(client, actor, chat, page_size=17):
|
||||
items = []
|
||||
cursor = None
|
||||
while True:
|
||||
path = f"/api/v1/chats/{chat['id']}/messages?limit={page_size}"
|
||||
if cursor:
|
||||
path += "&cursor=" + quote(cursor, safe="")
|
||||
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
items.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Student negative, pagination and concurrency tests")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, outsider, chat = client.bootstrap()
|
||||
|
||||
client.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
400,
|
||||
raw=b'{"username":',
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
client.call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
415,
|
||||
raw=b'{"username":"wrong_media","display_name":"Wrong"}',
|
||||
headers={"Content-Type": "text/plain"},
|
||||
)
|
||||
client.call("POST", "/api/v1/users", 409, body=alice["registration"])
|
||||
client.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
400,
|
||||
actor=alice,
|
||||
body={"text": " \t"},
|
||||
)
|
||||
client.call("GET", f"/api/v1/chats/{chat['id']}", 404, actor=outsider)
|
||||
|
||||
prefix = "race-" + uuid.uuid4().hex + "-"
|
||||
|
||||
def send(worker_id):
|
||||
local = Client(args.base_url, args.ca_file)
|
||||
return [
|
||||
local.message(alice, chat, f"{prefix}{worker_id}-{index}")["json"]
|
||||
for index in range(10)
|
||||
]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
created = [message for batch in pool.map(send, range(10)) for message in batch]
|
||||
|
||||
check(len(created) == 100, "not all concurrent requests succeeded")
|
||||
check(len({message["id"] for message in created}) == 100, "duplicate message ids returned")
|
||||
|
||||
history = collect_messages(client, bob, chat)
|
||||
concurrent_history = [message for message in history if message["text"].startswith(prefix)]
|
||||
check(len(concurrent_history) == 100, "history does not contain exactly 100 concurrent messages")
|
||||
check(len({message["id"] for message in concurrent_history}) == 100, "history contains duplicates")
|
||||
check(
|
||||
history == sorted(history, key=lambda message: (message["created_at"], uuid.UUID(message["id"]).int)),
|
||||
"multi-page history is out of order",
|
||||
)
|
||||
|
||||
print("PASS: malformed JSON/media type, duplicate username, blank message, outsider access, pagination")
|
||||
print("PASS: 10 clients created exactly 100 unique messages")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user