ЛР4 БВТ2304 Запорожец на 3

Вложения: приватный S3-bucket (RustFS 1.0.4) + метаданные в PostgreSQL, upload PNG/JPEG
с лимитами до декодирования, авторизованный download, attachment_ids в сообщениях,
идемпотентный bootstrap bucket, failover/persistence/S3-down тесты и REPORT.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 18:49:12 +03:00
co-authored by Claude Opus 5.5
parent ec540a1a72
commit 2dca5c114b
44 changed files with 3698 additions and 16 deletions
+312
View File
@@ -0,0 +1,312 @@
#!/usr/bin/env python3
"""Серии отказов под нагрузкой (уровень 4): RPS, ошибки, время обнаружения и восстановления.
Запускается на ХОСТЕ из корня репозитория (нужны docker CLI и, для rolling, compose с bind-путями):
python student-tests/failover_series.py --scenario stop # graceful stop каждой реплики по очереди
python student-tests/failover_series.py --scenario kill # SIGKILL каждой реплики по очереди
python student-tests/failover_series.py --scenario rolling # scripts/rolling-update.sh под нагрузкой
Нагрузка closed-loop: W писателей (POST сообщения; неопределённый результат повторяется с ТЕМ ЖЕ ключом,
как в tests/resilience.py) и R читателей (GET истории). Параллельно раз в 200 мс опрашивается
CSV-статистика HAProxy: когда слот целевой реплики перестал быть UP — это время обнаружения отказа LB.
После серии проверяется, что все подтверждённые сообщения на месте и нет дублей.
Токены остаются в памяти процесса; в отчёт попадают только агрегаты.
"""
import argparse
import csv
import io
import json
import math
import os
import subprocess
import sys
import threading
import time
import urllib.parse
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check # noqa: E402
PROJECT = 'mtusi-lab4'
EDGE_NETWORK = PROJECT + '_edge'
API_FILTER = ['--filter', f'label=com.docker.compose.project={PROJECT}',
'--filter', 'label=com.docker.compose.service=api']
def docker(*args: str) -> str:
return subprocess.run(['docker', *args], check=True, text=True, capture_output=True).stdout.strip()
def api_containers() -> list[str]:
names = docker('ps', *API_FILTER, '--format', '{{.Names}}').split()
return sorted(names)
def container_info(name: str) -> dict:
fmt = ('{{.Config.Hostname}}|{{index .Config.Labels "org.opencontainers.image.revision"}}|'
'{{(index .NetworkSettings.Networks "%s").IPAddress}}') % EDGE_NETWORK
hostname, revision, ip = docker('inspect', '-f', fmt, name).split('|')
return {'name': name, 'hostname': hostname, 'revision': revision, 'ip': ip}
def percentile(values: list[float], p: float):
values = sorted(values)
return round(1000 * values[max(0, math.ceil(p * len(values)) - 1)], 1) if values else None
class LbWatcher(threading.Thread):
"""Опрос /stats;csv: состояние слотов backend `api` и счётчики retry/redispatch."""
def __init__(self, stats_url: str, t0: float):
super().__init__(daemon=True)
self.url = stats_url.rstrip('/') + ';csv'
self.t0 = t0
self.stop_flag = threading.Event()
self.samples = [] # (t, {addr: status})
self.first = self.last = None
def snapshot(self):
with urllib.request.urlopen(self.url, timeout=1) as r:
rows = list(csv.DictReader(io.StringIO(r.read().decode().lstrip('# '))))
servers = {row['addr']: row['status'] for row in rows
if row['pxname'] == 'api' and row['svname'] not in ('FRONTEND', 'BACKEND') and row.get('addr')}
backend = next(row for row in rows if row['pxname'] == 'api' and row['svname'] == 'BACKEND')
return servers, {'retries': int(backend['wretr'] or 0), 'redispatches': int(backend['wredis'] or 0)}
def run(self):
while not self.stop_flag.is_set():
try:
servers, counters = self.snapshot()
self.samples.append((time.monotonic() - self.t0, servers))
self.first = self.first or counters
self.last = counters
except Exception: # LB-статистика — вспомогательная, не влияет на результат серии
pass
time.sleep(0.2)
def first_not_up(self, ip: str, after: float):
"""Первый момент после `after`, когда слот с этим IP не UP (DOWN/MAINT/исчез из DNS)."""
addr = ip + ':8080'
for t, servers in self.samples:
if t >= after and not servers.get(addr, 'MISSING').startswith('UP'):
return round(t - after, 3), servers.get(addr, 'removed from DNS')
return None, None
def run_probe(base_url: str, stats_url: str, action, targets: list[dict], duration: float,
action_at: float, writers: int, readers: int) -> dict:
c = Client(base_url)
alice, bob, _eve, chat = c.bootstrap()
events = [] # (t, kind, ok, instance, latency)
confirmed = [] # подтверждённые сообщения
lock = threading.Lock()
retries_with_same_key = [0]
t0 = time.monotonic()
deadline = t0 + duration
watcher = LbWatcher(stats_url, t0)
watcher.start()
def record(kind, ok, instance, latency):
with lock:
events.append((time.monotonic() - t0, kind, ok, instance, latency))
def writer(i):
local = Client(base_url, timeout=3)
key, n = uuid.uuid4().hex, 0
text = f'probe-{i}-{n}'
while time.monotonic() < deadline:
start = time.monotonic()
try:
r = local.message(alice, chat, text, key=key)
record('write', True, r['headers'].get('X-Instance-Id', ''), time.monotonic() - start)
with lock:
confirmed.append(r['json'])
n += 1
key, text = uuid.uuid4().hex, f'probe-{i}-{n}'
except Failure:
record('write', False, '', time.monotonic() - start)
with lock:
retries_with_same_key[0] += 1
time.sleep(0.05) # тот же key и тот же body при следующей попытке
def reader(_i):
local = Client(base_url, timeout=3)
path = f"/api/v1/chats/{chat['id']}/messages?limit=20"
while time.monotonic() < deadline:
start = time.monotonic()
try:
r = local.call('GET', path, actor=bob, schema='MessagePage')
record('read', True, r['headers'].get('X-Instance-Id', ''), time.monotonic() - start)
except Failure:
record('read', False, '', time.monotonic() - start)
time.sleep(0.05)
threads = [threading.Thread(target=writer, args=(i,)) for i in range(writers)]
threads += [threading.Thread(target=reader, args=(i,)) for i in range(readers)]
for t in threads:
t.start()
time.sleep(max(0.0, t0 + action_at - time.monotonic()))
a_start = time.monotonic() - t0
action_output = action()
a_end = time.monotonic() - t0
for t in threads:
t.join()
watcher.stop_flag.set()
watcher.join()
# Сохранность: тот же токен, полная история через LB, без дублей.
history, cursor = [], None
while True:
path = f"/api/v1/chats/{chat['id']}/messages?limit=100" + (f'&cursor={urllib.parse.quote(cursor, safe="")}' if cursor else '')
page = c.call('GET', path, actor=bob, schema='MessagePage')['json']
history += page['items']
cursor = page['next_cursor']
if cursor is None:
break
ids = {m['id'] for m in history}
texts = [m['text'] for m in history]
lost = sum(1 for m in confirmed if m['id'] not in ids)
check(len(ids) == len(history), 'duplicated message id in history')
check(len(texts) == len(set(texts)), 'retry with same key produced a duplicate message')
check(lost == 0, f'{lost} confirmed messages lost')
def window(lo, hi):
sel = [e for e in events if lo <= e[0] < hi]
ok = [e for e in sel if e[2]]
span = max(hi - lo, 1e-9)
return {'seconds': round(span, 2), 'ok_rps': round(len(ok) / span, 1),
'write_rps': round(sum(1 for e in ok if e[1] == 'write') / span, 1),
'read_rps': round(sum(1 for e in ok if e[1] == 'read') / span, 1),
'errors': len(sel) - len(ok),
'p50_ms': percentile([e[4] for e in ok], .50), 'p95_ms': percentile([e[4] for e in ok], .95),
'p99_ms': percentile([e[4] for e in ok], .99), 'max_ms': percentile([e[4] for e in ok], 1.0)}
errors = [e for e in events if not e[2]]
target_prefixes = tuple(t['hostname'] + '-' for t in targets)
served_by_target = [e[0] for e in events if e[2] and e[3].startswith(target_prefixes)]
per_second = []
for s in range(int(duration)):
sel = [e for e in events if s <= e[0] < s + 1]
per_second.append({'t': s, 'ok': sum(1 for e in sel if e[2]), 'err': sum(1 for e in sel if not e[2]),
'instances': len({e[3] for e in sel if e[2]})})
detection = {}
for t in targets:
seconds, state = watcher.first_not_up(t['ip'], a_start)
detection[t['name']] = {'lb_marked_not_up_after_s': seconds, 'lb_state': state}
lb_counters = None
if watcher.first and watcher.last:
lb_counters = {k: watcher.last[k] - watcher.first[k] for k in watcher.last}
return {
'targets': [{k: t[k] for k in ('name', 'hostname', 'revision')} for t in targets],
'action_started_s': round(a_start, 3), 'action_duration_s': round(a_end - a_start, 3),
'action_output': action_output,
'before': window(1, a_start), 'during_action_plus_5s': window(a_start, a_end + 5),
'after': window(a_end + 5, duration),
'errors_total': len(errors),
'write_attempts_retried_same_key': retries_with_same_key[0],
'error_window_s': ([round(errors[0][0] - a_start, 3), round(errors[-1][0] - a_start, 3)] if errors else None),
'recovery_s': round(errors[-1][0] - a_start, 3) if errors else 0.0,
'target_last_served_after_action_s': (round(max(served_by_target) - a_start, 3)
if served_by_target and max(served_by_target) >= a_start else None),
'lb_detection': detection,
'lb_retries_redispatches': lb_counters,
'instances_after': sorted({e[3] for e in events if e[2] and e[0] > a_end + 5}),
'confirmed_writes': len(confirmed), 'history_messages': len(history),
'duplicates': 0, 'lost_confirmed': lost,
'timeline_per_second': per_second,
}
def wait_lb_up(stats_url: str, ip: str, seconds: float = 60) -> None:
deadline = time.monotonic() + seconds
url = stats_url.rstrip('/') + ';csv'
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(url, timeout=1) as r:
rows = csv.DictReader(io.StringIO(r.read().decode().lstrip('# ')))
if any(row['pxname'] == 'api' and row.get('addr') == ip + ':8080' and row['status'].startswith('UP')
for row in rows):
return
except OSError:
pass
time.sleep(0.5)
raise Failure('replica did not return to LB rotation')
def restore(stats_url: str) -> None:
subprocess.run(['sh', str(ROOT / 'scripts/restore.sh')], check=True, capture_output=True)
for name in api_containers():
wait_lb_up(stats_url, container_info(name)['ip'])
def main() -> int:
p = argparse.ArgumentParser(description=__doc__.split('\n')[0])
p.add_argument('--scenario', choices=['stop', 'kill', 'rolling'], required=True)
p.add_argument('--base-url', default=os.environ.get('BASE_URL', 'http://localhost:8080'))
p.add_argument('--stats-url', default=os.environ.get('LB_STATS_URL', 'http://localhost:8404/stats'))
p.add_argument('--duration', type=float, default=None)
p.add_argument('--action-at', type=float, default=8)
p.add_argument('--writers', type=int, default=4)
p.add_argument('--readers', type=int, default=2)
p.add_argument('--output', default=None)
args = p.parse_args()
duration = args.duration or (45 if args.scenario == 'rolling' else 25)
runs = []
if args.scenario == 'rolling':
targets = [container_info(n) for n in api_containers()]
def action():
r = subprocess.run(['sh', str(ROOT / 'scripts/rolling-update.sh')], text=True, capture_output=True)
check(r.returncode == 0, 'rolling-update.sh failed: ' + r.stderr[-500:])
return r.stdout.strip().splitlines()
result = run_probe(args.base_url, args.stats_url, action, targets, duration, args.action_at,
args.writers, args.readers)
result['replicas_after'] = [container_info(n) for n in api_containers()]
runs.append(result)
else:
for name in api_containers(): # по очереди каждую реплику, восстанавливая предыдущую
restore(args.stats_url)
target = container_info(name)
def action(name=name):
started = time.monotonic()
if args.scenario == 'kill':
docker('kill', name)
else:
docker('stop', '-t', '20', name)
state = docker('inspect', '-f', '{{.State.Status}} exit={{.State.ExitCode}}', name)
return [f'{args.scenario} {name}: {state} in {time.monotonic() - started:.2f}s']
result = run_probe(args.base_url, args.stats_url, action, [target], duration, args.action_at,
args.writers, args.readers)
runs.append(result)
print(f"{args.scenario} {name}: errors={result['errors_total']} recovery={result['recovery_s']}s "
f"lb_detection={result['lb_detection'][name]['lb_marked_not_up_after_s']}s "
f"rps before/after={result['before']['ok_rps']}/{result['after']['ok_rps']}", flush=True)
restore(args.stats_url)
report = {
'scenario': args.scenario, 'date_utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
'profile': {'duration_s': duration, 'action_at_s': args.action_at, 'writers': args.writers,
'readers': args.readers, 'client_timeout_s': 3,
'workload': 'closed-loop: POST message (retry same key on failure) + GET history limit=20'},
'runs': runs,
}
text = json.dumps(report, ensure_ascii=False, indent=2)
if args.output:
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
Path(args.output).write_text(text + '\n', encoding='utf-8')
summary = [{k: r[k] for k in ('targets', 'errors_total', 'recovery_s', 'lb_detection', 'action_duration_s',
'target_last_served_after_action_s', 'lb_retries_redispatches')}
| {'rps_before': r['before']['ok_rps'], 'rps_after': r['after']['ok_rps'],
'p99_during_ms': r['during_action_plus_5s']['p99_ms']} for r in runs]
print(json.dumps(summary, ensure_ascii=False, indent=1))
return 0
if __name__ == '__main__':
sys.exit(main())
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env python3
"""Один вход (одна сессия) -> 10 запросов через LB: какие реплики обслужили. Токен не печатается."""
import os
import sys
from collections import Counter
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client # noqa: E402
c = Client(os.environ.get('BASE_URL', 'http://lb:8080'))
alice = c.user('instances')
served = [c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id'] for _ in range(10)]
print('X-Instance-Id sequence:', ' '.join(served))
print('distinct replicas for one session without re-login:', dict(Counter(served)))
+256
View File
@@ -0,0 +1,256 @@
#!/usr/bin/env python3
"""Регрессия: собственные проверки уровня 4 из lab2, перенесённые на стенд lab3 (через LB).
Запуск: sh scripts/test-lab3.sh (внутри сервиса tester).
Требуют запущенный стенд и доступ к docker (останавливают/ставят на паузу valkey и postgres,
затем возвращают их). Используют только синтетические данные.
"""
import base64
import hashlib
import os
import subprocess
import sys
import threading
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check # noqa: E402
BASE_URL = os.environ.get('BASE_URL', 'http://lb:8080')
TTL_BASE_URL = os.environ.get('TTL_BASE_URL', 'http://api-ttl:8080')
VALKEY_CLI = 'valkey-cli --no-auth-warning -a "$(sed -n "s/^requirepass //p" /run/secrets/valkey_conf)" '
def compose(*args: str, capture: bool = False) -> str:
result = subprocess.run(['docker', 'compose', '--env-file', str(ROOT / '.env'), *args],
cwd=ROOT, check=True, text=True,
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
return (result.stdout or '').strip()
def sql(query: str) -> str:
return compose('exec', '-T', 'postgres', 'psql', '-U', 'app', '-d', 'messenger', '-tAc', query, capture=True)
def valkey(command: str) -> str:
return compose('exec', '-T', 'valkey', 'sh', '-c', VALKEY_CLI + command, capture=True)
def basic(username: str, password: str) -> dict:
return {'Authorization': 'Basic ' + base64.b64encode(f'{username}:{password}'.encode()).decode()}
def wait_ready(c: Client, seconds: float = 60) -> None:
deadline = time.monotonic() + seconds
while True:
try:
c.call('GET', '/health/ready', schema='Health')
return
except Failure:
check(time.monotonic() < deadline, 'API did not become ready')
time.sleep(0.5)
def wait_healthy(service: str, seconds: float = 60) -> None:
deadline = time.monotonic() + seconds
container = compose('ps', '-q', service, capture=True)
while subprocess.run(['docker', 'inspect', '-f', '{{.State.Health.Status}}', container],
text=True, capture_output=True).stdout.strip() != 'healthy':
check(time.monotonic() < deadline, service + ' did not become healthy')
time.sleep(0.5)
def cache_key(actor: dict) -> str:
return 'session:' + hashlib.sha256(actor['token'].encode()).hexdigest()
def wait_cache_used(c: Client, actor: dict, seconds: float = 75) -> None:
"""После недавнего сбоя Valkey API законно не доверяет кэшу SESSION_CACHE_TTL_SECONDS — ждём конца окна."""
deadline = time.monotonic() + seconds
while True:
c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
if valkey('EXISTS ' + cache_key(actor)) == '1':
return
check(time.monotonic() < deadline, 'session was never cached in Valkey')
time.sleep(2)
def bearer(token: str) -> dict:
return {'Authorization': 'Bearer ' + token}
# ---------------------------------------------------------------- тесты
def test_wrong_password(c: Client):
alice = c.user('wrongpw')
username = alice['registration']['username']
wrong = c.call('POST', '/api/v1/auth/sessions', 401, headers=basic(username, 'definitely-wrong-password'))
unknown = c.call('POST', '/api/v1/auth/sessions', 401, headers=basic('no_such_' + uuid.uuid4().hex[:8], 'whatever-password-123'))
# Одинаковый ответ: по нему нельзя узнать, существует ли username.
check(wrong['json']['error']['message'] == unknown['json']['error']['message'], 'different 401 for unknown user')
check(wrong['headers']['WWW-Authenticate'] == 'Basic realm="messenger", charset="UTF-8"', 'wrong Basic challenge')
c.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': 'Basic !!!not-base64'})
c.call('POST', '/api/v1/auth/sessions', 401, headers=bearer(alice['token'])) # Bearer на входе не принимается
def test_logout(c: Client):
alice = c.user('logout')
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
r = c.call('GET', '/api/v1/users/me', 401, actor=alice)
check(r['headers']['WWW-Authenticate'] == 'Bearer realm="messenger"', 'wrong Bearer challenge')
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=alice)
revoked = sql("SELECT count(*) FROM sessions s JOIN users u ON u.id = s.user_id "
f"WHERE u.username = '{alice['registration']['username']}' AND s.revoked_at IS NOT NULL")
check(revoked == '1', 'revocation not recorded in PostgreSQL')
def test_short_ttl(_c: Client):
# Отдельная реплика api-ttl с SESSION_TTL_SECONDS=2, общая БД и кэш.
c = Client(TTL_BASE_URL)
wait_ready(c)
alice = c.user('ttl')
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
time.sleep(3)
c.call('GET', '/api/v1/users/me', 401, actor=alice)
def test_username_race(c: Client):
username = 'race_' + uuid.uuid4().hex[:12]
body = {'username': username, 'display_name': 'Гонка', 'password': 'Race-password-' + uuid.uuid4().hex}
statuses, barrier = [], threading.Barrier(16)
def register():
barrier.wait()
statuses.append(Client(BASE_URL, timeout=30).call('POST', '/api/v1/users', [201, 409], body=body)['status'])
threads = [threading.Thread(target=register) for _ in range(16)]
for t in threads:
t.start()
for t in threads:
t.join()
check(sorted(statuses) == [201] + [409] * 15, f'race result {sorted(statuses)}')
check(sql(f"SELECT count(*) FROM users WHERE username = '{username}'") == '1', 'duplicate username row')
def test_chat_rollback(c: Client):
alice = c.user('rollback')
before = sql('SELECT (SELECT count(*) FROM chats) || \' \' || (SELECT count(*) FROM chat_members)')
# Второй участник не существует: INSERT chats уже выполнен, INSERT chat_members вставит 1 из 2 -> ROLLBACK.
c.call('POST', '/api/v1/chats', 400, actor=alice,
body={'title': 'Откат', 'member_ids': [alice['id'], str(uuid.uuid4())]})
after = sql('SELECT (SELECT count(*) FROM chats) || \' \' || (SELECT count(*) FROM chat_members)')
check(before == after, f'partial chat left after failure: {before} -> {after}')
listed = c.call('GET', '/api/v1/chats', actor=alice, schema='ChatPage')['json']
check(listed['items'] == [], 'failed chat is visible')
def test_cursor_rules(c: Client):
alice, bob, _eve, chat = c.bootstrap()
other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой', 'member_ids': [alice['id']]},
schema='Chat')['json']
for i in range(3):
c.message(alice, chat, f'm{i}')
c.message(alice, other, f'o{i}')
page = c.call('GET', f'/api/v1/chats/{chat["id"]}/messages?limit=1', actor=alice, schema='MessagePage')['json']
from urllib.parse import quote
cursor = quote(page['next_cursor'], safe='')
c.call('GET', f'/api/v1/chats/{other["id"]}/messages?cursor={cursor}', 400, actor=alice) # курсор чужого чата
c.call('GET', f'/api/v1/chats/{chat["id"]}/messages?cursor=garbage', 400, actor=alice)
c.call('GET', f'/api/v1/chats/{chat["id"]}/messages?limit=101', 400, actor=alice)
c.call('POST', '/api/v1/chats', 400, actor=alice, body={'title': 'x', 'member_ids': [alice['id']], 'extra': 1})
c.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 400, actor=bob, body={'text': 'x', 'sender_id': alice['id']})
def test_valkey_cache_role(c: Client):
alice = c.user('cache')
wait_cache_used(c, alice)
ttl = int(valkey('TTL ' + cache_key(alice)))
check(0 < ttl <= 60, f'unexpected cache TTL {ttl}')
valkey('FLUSHALL') # потеря всего кэша
c.call('GET', '/api/v1/users/me', actor=alice, schema='User') # источник истины — PostgreSQL
check(valkey('EXISTS ' + cache_key(alice)) == '1', 'cache was not refilled on miss')
def test_valkey_down(c: Client):
alice = c.user('vkdown')
try:
compose('stop', 'valkey')
c.call('GET', '/api/v1/users/me', actor=alice, schema='User') # обход кэша через PostgreSQL
c.call('GET', '/api/v1/users/me', 401, headers=bearer('A' * 43)) # неизвестный токен — не доверяем
c.call('GET', '/api/v1/users/me', 401) # аноним — 401
bob = c.user('vkdown_login') # вход работает без кэша
c.call('GET', '/health/ready', schema='Health') # Valkey не критичен
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=bob)
c.call('GET', '/api/v1/users/me', 401, actor=bob)
finally:
compose('start', 'valkey')
wait_healthy('valkey')
def test_revoke_during_cache_partition(c: Client):
# Худший случай инвалидации: logout во время разрыва API <-> Valkey, DEL потерян, а копия отозванной
# сессии в Valkey пережила разрыв. Окно недоверия к кэшу (SESSION_CACHE_TTL_SECONDS после ошибки)
# не даёт её использовать. TCP может доставить DEL повторной передачей после восстановления сети,
# поэтому потерю DEL моделируем явно: возвращаем сохранённую до разрыва копию записи.
alice = c.user('partition')
wait_cache_used(c, alice)
key = cache_key(alice)
stale_value = valkey('GET ' + key)
container = compose('ps', '-q', 'valkey', capture=True)
network = 'mtusi-lab4_data' # Valkey в lab3 только во внутренней сети data
subprocess.run(['docker', 'network', 'disconnect', network, container], check=True)
try:
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice) # COMMIT в PostgreSQL прошёл
finally:
subprocess.run(['docker', 'network', 'connect', '--alias', 'valkey', network, container], check=True)
valkey(f"SET {key} '{stale_value}' EX 60")
c.call('GET', '/api/v1/users/me', 401, actor=alice)
def test_postgres_down(c: Client):
alice = c.user('pgdown')
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')
try:
compose('stop', 'postgres')
c.call('GET', '/health/live', schema='Health')
c.call('GET', '/health/ready', 503)
r = c.call('GET', '/api/v1/users/me', 503, actor=alice) # ограниченная ошибка, не 500/200
check(r['json']['error']['code'] == 'unavailable', 'expected unavailable')
c.call('GET', '/api/v1/users/me', 503, headers=bearer('B' * 43)) # неизвестный токен не проходит
c.call('GET', '/api/v1/chats', 401) # аноним не пропускается
c.call('POST', '/api/v1/users', 503, body={'username': 'pg_' + uuid.uuid4().hex[:8],
'display_name': 'x', 'password': 'Password-123456'})
finally:
compose('start', 'postgres')
wait_ready(c)
c.call('GET', '/api/v1/users/me', actor=alice, schema='User') # та же сессия жива после рестарта БД
TESTS = [test_wrong_password, test_logout, test_short_ttl, test_username_race, test_chat_rollback,
test_cursor_rules, test_valkey_cache_role, test_revoke_during_cache_partition, test_valkey_down,
test_postgres_down]
def main() -> int:
c = Client(BASE_URL)
wait_ready(c)
failed = 0
for test in TESTS:
started = time.monotonic()
try:
test(c)
print(f'PASS {test.__name__} ({time.monotonic() - started:.1f}s)')
except (Failure, subprocess.CalledProcessError, OSError) as exc:
failed += 1
print(f'FAIL {test.__name__}: {exc}')
print(f'{len(TESTS) - failed}/{len(TESTS)} passed')
return 1 if failed else 0
if __name__ == '__main__':
sys.exit(main())
+280
View File
@@ -0,0 +1,280 @@
#!/usr/bin/env python3
"""Собственные проверки lab3 (уровни 3–4), в lab4 — регрессия. Запуск: sh scripts/test-lab4.sh (внутри сервиса tester).
Обращаются к репликам и НАПРЯМУЮ (по IP из DNS Docker внутри сети edge), чтобы гарантировать, что
конкурентные повторы действительно приходят в разные процессы, а не полагаться на round-robin LB.
Требуют доступ к docker (останавливают postgres, шлют SIGTERM реплике и возвращают всё обратно).
"""
import json
import os
import socket
import subprocess
import sys
import threading
import time
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, Failure, check # noqa: E402
BASE_URL = os.environ.get('BASE_URL', 'http://lb:8080')
PROJECT = 'mtusi-lab4'
API_FILTER = ['--filter', f'label=com.docker.compose.project={PROJECT}',
'--filter', 'label=com.docker.compose.service=api']
def compose(*args: str, capture: bool = False) -> str:
result = subprocess.run(['docker', 'compose', '--env-file', str(ROOT / '.env'), *args],
cwd=ROOT, check=True, text=True,
stdout=subprocess.PIPE if capture else subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
return (result.stdout or '').strip()
def docker(*args: str) -> str:
return subprocess.run(['docker', *args], check=True, text=True, capture_output=True).stdout.strip()
def sql(query: str) -> str:
return compose('exec', '-T', 'postgres', 'psql', '-U', 'app', '-d', 'messenger', '-tAc', query, capture=True)
def replica_urls() -> list[str]:
"""Все IP сервиса api из DNS Docker -> прямые адреса реплик (порты наружу не опубликованы)."""
ips = sorted({info[4][0] for info in socket.getaddrinfo('api', 8080, socket.AF_INET, socket.SOCK_STREAM)})
check(len(ips) >= 2, f'expected >= 2 api replicas in DNS, got {len(ips)}')
return [f'http://{ip}:8080' for ip in ips]
def wait_ready(c: Client, seconds: float = 60) -> None:
deadline = time.monotonic() + seconds
while True:
try:
c.call('GET', '/health/ready', schema='Health')
return
except Failure:
check(time.monotonic() < deadline, 'API did not become ready')
time.sleep(0.5)
def raw_post(base: str, path: str, actor: dict, raw: bytes, key: str | None):
"""POST с заданными байтами тела (для проверки семантического равенства JSON)."""
headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + actor['token']}
if key is not None:
headers['Idempotency-Key'] = key
return Client(base).call('POST', path, [201, 400, 409], raw=raw, headers=headers, schema='Message')
def concurrent(calls: list) -> list:
"""Запускает функции одновременно (barrier) и возвращает результаты в исходном порядке."""
results = [None] * len(calls)
barrier = threading.Barrier(len(calls))
def run(i):
barrier.wait()
try:
results[i] = calls[i]()
except Exception as exc: # результат проверяет вызывающий тест
results[i] = exc
threads = [threading.Thread(target=run, args=(i,)) for i in range(len(calls))]
for t in threads:
t.start()
for t in threads:
t.join()
return results
def count_messages(chat: dict) -> int:
return int(sql(f"SELECT count(*) FROM messages WHERE chat_id = '{chat['id']}'"))
# ---------------------------------------------------------------- тесты
def test_session_across_replicas(c: Client):
alice = c.user('xrepl') # вход через LB (обслужила какая-то одна реплика)
seen = {c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id']
for _ in range(20)}
check(len(seen) >= 2, f'one session must be served by >= 2 replicas, saw {seen}')
urls = replica_urls()
for url in urls: # каждая реплика напрямую принимает тот же токен
me = Client(url).call('GET', '/api/v1/users/me', actor=alice, schema='User')['json']
check(me['id'] == alice['id'], 'replica resolved another user')
Client(urls[0]).call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
for url in urls: # logout на одной реплике виден всем (общий store)
Client(url).call('GET', '/api/v1/users/me', 401, actor=alice)
def test_same_key_concurrent_across_replicas(c: Client):
alice, _bob, _eve, chat = c.bootstrap()
urls, key = replica_urls(), uuid.uuid4().hex
calls = [lambda u=urls[i % len(urls)]: Client(u, timeout=15).message(alice, chat, 'один раз', key=key)
for i in range(24)]
results = concurrent(calls)
failures = [r for r in results if isinstance(r, Exception)]
check(not failures, f'concurrent retry failed: {failures[:1]}')
bodies = {json.dumps(r['json'], sort_keys=True) for r in results}
instances = {r['headers']['X-Instance-Id'] for r in results}
check(len(bodies) == 1, f'{len(bodies)} different messages returned for one key')
check(len(instances) >= 2, 'retries did not hit different replicas')
check(count_messages(chat) == 1, f'{count_messages(chat)} messages stored for one key')
via_lb = c.message(alice, chat, 'один раз', key=key)['json'] # и позже через LB — тот же ответ
check(json.dumps(via_lb, sort_keys=True) in bodies, 'later replay differs')
def test_same_key_concurrent_different_bodies(c: Client):
alice, _bob, _eve, chat = c.bootstrap()
urls, key = replica_urls(), uuid.uuid4().hex
path = f"/api/v1/chats/{chat['id']}/messages"
def send(url, text):
return Client(url, timeout=15).call('POST', path, [201, 409], actor=alice, body={'text': text},
headers={'Idempotency-Key': key}, schema='Message')
calls = [lambda u=urls[i % len(urls)], t=('A' if i % 2 else 'B'): send(u, t) for i in range(20)]
results = concurrent(calls)
check(not any(isinstance(r, Exception) for r in results), 'unexpected status in conflicting retries')
winners = {r['json']['text'] for r in results if r['status'] == 201}
check(len(winners) == 1, f'both bodies accepted for one key: {winners}')
loser_statuses = {r['status'] for r in results if r['status'] != 201}
check(loser_statuses <= {409}, 'different body must be 409')
check(sum(r['status'] == 409 for r in results) == 10, 'every other-body request must get 409')
check(count_messages(chat) == 1, 'conflicting retries stored more than one message')
def test_key_scope_and_format(c: Client):
alice, bob, _eve, chat = c.bootstrap()
other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой', 'member_ids': [alice['id']]},
schema='Chat')['json']
path = f"/api/v1/chats/{chat['id']}/messages"
key = 'scope.' + uuid.uuid4().hex + ':1-x_y' # все допустимые символы
first = c.message(alice, chat, 'область', key=key)['json']
check(c.message(bob, chat, 'область', key=key)['json']['id'] != first['id'], 'key shared between users')
check(c.message(alice, other, 'область', key=key)['json']['id'] != first['id'], 'key shared between chats')
# Семантически тот же JSON другими байтами (пробелы, \u-экранирование) — тот же ответ.
same = raw_post(BASE_URL, path, alice, b'{ "text" : "\\u043e\\u0431\\u043b\\u0430\\u0441\\u0442\\u044c" }', key)
check(same['status'] == 201 and same['json'] == first, 'semantically equal JSON was not a replay')
conflict = raw_post(BASE_URL, path, alice, json.dumps({'text': 'иначе'}).encode(), key)
check(conflict['status'] == 409 and conflict['json']['error']['code'] == 'conflict', 'expected 409 conflict')
check(c.message(alice, chat, 'область', key=key)['json'] == first, '409 must not replace stored result')
for bad in (None, '', 'has space', 'café', 'x' * 129, 'a/b'):
r = raw_post(BASE_URL, path, alice, b'{"text":"bad key"}', bad)
check(r['status'] == 400, f'invalid key {bad!r} accepted')
check(len(c.message(alice, chat, 'max', key='k' * 128)['json']['id']) == 36, '128-char key rejected')
check(count_messages(chat) == 3, 'unexpected number of messages in scope test') # alice x2, bob x1
def test_replay_rechecks_session(c: Client):
alice, _bob, eve, chat = c.bootstrap()
key = uuid.uuid4().hex
c.message(alice, chat, 'до выхода', key=key)
path = f"/api/v1/chats/{chat['id']}/messages"
# Посторонний с тем же ключом не получает чужой результат.
c.call('POST', path, 404, actor=eve, body={'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': 'до выхода'}, headers={'Idempotency-Key': key})
def test_transient_failure_not_recorded(c: Client):
alice, _bob, _eve, chat = c.bootstrap()
key = uuid.uuid4().hex
try:
compose('stop', 'postgres')
r = c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 503, actor=alice,
body={'text': 'после сбоя'}, headers={'Idempotency-Key': key})
check(r['json']['error']['code'] == 'unavailable', 'expected unavailable')
check(bool(r['headers'].get('X-Instance-Id')), '503 must come from API (fallback backend), not LB')
c.call('GET', '/health/live', schema='Health')
finally:
compose('start', 'postgres')
wait_ready(c)
first = c.message(alice, chat, 'после сбоя', key=key)['json'] # повтор с тем же ключом создаёт запись
check(c.message(alice, chat, 'после сбоя', key=key)['json'] == first, 'replay after recovery differs')
check(count_messages(chat) == 1, 'transient failure produced extra message')
def test_sigterm_drain(c: Client):
"""SIGTERM: реплика сначала отвечает ready=503, но ещё обслуживает запросы, затем завершается с кодом 0."""
alice = c.user('drain')
names = docker('ps', *API_FILTER, '--format', '{{.Names}}').split()
name = sorted(names)[0]
ip = docker('inspect', '-f', '{{(index .NetworkSettings.Networks "%s_edge").IPAddress}}' % PROJECT, name)
direct = Client(f'http://{ip}:8080', timeout=2)
docker('kill', '-s', 'TERM', name)
signalled = time.monotonic()
try:
time.sleep(0.3)
direct.call('GET', '/health/ready', 503)
direct.call('GET', '/health/live', schema='Health')
r = direct.call('GET', '/api/v1/users/me', actor=alice, schema='User')
check(r['headers'].get('Connection', '').lower() == 'close', 'draining replica must close keep-alive')
time.sleep(max(0.0, signalled + 2.0 - time.monotonic())) # окно обнаружения LB: fall 2 x 0.5-1 с
served = {c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id']
for _ in range(10)} # LB уже не отправляет на неё запросы
deadline = time.monotonic() + 20
while docker('inspect', '-f', '{{.State.Status}}', name) != 'exited':
check(time.monotonic() < deadline, 'replica did not exit after drain')
time.sleep(0.2)
code = docker('inspect', '-f', '{{.State.ExitCode}}', name)
check(code in ('0', '143'), f'unclean exit code {code}')
hostname = docker('inspect', '-f', '{{.Config.Hostname}}', name)
check(not any(i.startswith(hostname) for i in served), 'LB still routes to the draining replica')
finally:
subprocess.run(['sh', str(ROOT / 'scripts/restore.sh')], check=True, capture_output=True)
deadline = time.monotonic() + 30
while len({c.call('GET', '/health/live', schema='Health')['headers']['X-Instance-Id'] for _ in range(10)}) < 2:
check(time.monotonic() < deadline, 'restored replica did not return to LB')
time.sleep(0.5)
def test_infrastructure_rules(_c: Client):
containers = docker('ps', '--filter', f'label=com.docker.compose.project={PROJECT}', '--format', '{{.Names}}').split()
for name in containers:
cfg = json.loads(docker('inspect', name))[0]
service = cfg['Config']['Labels']['com.docker.compose.service']
if service == 'tester':
continue
host = cfg['HostConfig']
check(host['NanoCpus'] > 0 and host['Memory'] > 0, f'{name}: no CPU/RAM limit')
check(name.startswith(f'{PROJECT}-{service}-'), f'{name}: fixed container_name prevents scaling')
bindings = host.get('PortBindings') or {}
if service == 'lb':
check(all(b['HostIp'] == '127.0.0.1' for v in bindings.values() for b in v), 'LB published beyond loopback')
else:
check(not bindings, f'{name} publishes ports in bypass of LB')
if service == 'api':
check(cfg['HostConfig']['ReadonlyRootfs'], 'api root fs must be read-only (no local state)')
mounts = {m['Destination'] for m in cfg['Mounts']}
check(mounts <= {'/run/secrets/database_url', '/run/secrets/cache_url', '/run/secrets/s3_access_key_id',
'/run/secrets/s3_secret_access_key'}, f'api has unexpected mounts {mounts}') # lab4: + S3
check(sql('SELECT count(*) FROM schema_migrations') == '4', 'unexpected migration count') # lab4: + 0004_attachments
with urllib.request.urlopen(os.environ.get('LB_STATS_URL', 'http://lb:8404/stats') + ';csv', timeout=2) as r:
text = r.read().decode()
check(',UP,' in text or ',UP ' in text, 'LB stats show no UP backend')
TESTS = [test_session_across_replicas, test_same_key_concurrent_across_replicas,
test_same_key_concurrent_different_bodies, test_key_scope_and_format, test_replay_rechecks_session,
test_transient_failure_not_recorded, test_sigterm_drain, test_infrastructure_rules]
def main() -> int:
c = Client(BASE_URL)
wait_ready(c)
failed = 0
for test in TESTS:
started = time.monotonic()
try:
test(c)
print(f'PASS {test.__name__} ({time.monotonic() - started:.1f}s)', flush=True)
except (Failure, subprocess.CalledProcessError, OSError) as exc:
failed += 1
print(f'FAIL {test.__name__}: {exc}', flush=True)
print(f'{len(TESTS) - failed}/{len(TESTS)} passed')
return 1 if failed else 0
if __name__ == '__main__':
sys.exit(main())
+278
View File
@@ -0,0 +1,278 @@
#!/usr/bin/env python3
"""Собственные проверки lab4 (уровень 3). Запуск: sh scripts/test-lab4.sh (внутри сервиса tester).
Покрывают критерии README «3»: PNG/JPEG upload -> 201 ready, побайтный download с SHA-256, доступ только
участникам, сообщение с attachment_ids, лимиты (10 MiB, 40 Мпикс до декодирования), MIME по содержимому,
опасные filename, failover загрузившей реплики, недоступность S3, приватность bucket вне API и отсутствие
локальной копии файла на API. Требуют доступ к docker: останавливают реплику и S3, затем возвращают.
"""
import hashlib
import os
import struct
import subprocess
import sys
import time
import uuid
import zlib
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, Failure, check # noqa: E402
BASE_URL = os.environ.get('BASE_URL', 'http://lb:8080')
PROJECT = 'mtusi-lab4'
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
JPEG = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes()
def docker(*args: str) -> str:
return subprocess.run(['docker', *args], check=True, text=True, capture_output=True).stdout.strip()
def service_containers(service: str, running_only: bool = True) -> list[str]:
args = ['ps', '-q', '--filter', f'label=com.docker.compose.project={PROJECT}',
'--filter', f'label=com.docker.compose.service={service}']
if not running_only:
args.insert(1, '-a')
return docker(*args).split()
def wait_ready(c: Client, seconds: float = 60) -> None:
deadline = time.monotonic() + seconds
while True:
try:
c.call('GET', '/health/ready', schema='Health')
return
except Failure:
check(time.monotonic() < deadline, 'API did not become ready')
time.sleep(0.5)
def upload(c: Client, actor: dict, chat: dict, data: bytes, ctype: str, filename: str = 'photo.png',
expected=201) -> dict:
path = f"/api/v1/chats/{chat['id']}/attachments?filename={quote(filename, safe='')}"
return c.call('POST', path, expected, actor=actor, raw=data, headers={'Content-Type': ctype},
schema='Attachment' if expected == 201 else None)
def download(c: Client, actor: dict, att_id: str, expected=200) -> dict:
return c.call('GET', f'/api/v1/attachments/{att_id}/content', expected, actor=actor)
def png_chunk(kind: bytes, data: bytes) -> bytes:
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data) & 0xffffffff)
def png_header_only(width: int, height: int) -> bytes:
"""Валидная сигнатура и IHDR (с верным CRC) огромного изображения, без пиксельных данных."""
ihdr = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)
idat = zlib.compress(b'\x00' * 64) # заведомо меньше, чем нужно: декодировать сервер не должен
return b'\x89PNG\r\n\x1a\n' + png_chunk(b'IHDR', ihdr) + png_chunk(b'IDAT', idat) + png_chunk(b'IEND', b'')
# ---------- тесты ----------
def test_png_and_jpeg_roundtrip(c: Client):
alice, bob, eve, chat = c.bootstrap()
for data, ctype, name in ((PNG, 'image/png', 'Фото 1.png'), (JPEG, 'image/jpeg', 'кадр.jpg')):
att = upload(c, alice, chat, data, ctype, name)['json']
check(att['status'] == 'ready' and att['variants'] == [] and att['error_code'] is None, 'not ready')
check(att['filename'] == name and att['content_type'] == ctype, 'metadata mismatch')
check(att['sha256'] == hashlib.sha256(data).hexdigest() and att['size_bytes'] == len(data), 'checksum')
meta = c.call('GET', f"/api/v1/attachments/{att['id']}", actor=bob, schema='Attachment')['json']
check(meta == att, 'metadata via GET differs from upload response')
got = download(c, bob, att['id'])
check(got['bytes'] == data, 'downloaded bytes differ')
check(got['headers'].get_content_type() == ctype, 'wrong Content-Type on download')
check(hashlib.sha256(got['bytes']).hexdigest() == att['sha256'], 'sha256 mismatch')
for suffix in ('', '/content'):
c.call('GET', f"/api/v1/attachments/{att['id']}{suffix}", 404, actor=eve)
c.call('GET', f"/api/v1/attachments/{att['id']}/content", 401)
def test_message_with_attachments(c: Client):
alice, bob, _eve, chat = c.bootstrap()
a1 = upload(c, alice, chat, PNG, 'image/png')['json']
a2 = upload(c, bob, chat, JPEG, 'image/jpeg', 'b.jpg')['json']
key = uuid.uuid4().hex
msg = c.message(bob, chat, '', key=key, attachments=[a2['id'], a1['id']])['json'] # любой участник
check(msg['attachment_ids'] == [a2['id'], a1['id']] and msg['text'] == '', 'attachment order lost')
replay = c.message(bob, chat, '', key=key, attachments=[a2['id'], a1['id']])['json']
check(replay == msg, 'idempotent replay with attachments differs')
plain = c.message(alice, chat, 'только текст')['json']
check(plain['attachment_ids'] == [], 'text message must have attachment_ids=[]')
history = c.call('GET', f"/api/v1/chats/{chat['id']}/messages?limit=100", actor=alice,
schema='MessagePage')['json']['items']
check([m['attachment_ids'] for m in history] == [[a2['id'], a1['id']], []], 'history lost attachments')
h = {'Idempotency-Key': uuid.uuid4().hex}
c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 400, actor=alice, body={'text': ' '}, headers=h)
c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 400, actor=alice,
body={'text': '', 'attachment_ids': [a1['id'], a1['id']]}, headers=h)
def test_foreign_attachment_rejected(c: Client):
alice, bob, eve, chat = c.bootstrap()
other = c.call('POST', '/api/v1/chats', 201, actor=eve, body={'title': 'чужой', 'member_ids': [eve['id']]},
schema='Chat')['json']
foreign = upload(c, eve, other, PNG, 'image/png')['json']
h = {'Idempotency-Key': uuid.uuid4().hex}
# Вложение другого чата и несуществующее — 404, сообщение не создаётся.
for ids in ([foreign['id']], [str(uuid.uuid4())]):
c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 404, actor=alice,
body={'text': 'x', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
items = c.call('GET', f"/api/v1/chats/{chat['id']}/messages", actor=alice, schema='MessagePage')['json']['items']
check(items == [], 'message with foreign attachment was created')
# Посторонний не может загрузить файл в чужой чат.
upload(c, eve, chat, PNG, 'image/png', expected=404)
c.call('POST', f"/api/v1/chats/{chat['id']}/messages", 404, actor=eve,
body={'text': 'x'}, headers=h)
def test_limits_and_mime(c: Client):
alice, _bob, _eve, chat = c.bootstrap()
# 10 MiB + 1 байт: 413 (тело дальше лимита сервер не читает).
upload(c, alice, chat, PNG[:8] + b'\0' * (10 * 1024 * 1024 - 7), 'image/png', expected=413)
# Ровно 10 MiB проходит проверку размера (а затем отклоняется как повреждённый PNG — 415, не 413).
upload(c, alice, chat, PNG[:8] + b'\0' * (10 * 1024 * 1024 - 8), 'image/png', expected=415)
# 10000 x 5000 = 50 Мпикс по заголовку -> 413 до декодирования (файл всего ~100 байт).
upload(c, alice, chat, png_header_only(10000, 5000), 'image/png', expected=413)
# 6000 x 6000 = 36 Мпикс укладывается в лимит, но пикселей нет -> повреждённый -> 415.
upload(c, alice, chat, png_header_only(6000, 6000), 'image/png', expected=415)
# MIME по содержимому: PNG с Content-Type image/jpeg и наоборот -> 415.
upload(c, alice, chat, PNG, 'image/jpeg', expected=415)
upload(c, alice, chat, JPEG, 'image/png', expected=415)
# Не изображение, обрезанные файлы, пустое тело, чужие Content-Type.
upload(c, alice, chat, b'GIF89a' + b'\0' * 100, 'image/png', expected=415)
upload(c, alice, chat, PNG[:len(PNG) // 2], 'image/png', expected=415)
upload(c, alice, chat, JPEG[:len(JPEG) // 2], 'image/jpeg', expected=415)
upload(c, alice, chat, b'', 'image/png', expected=415)
upload(c, alice, chat, PNG, 'text/plain', expected=415)
upload(c, alice, chat, PNG, 'multipart/form-data; boundary=x', expected=415)
def test_dangerous_filenames(c: Client):
alice, _bob, _eve, chat = c.bootstrap()
for name in ('../etc/passwd', 'a/b.png', 'a\\b.png', 'nul\x00.png', 'tab\t.png', 'new\nline.png',
'\x7f.png', '', ' ', '..', 'x' * 256):
upload(c, alice, chat, PNG, 'image/png', name, expected=400)
c.call('POST', f"/api/v1/chats/{chat['id']}/attachments", 400, actor=alice, raw=PNG,
headers={'Content-Type': 'image/png'}) # без filename
ok = upload(c, alice, chat, PNG, 'image/png', 'отчёт (финал) ✓.png')['json']
check(ok['filename'] == 'отчёт (финал) ✓.png', 'unicode filename changed')
upload(c, alice, chat, PNG, 'image/png', 'x' * 255)
def test_failover_of_uploading_replica(c: Client):
"""Upload -> остановить реплику, которая его обслужила -> download через другую = тот же файл."""
alice, bob, _eve, chat = c.bootstrap()
response = upload(c, alice, chat, PNG, 'image/png')
att = response['json']
served_by = response['headers']['X-Instance-Id']
cid = served_by.rsplit('-', 1)[0]
check(cid in [x[:12] for x in service_containers('api')], 'uploader replica not found among containers')
docker('stop', '-t', '20', cid)
try:
time.sleep(2)
got = download(c, bob, att['id'])
check(got['headers']['X-Instance-Id'] != served_by, 'download served by stopped replica')
check(got['bytes'] == PNG and hashlib.sha256(got['bytes']).hexdigest() == att['sha256'],
'file differs after uploader replica stopped')
print(f' uploaded via {served_by}, downloaded via {got["headers"]["X-Instance-Id"]}')
finally:
docker('start', cid)
wait_ready(c)
def test_s3_unavailable(c: Client):
"""S3 остановлен: upload/download -> 503 без 500, текстовые сообщения работают, после старта — всё снова."""
alice, bob, _eve, chat = c.bootstrap()
att = upload(c, alice, chat, PNG, 'image/png')['json']
s3 = service_containers('s3')
check(len(s3) == 1, 'expected one s3 container')
docker('stop', s3[0])
try:
started = time.monotonic()
upload(c, alice, chat, PNG, 'image/png', expected=503)
download(c, bob, att['id'], expected=503)
check(time.monotonic() - started < 15, 'S3 failure is not bounded by timeouts')
c.message(alice, chat, 'S3 недоступен, а текст отправляется')
c.call('GET', f"/api/v1/attachments/{att['id']}", actor=bob, schema='Attachment') # метаданные в БД
c.call('GET', '/health/ready', schema='Health')
finally:
docker('start', s3[0])
deadline = time.monotonic() + 60
while True:
try:
check(download(c, bob, att['id'])['bytes'] == PNG, 'file changed after S3 restart')
break
except Failure:
check(time.monotonic() < deadline, 'S3 did not come back')
time.sleep(1)
upload(c, alice, chat, JPEG, 'image/jpeg', 'after.jpg')
def test_bucket_private_outside_api(c: Client):
"""Прямой анонимный GET объекта в S3 (в обход API) отклоняется; ключ в API не раскрывается."""
alice, _bob, _eve, chat = c.bootstrap()
att = upload(c, alice, chat, PNG, 'image/png')['json']
check('object_key' not in att and 'attachments/' not in str(att), 'object key leaked to API')
api = service_containers('api')[0]
code = docker('exec', api, 'python', '-c',
'import urllib.request,urllib.error,sys\n'
'try:\n'
f' urllib.request.urlopen("http://s3:9000/messenger-attachments/attachments/{att["id"]}", timeout=5)\n'
' print(200)\n'
'except urllib.error.HTTPError as e:\n'
' print(e.code)\n')
check(code in ('401', '403'), f'anonymous S3 GET returned {code}')
# Листинг bucket анонимно тоже запрещён.
code = docker('exec', api, 'python', '-c',
'import urllib.request,urllib.error\n'
'try:\n'
' urllib.request.urlopen("http://s3:9000/messenger-attachments", timeout=5); print(200)\n'
'except urllib.error.HTTPError as e:\n'
' print(e.code)\n')
check(code in ('401', '403'), f'anonymous S3 list returned {code}')
print(f' anonymous GET object/list -> {code}')
def test_no_local_copy_on_api(c: Client):
"""У API read-only корневая ФС и пустой tmpfs: оригинал не хранится локально."""
alice, _bob, _eve, chat = c.bootstrap()
upload(c, alice, chat, PNG, 'image/png')
for cid in service_containers('api'):
check(docker('inspect', '-f', '{{.HostConfig.ReadonlyRootfs}}', cid) == 'true', 'api rootfs is writable')
# Допустимы только read-only секреты compose (/run/secrets/*); volume и записываемых bind нет.
mounts = docker('inspect', '-f', '{{range .Mounts}}{{.Type}}:{{.Destination}}:{{.RW}} {{end}}', cid).split()
writable = [m for m in mounts if m.startswith('volume:') or
(m.startswith('bind:') and not (m.startswith('bind:/run/secrets/') and m.endswith(':false')))]
check(not writable, f'api has persistent/writable mounts: {writable}')
files = docker('exec', cid, 'find', '/tmp', '-type', 'f')
check(files == '', f'unexpected files in api /tmp: {files}')
TESTS = [test_png_and_jpeg_roundtrip, test_message_with_attachments, test_foreign_attachment_rejected,
test_limits_and_mime, test_dangerous_filenames, test_bucket_private_outside_api,
test_no_local_copy_on_api, test_failover_of_uploading_replica, test_s3_unavailable]
def main() -> int:
c = Client(BASE_URL, timeout=30)
wait_ready(c)
failed = 0
for test in TESTS:
started = time.monotonic()
try:
test(c)
print(f'PASS {test.__name__} ({time.monotonic() - started:.1f}s)', flush=True)
except (Failure, subprocess.CalledProcessError, OSError) as exc:
failed += 1
print(f'FAIL {test.__name__}: {exc}', flush=True)
print(f'{len(TESTS) - failed}/{len(TESTS)} passed')
return 1 if failed else 0
if __name__ == '__main__':
sys.exit(main())