"""Приватность bucket вне API и недоступность S3 (stdlib + docker CLI). 1. Bucket приватен вне API: реальный object_key берётся из PostgreSQL (docker exec db psql), затем анонимные GET/HEAD/LIST/PUT напрямую в S3 из сети backend -> 403; S3-порт не опубликован на хосте; LB не проксирует пути S3. 2. Отказ S3 (docker stop s3): /health/ready 200, сообщения 201, metadata 200, upload/download -> быстрый 503 в общем формате (не 500, не зависание). После docker start s3: upload 201, старый файл скачивается побайтно. Нужен docker.sock: запускайте только в tester на учебном стенде: docker compose --profile tools run --rm tester python3 student-tests/s3_failures.py """ from __future__ import annotations import base64 import hashlib import json import os import socket import subprocess import sys import time import urllib.error import urllib.parse import urllib.request import uuid from pathlib import Path ROOT = Path(__file__).resolve().parent.parent BASE = os.environ.get('BASE_URL', 'http://lb:8080').rstrip('/') S3 = os.environ.get('S3_ENDPOINT', 'http://s3:9000').rstrip('/') PROJECT = os.environ.get('COMPOSE_PROJECT', 'messenger-lab4') BUCKET = 'messenger-attachments' SAMPLE = (ROOT / 'tests/fixtures/sample.png').read_bytes() failed = 0 def check(label, ok, detail=''): global failed failed += not ok print(f"{'OK ' if ok else 'FAIL'} {label} {detail}".rstrip(), flush=True) def docker(*args, check_rc=True) -> str: return subprocess.run(['docker', *args], check=check_rc, capture_output=True, text=True).stdout.strip() def container(service: str) -> str: ids = docker('ps', '-aq', '--filter', f'label=com.docker.compose.project={PROJECT}', '--filter', f'label=com.docker.compose.service={service}').split() assert ids, f'no container for {service}' return ids[0] def http(method, url, data=None, headers=None, timeout=30): req = urllib.request.Request(url, data=data, headers=headers or {}, method=method) started = time.monotonic() try: with urllib.request.urlopen(req, timeout=timeout) as r: return r.status, r.read(), time.monotonic() - started except urllib.error.HTTPError as e: return e.code, e.read(), time.monotonic() - started def api(method, path, body=None, auth=None, raw=None, ctype=None, extra=None): h = dict(extra or {}) if auth: h['Authorization'] = auth if body is not None: raw = json.dumps(body).encode() ctype = 'application/json' if ctype: h['Content-Type'] = ctype status, data, elapsed = http(method, BASE + '/api/v1' + path, raw, h) try: parsed = json.loads(data) if data else None except ValueError: parsed = None return status, parsed, data, elapsed def err(parsed): return parsed.get('error', {}).get('code') if isinstance(parsed, dict) else None def wait_healthy(cid, seconds=90): deadline = time.monotonic() + seconds while time.monotonic() < deadline: if docker('inspect', '-f', '{{.State.Health.Status}}', cid) == 'healthy': return True time.sleep(1) return False def main() -> int: name = 's3f' + uuid.uuid4().hex[:12] password = 's3-failure-password' s, user, _, _ = api('POST', '/users', {'username': name, 'display_name': 'S3', 'password': password}) basic = 'Basic ' + base64.b64encode(f'{name}:{password}'.encode()).decode() s, session, _, _ = api('POST', '/auth/sessions', auth=basic) auth = 'Bearer ' + session['token'] s, chat, _, _ = api('POST', '/chats', {'title': 's3', 'member_ids': [user['id']]}, auth=auth) s, att, _, _ = api('POST', f"/chats/{chat['id']}/attachments?filename=a.png", auth=auth, raw=SAMPLE, ctype='image/png') assert s == 201, s # --- 1. приватный bucket вне API --------------------------------------- db = container('db') key = docker('exec', db, 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc', f"SELECT object_key FROM attachments WHERE id = '{att['id']}'") check('object_key есть в PostgreSQL и не совпадает с filename/ID', bool(key) and 'a.png' not in key and att['id'] not in key) check('API не раскрывает object_key', key not in json.dumps(att)) for method, path, data in [ ('GET', f'/{BUCKET}/{key}', None), ('HEAD', f'/{BUCKET}/{key}', None), ('GET', f'/{BUCKET}?list-type=2', None), ('GET', f'/{BUCKET}/', None), ('PUT', f'/{BUCKET}/{key}', b'overwrite'), ('DELETE', f'/{BUCKET}/{key}', None), ]: s, _, _ = http(method, S3 + path, data) check(f'анонимный {method} {path.replace(key, "")} напрямую в S3 -> 403', s == 403, f'({s})') s, _, data, _ = api('GET', f"/attachments/{att['id']}/content", auth=auth) check('объект не изменён анонимными PUT/DELETE', hashlib.sha256(data).digest() == hashlib.sha256(SAMPLE).digest()) s3 = container('s3') ports = docker('port', s3, check_rc=False) check('S3 не опубликован на хосте (docker port пуст)', ports == '', repr(ports)) s, _, _ = http('GET', BASE + f'/{BUCKET}/{key}') check('LB не проксирует путь S3', s == 404, f'({s})') host = urllib.parse.urlsplit(S3).hostname for port, role in [(9333, 'master UI/API'), (8888, 'filer UI/API'), (8080, 'volume'), (19333, 'master gRPC'), (18888, 'filer gRPC'), (23646, 'admin')]: try: socket.create_connection((host, port), timeout=2).close() reachable = True except OSError: reachable = False check(f'SeaweedFS {role} :{port} недоступен из сети стенда', not reachable) # --- 2. отказ S3 ------------------------------------------------------- docker('stop', '--time', '10', s3) print('-- s3 остановлен', flush=True) try: s, _, _ = http('GET', BASE + '/health/ready') check('/health/ready при отказе S3 -> 200 (S3 не критичен для чата)', s == 200, f'({s})') s, m, _, _ = api('POST', f"/chats/{chat['id']}/messages", {'text': 'без S3', 'attachment_ids': [att['id']]}, auth=auth, extra={'Idempotency-Key': uuid.uuid4().hex}) check('сообщение со ссылкой на готовое вложение -> 201', s == 201, f'({s})') s, _, _, _ = api('GET', f"/attachments/{att['id']}", auth=auth) check('metadata из PostgreSQL -> 200', s == 200, f'({s})') s, p, _, t = api('POST', f"/chats/{chat['id']}/attachments?filename=b.png", auth=auth, raw=SAMPLE, ctype='image/png') check('upload -> 503 unavailable', s == 503 and err(p) == 'unavailable', f'({s} {err(p)}, {t:.2f} s)') check('upload отказал быстрее timeout LB (< 8 s)', t < 8, f'({t:.2f} s)') s, p, _, t = api('GET', f"/attachments/{att['id']}/content", auth=auth) check('download -> 503 unavailable', s == 503 and err(p) == 'unavailable', f'({s} {err(p)}, {t:.2f} s)') check('download отказал быстрее timeout LB (< 8 s)', t < 8, f'({t:.2f} s)') s, p, _, _ = api('POST', f"/chats/{chat['id']}/attachments?filename=c.png", auth=auth, raw=b'junk', ctype='image/png') check('пользовательская ошибка при отказе S3 остаётся 415', s == 415, f'({s})') intents = docker('exec', db, 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc', 'SELECT count(*) FROM upload_intents') print(f' upload_intents после неудачных upload: {intents}', flush=True) finally: docker('start', s3) print('-- s3 запущен', flush=True) check('s3 снова healthy', wait_healthy(s3)) deadline = time.monotonic() + 30 while True: s, new, _, _ = api('POST', f"/chats/{chat['id']}/attachments?filename=d.png", auth=auth, raw=SAMPLE, ctype='image/png') if s == 201 or time.monotonic() > deadline: break time.sleep(1) check('после восстановления S3 upload -> 201', s == 201, f'({s})') s, _, data, _ = api('GET', f"/attachments/{att['id']}/content", auth=auth) check('старый файл скачивается побайтно', s == 200 and data == SAMPLE, f'({s})') print('PASS: bucket приватен вне API, отказ S3 даёт 503 только для вложений' if not failed else f'FAIL: {failed} проверок не прошло') return 1 if failed else 0 if __name__ == '__main__': sys.exit(main())