Реализовать лабораторную 4: вложения в S3 и согласованность с БД

- приватный bucket SeaweedFS за S3-шлюзом, отдельные identities
  admin/api/reconciler, анонимный доступ запрещён
- потоковый upload с проверкой PNG/JPEG (CRC, распаковка со сверкой
  объёма, лимит пикселей до распаковки) без буферизации тела
- скачивание через авторизованный API; компенсация неудачной загрузки:
  сначала pending-строка, затем объект
- reconciler БД ↔ S3 с grace period: stale_pending, orphan_object,
  missing_object, size/checksum mismatch, обратимый карантин lost
- сценарии отказов S3, замер памяти загрузок, трек 2, evidence и REPORT.md
This commit is contained in:
celis
2026-10-31 00:31:54 +03:00
parent ec540a1a72
commit 04458025fb
58 changed files with 4549 additions and 17 deletions
+192
View File
@@ -0,0 +1,192 @@
#!/usr/bin/env python3
"""Негативные и граничные сценарии вложений (уровень 4) через LB: ни один из них не должен дать 500.
Изображения генерируются кодом (PNG — zlib/struct), JPEG — синтетический fixtures/sample.jpg (sips из sample.png).
Запуск: python3 student-tests/attachments.py --base-url http://localhost:8080"""
import hashlib
import http.client
import os
from pathlib import Path
import struct
import sys
import time
import urllib.parse
import uuid
import zlib
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, ROOT, arguments, check, run # noqa: E402
MiB = 1024 * 1024
SAMPLE_PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
SAMPLE_JPG = (Path(__file__).parent / 'fixtures/sample.jpg').read_bytes()
def chunk(kind, data):
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
def png(width, height, raw, depth=8, color=2, level=1):
"""PNG из готовых распакованных строк raw (байт фильтра + пиксели)."""
ihdr = struct.pack('>IIBBBBB', width, height, depth, color, 0, 0, 0)
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', ihdr) + chunk(b'IDAT', zlib.compress(raw, level)) + chunk(b'IEND', b'')
def noise_png(side):
"""RGB-шум не сжимается: размер файла ≈ side² × 3 байт."""
row = 1 + side * 3
return png(side, side, b''.join(b'\0' + os.urandom(row - 1) for _ in range(side)))
def gray1(width, height):
"""1-битный серый PNG из нулей: 40 Мпикс занимают несколько килобайт файла."""
return png(width, height, bytes(height * (1 + (width + 7) // 8)), depth=1, color=0, level=9)
def jpeg_with_size(data, width, height):
"""Подменить размеры в SOF0 существующего JPEG."""
i = data.index(b'\xff\xc0')
return data[:i + 5] + struct.pack('>HH', height, width) + data[i + 9:]
def main():
args = arguments('Attachment negative suite')
c = Client(args.base_url, args.ca_file, timeout=30)
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']
results = []
def upload(data, expected, ctype='image/png', name='file.png', actor=alice, target=chat, label=None):
path = '/api/v1/chats/' + target['id'] + '/attachments?filename=' + urllib.parse.quote(name, safe='')
r = c.call('POST', path, expected, actor=actor, raw=data, headers={'Content-Type': ctype}, schema='Attachment' if expected == 201 else None)
results.append((label or name, r['status'], (r['json'] or {}).get('error', {}).get('code', ''), round(r['elapsed'] * 1000)))
if expected == 201:
att = r['json']
check(att['sha256'] == hashlib.sha256(data).hexdigest() and att['size_bytes'] == len(data), label + ': checksum/size')
check(att['content_type'] == ctype and att['filename'] == name and att['status'] == 'ready', label + ': metadata')
return att
return r['json']
def download(att, actor=bob, expect=None):
r = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=actor)
check(r['bytes'] == expect and hashlib.sha256(r['bytes']).hexdigest() == att['sha256'], 'download differs')
check(r['headers'].get_content_type() == att['content_type'], 'download content type')
check(r['headers'].get('X-Content-Type-Options') == 'nosniff', 'missing nosniff')
check(not r['headers'].get('Location'), 'download must not redirect')
# Принимаются реальные PNG/JPEG, граница по размеру и по пикселям.
jpg = upload(SAMPLE_JPG, 201, 'image/jpeg', 'фото 📷 2026.jpg', label='real JPEG + unicode filename')
download(jpg, expect=SAMPLE_JPG)
big = noise_png(1860)
check(9 * MiB < len(big) <= 10 * MiB, 'big fixture size %d' % len(big))
big_att = upload(big, 201, label='PNG %.2f MiB (noise 1860x1860)' % (len(big) / MiB))
download(big_att, expect=big)
upload(gray1(6400, 6250), 201, label='PNG ровно 40 000 000 px')
# Лимиты: до чтения тела (Content-Length) и по заголовку изображения до распаковки.
upload(noise_png(1900), 413, label='PNG 10.33 MiB > 10 MiB')
upload(os.urandom(10 * MiB + 1), 413, label='10 MiB + 1 байт')
upload(gray1(6400, 6251), 413, label='PNG 40 006 400 px')
bomb = gray1(30000, 30000)
upload(bomb, 413, label='pixel-bomb 30000x30000, файл %d КБ' % (len(bomb) // 1024))
upload(jpeg_with_size(SAMPLE_JPG, 10000, 10000), 413, 'image/jpeg', 'bomb.jpg', label='JPEG SOF 10000x10000')
# IHDR обещает 100x100, а IDAT распаковывается в 64 МБ нулей: распаковка останавливается на лишних данных.
upload(png(100, 100, bytes(64 * MiB), level=9), 415, label='zip-bomb в IDAT (64 МБ при 100x100)')
# Повреждённые файлы и подмена типа.
bad_crc = bytearray(SAMPLE_PNG)
bad_crc[1000] ^= 0xFF
upload(bytes(bad_crc), 415, label='PNG: байт IDAT испорчен (CRC)')
upload(png(320, 200, os.urandom(1000)), 415, label='PNG: корректные CRC, мусор в zlib')
upload(png(320, 200, bytes(100)), 415, label='PNG: данных меньше, чем пикселей')
upload(SAMPLE_PNG[:-200], 415, label='PNG обрезан')
upload(SAMPLE_PNG + b'<html>', 415, label='PNG + данные после IEND')
upload(SAMPLE_JPG[:-500], 415, 'image/jpeg', 'cut.jpg', label='JPEG обрезан (нет EOI)')
upload(SAMPLE_PNG, 415, 'image/jpeg', 'spoof.jpg', label='PNG под видом image/jpeg')
upload(SAMPLE_JPG, 415, 'image/png', 'spoof.png', label='JPEG под видом image/png')
upload(b'GIF89a' + os.urandom(100), 415, label='GIF под видом image/png')
upload(b'<svg xmlns="http://www.w3.org/2000/svg"/>', 415, label='SVG под видом image/png')
upload(SAMPLE_PNG, 415, 'image/gif', 'x.gif', label='Content-Type image/gif')
upload(SAMPLE_PNG, 415, 'application/octet-stream', 'x.png', label='Content-Type octet-stream')
upload(b'', 415, label='пустое тело')
# Опасные и некорректные filename: 400 до чтения тела.
for name in ['../etc/passwd', 'a/b.png', 'a\\b.png', 'nul\x00.png', 'tab\t.png', 'line\n.png', 'c1\x85.png', '', ' ', 'x' * 256]:
upload(SAMPLE_PNG, 400, name=name, label='filename %r' % name[:20])
r = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments', 400, actor=alice, raw=SAMPLE_PNG, headers={'Content-Type': 'image/png'})
results.append(('без filename', r['status'], r['json']['error']['code'], round(r['elapsed'] * 1000)))
results.append(('chunked без Content-Length',) + chunked_upload(c, alice, chat))
# Доступ: без сессии, посторонний, чужое вложение.
upload(SAMPLE_PNG, 401, actor={'id': '', 'token': 'bad'}, label='без действительной сессии')
upload(SAMPLE_PNG, 404, actor=eve, label='посторонний грузит в чужой чат')
upload(SAMPLE_PNG, 404, target={'id': str(uuid.uuid4())}, label='несуществующий чат')
upload(SAMPLE_PNG, 400, target={'id': 'not-a-uuid'}, label='chat_id не UUID')
own = upload(SAMPLE_PNG, 201, label='обычный PNG')
foreign = upload(SAMPLE_PNG, 201, target=other, label='PNG в другом чате')
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/' + own['id'] + suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + foreign['id'] + suffix, 404, actor=bob)
c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()) + suffix, 404, actor=bob)
c.call('GET', '/api/v1/attachments/xyz' + suffix, 400, actor=bob)
c.call('GET', '/api/v1/attachments/' + own['id'] + suffix, 401)
content = '/api/v1/attachments/' + own['id'] + '/content'
c.call('GET', content + '?variant=thumbnail', 404, actor=bob)
c.call('GET', content + '?variant=bogus', 400, actor=bob)
check(c.call('GET', content + '?variant=original', actor=bob)['bytes'] == SAMPLE_PNG, 'variant=original')
# Привязка к сообщению: только вложения этого чата, 0–10 уникальных UUID.
send = '/api/v1/chats/' + chat['id'] + '/messages'
def post(body, expected, key=None):
return c.call('POST', send, expected, actor=alice, body=body, headers={'Idempotency-Key': key or uuid.uuid4().hex},
schema='Message' if expected == 201 else None)['json']
post({'text': 'чужое', 'attachment_ids': [foreign['id']]}, 404)
post({'text': 'смесь', 'attachment_ids': [own['id'], foreign['id']]}, 404)
post({'text': 'нет такого', 'attachment_ids': [str(uuid.uuid4())]}, 404)
post({'text': 'дубль', 'attachment_ids': [own['id'], own['id'].upper()]}, 400)
post({'text': 'много', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]}, 400)
post({'text': 'не uuid', 'attachment_ids': ['x']}, 400)
post({'text': 'не массив', 'attachment_ids': own['id']}, 400)
post({'text': ' '}, 400)
post({'text': '', 'attachment_ids': []}, 400)
c.call('POST', '/api/v1/chats/' + other['id'] + '/messages', 404, actor=bob, body={'text': 'x', 'attachment_ids': [foreign['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex})
key = uuid.uuid4().hex
m = post({'text': '', 'attachment_ids': [own['id'], jpg['id']]}, 201, key)
check(m['attachment_ids'] == [own['id'], jpg['id']] and m['text'] == '', 'attachment order/text')
check(post({'attachment_ids': [own['id'], jpg['id']], 'text': ''}, 201, key) == m, 'replay with attachments differs')
post({'text': '', 'attachment_ids': [jpg['id'], own['id']]}, 409, key)
post({'text': '', 'attachment_ids': [own['id']]}, 409, key)
key = uuid.uuid4().hex
t = post({'text': 'без вложений'}, 201, key)
check(post({'text': 'без вложений', 'attachment_ids': []}, 201, key) == t and t['attachment_ids'] == [], 'missing attachment_ids != []')
history = c.call('GET', send + '?limit=100', actor=bob, schema='MessagePage')['json']['items']
check([x for x in history if x['id'] == m['id']] == [m], 'history lost attachment_ids')
width = max(len(r[0]) for r in results)
for label, status, code, ms in results:
print('%-*s %d %-24s %5d ms' % (width, label, status, code, ms))
check(all(status < 500 for _, status, _, _ in results), 'server error in negative suite')
print('PASS: %d upload cases, ACL and message linking; no 5xx' % len(results))
def chunked_upload(c, actor, chat):
"""Тело без Content-Length (Transfer-Encoding: chunked): потоковая запись в S3 требует длину — 400."""
url = urllib.parse.urlsplit(c.base)
conn = http.client.HTTPConnection(url.hostname, url.port, timeout=10)
conn.putrequest('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=c.png')
conn.putheader('Authorization', 'Bearer ' + actor['token'])
conn.putheader('Content-Type', 'image/png')
conn.putheader('Transfer-Encoding', 'chunked')
conn.endheaders()
start = time.monotonic()
conn.send(b'%x\r\n%s\r\n0\r\n\r\n' % (len(SAMPLE_PNG), SAMPLE_PNG))
r = conn.getresponse()
body = r.read()
check(r.status == 400 and b'invalid_request' in body, 'chunked upload: %d' % r.status)
return r.status, 'invalid_request', round((time.monotonic() - start) * 1000)
if __name__ == '__main__':
run(main)
+167
View File
@@ -0,0 +1,167 @@
#!/usr/bin/env python3
"""Отказы вокруг S3 и перезапуск всего стенда (уровни 3–4). Управляет Docker Compose этого каталога:
0. клиент обрывает загрузку на середине тела: компенсация убирает строку, объект не появляется;
1. S3 остановлен: upload/download → 503 быстро, метаданные и текст работают, readiness = 200;
2. S3 «завис» (docker pause): ответ 503 по таймауту API раньше таймаута LB;
3. после возврата S3 всё работает, неудачные загрузки не оставили ни строк, ни объектов; «воскресший» PUT убирает reconciler;
4. docker compose down (без -v) + up: метаданные, оригинал и прежний токен сохранены.
Запуск: python3 student-tests/failures.py --base-url http://localhost:8080"""
import hashlib
import http.client
import json
from pathlib import Path
import subprocess
import sys
import time
import urllib.parse
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, ROOT, arguments, check, run # noqa: E402
PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes()
def compose(*args, capture=False):
r = subprocess.run(['docker', 'compose', *args], cwd=ROOT, text=True, capture_output=True)
check(r.returncode == 0, 'docker compose %s: %s' % (args[0], r.stderr.strip().splitlines()[-1:]))
return r.stdout if capture else None
def sql(query):
return compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-tAc', query, capture=True).strip()
def reconcile(*flags):
for _ in range(3): # фоновый reconciler держит advisory lock — подождать и повторить
out = compose('run', '--rm', '--no-deps', '-T', 'reconciler', 'node', 'src/main.ts', 'reconcile', *flags, capture=True)
summary = json.loads(out.strip().splitlines()[-1])
if 'skipped' not in summary:
return summary
time.sleep(2)
raise AssertionError('reconciler lock is busy')
def abort_upload(base, token, chat):
"""Отправить заголовки и половину тела, затем закрыть соединение."""
url = urllib.parse.urlsplit(base)
conn = http.client.HTTPConnection(url.hostname, url.port, timeout=10)
conn.putrequest('POST', '/api/v1/chats/' + chat + '/attachments?filename=abort.png')
conn.putheader('Authorization', 'Bearer ' + token)
conn.putheader('Content-Type', 'image/png')
conn.putheader('Content-Length', str(len(PNG)))
conn.endheaders()
conn.send(PNG[:len(PNG) // 2])
time.sleep(0.5) # строка pending и S3 PUT уже начаты
conn.close()
return len(PNG) // 2
def wait_ready(c, seconds=90):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
if c.call('GET', '/health/ready', [200, 503])['status'] == 200:
return
except AssertionError:
pass
time.sleep(1)
raise AssertionError('stand not ready')
def recover(c, path, actor, seconds=60):
"""Время до первого успешного скачивания после возврата S3."""
start = time.monotonic()
while c.call('GET', path, [200, 503], actor=actor)['status'] != 200:
check(time.monotonic() - start < seconds, 'S3 path did not recover')
time.sleep(0.5)
return time.monotonic() - start
def main():
args = arguments('S3 outage, S3 hang and full stand restart')
c = Client(args.base_url, args.ca_file, timeout=30)
alice, bob, _, chat = c.bootstrap()
up = '/api/v1/chats/' + chat['id'] + '/attachments?filename=outage.png'
send = '/api/v1/chats/' + chat['id'] + '/messages'
hdr = {'Content-Type': 'image/png'}
att = c.call('POST', up, 201, actor=alice, raw=PNG, headers=hdr, schema='Attachment')['json']
content = '/api/v1/attachments/' + att['id'] + '/content'
pending_before = int(sql("SELECT count(*) FROM attachments WHERE state = 'pending'"))
log = []
def step(name, r):
log.append('%-52s %d %5d ms' % (name, r['status'], r['elapsed'] * 1000))
# 0. Обрыв загрузки клиентом. Перед этим --apply с grace 0 (кроме теста никто не пишет): чистая база для сравнения.
reconcile('--grace=0', '--apply')
sent = abort_upload(c.base, alice['token'], chat['id'])
time.sleep(1.5)
left = sql("SELECT count(*) FROM attachments WHERE chat_id = '%s' AND filename = 'abort.png'" % chat['id'])
after = reconcile('--grace=0')
log.append('client abort после %d из %d байт: строк abort.png %s, сверка: %s' % (sent, len(PNG), left, json.dumps(after['findings'])))
check(left == '0' and not after['findings'], 'aborted upload left a row or an object')
# 1. S3 остановлен.
compose('stop', 's3')
try:
step('S3 stopped: /health/ready (S3 не критичен)', c.call('GET', '/health/ready', 200))
for i in range(3):
step('S3 stopped: upload #%d' % (i + 1), c.call('POST', up, 503, actor=alice, raw=PNG, headers=hdr))
step('S3 stopped: download', c.call('GET', content, 503, actor=bob))
step('S3 stopped: metadata (только БД)', c.call('GET', '/api/v1/attachments/' + att['id'], 200, actor=bob, schema='Attachment'))
step('S3 stopped: text message', c.call('POST', send, 201, actor=alice, body={'text': 'S3 недоступен'},
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message'))
step('S3 stopped: message with ready attachment', c.call('POST', send, 201, actor=alice, body={'text': '', 'attachment_ids': [att['id']]},
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message'))
finally:
compose('start', 's3')
# Компенсация сначала удаляет pending-строку (БД доступна), затем объект: S3 недоступен, но объекта и нет — PUT не прошёл.
leftover = int(sql("SELECT count(*) FROM attachments WHERE state = 'pending'")) - pending_before
log.append('pending-строк после 3 неудачных загрузок: %d' % leftover)
check(leftover == 0, 'compensation left pending rows')
log.append('S3 started: download снова 200 через %.1f s' % recover(c, content, bob))
# 2. S3 завис: TCP-соединения не отвечают.
c.call('GET', content, 200, actor=bob) # прогреть keep-alive соединения API → S3
compose('pause', 's3')
try:
step('S3 paused: download (таймаут сокета S3 8 с)', c.call('GET', content, 503, actor=bob))
step('S3 paused: upload', c.call('POST', up, 503, actor=alice, raw=PNG, headers=hdr))
step('S3 paused: text message', c.call('POST', send, 201, actor=alice, body={'text': 'S3 завис'},
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message'))
finally:
compose('unpause', 's3')
# 3. S3 вернулся.
log.append('S3 unpaused: download снова 200 через %.1f s' % recover(c, content, bob))
step('S3 back: upload', c.call('POST', up, 201, actor=alice, raw=PNG, headers=hdr, schema='Attachment'))
r = c.call('GET', content, 200, actor=bob)
check(r['bytes'] == PNG, 'original changed')
step('S3 back: download old attachment', r)
# Ожидаемо: пусто или orphan_object — PUT, который S3 буферизовал во время pause и выполнил после того,
# как API сдался и компенсация уже удалила строку и объект (объект «воскрес»).
dry = reconcile('--grace=0')
log.append('reconcile dry-run --grace=0: %s' % json.dumps(dry['findings'], ensure_ascii=False))
check(set(dry['findings']) <= {'orphan_object'}, 'unexpected findings')
fixed = reconcile('--grace=0', '--apply')
again = reconcile('--grace=0')
log.append('reconcile --apply: applied=%d; повтор: %s' % (fixed['applied'], json.dumps(again['findings'])))
check(not again['findings'], 'reconciler left inconsistencies')
# 4. Полный перезапуск стенда с сохранением volumes: down удаляет контейнеры и сети, не volumes.
compose('down')
compose('up', '-d', '--wait')
wait_ready(c)
r = c.call('GET', content, 200, actor=bob) # прежний токен
check(r['bytes'] == PNG and hashlib.sha256(r['bytes']).hexdigest() == att['sha256'], 'original lost after down/up')
step('down + up -d: download with old token', r)
meta = c.call('GET', '/api/v1/attachments/' + att['id'], 200, actor=bob, schema='Attachment')['json']
check(meta == att, 'metadata changed after restart')
print('\n'.join(log))
print('PASS: S3 outage/hang degrade only attachments (503), compensation + reconciler clean up, full restart keeps data')
if __name__ == '__main__':
run(main)
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Один Idempotency-Key, N параллельных запросов через LB (то есть через разные реплики).
Половина запросов с телом A, половина с телом B: должно появиться ровно одно сообщение, каждый 201 возвращает его,
другое тело получает 409. Запуск: python3 student-tests/idempotency_race.py --base-url http://localhost:8080"""
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
import sys
import threading
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, arguments, check, run # noqa: E402
def main():
args = arguments('Parallel same-key POST race', lambda p: p.add_argument('--parallel', type=int, default=32))
c = Client(args.base_url, args.ca_file)
alice, bob, _, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id'] + '/messages'
key = 'race-' + uuid.uuid4().hex
texts = ['гонка A ' + key, 'гонка B ' + key]
barrier = threading.Barrier(args.parallel)
def send(i):
local = Client(args.base_url, args.ca_file)
barrier.wait()
r = local.call('POST', path, [201, 409], actor=alice, body={'text': texts[i % 2]}, headers={'Idempotency-Key': key}, schema='Message')
return r['status'], r['json'], r['headers']['X-Instance-Id']
with ThreadPoolExecutor(args.parallel) as pool:
results = list(pool.map(send, range(args.parallel)))
created = [body for status, body, _ in results if status == 201]
check(created, 'no request succeeded')
winner = created[0]
check(all(body == winner for body in created), 'replicas returned different messages for one key')
check(all(body['error']['code'] == 'conflict' for status, body, _ in results if status == 409), '409 without conflict code')
statuses = {texts[i % 2]: set() for i in range(2)}
for i, (status, _, _) in enumerate(results):
statuses[texts[i % 2]].add(status)
check(statuses[winner['text']] == {201}, 'winning body must always get 201')
check(statuses[next(t for t in texts if t != winner['text'])] == {409}, 'other body must always get 409')
instances = {inst for _, _, inst in results}
check(len(instances) >= 2, 'race did not reach two replicas')
history = c.call('GET', path + '?limit=100', actor=bob, schema='MessagePage')['json']['items']
stored = [m for m in history if key in m['text']]
check(stored == [winner], 'expected exactly one stored message equal to the replayed one')
# Тот же ключ у другого пользователя независим.
other = c.message(bob, chat, texts[0], key=key)['json']
check(other['id'] != winner['id'] and other['sender_id'] == bob['id'], 'key scope leaked across users')
print(json.dumps({'parallel': args.parallel, 'replicas_hit': len(instances), 'created_201': len(created),
'conflict_409': args.parallel - len(created), 'stored_messages': len(stored)}, ensure_ascii=False))
print('PASS: concurrent same-key POSTs through different replicas created exactly one message')
if __name__ == '__main__':
run(main)
+31
View File
@@ -0,0 +1,31 @@
// Проба прав S3 изнутри контейнера сервиса (его же ключами из /run/secrets).
// Запуск: docker compose exec -T api node --input-type=module - <key> < student-tests/s3_probe.mjs
// Печатает по строке «операция: результат»; ключи и секреты не выводятся.
import { readFileSync } from 'node:fs';
import { CreateBucketCommand, GetObjectCommand, ListObjectsV2Command, PutObjectCommand, DeleteObjectCommand, S3Client } from '@aws-sdk/client-s3';
const key = process.argv[2];
const bucket = process.env.S3_BUCKET;
const s3 = new S3Client({
endpoint: process.env.S3_ENDPOINT, region: process.env.S3_REGION, forcePathStyle: true, maxAttempts: 1,
credentials: {
accessKeyId: readFileSync('/run/secrets/s3_access_key_id', 'utf8').trim(),
secretAccessKey: readFileSync('/run/secrets/s3_secret_access_key', 'utf8').trim(),
},
});
const probe = async (name, command) => {
try {
await s3.send(command);
console.log(`${name}: allowed`);
} catch (err) {
console.log(`${name}: denied (${err.$metadata?.httpStatusCode} ${err.name})`);
}
};
const scratch = `probe/${Date.now()}`;
await probe('GetObject own bucket', new GetObjectCommand({ Bucket: bucket, Key: key }));
await probe('ListObjectsV2 own bucket', new ListObjectsV2Command({ Bucket: bucket, MaxKeys: 1 }));
await probe('CreateBucket other', new CreateBucketCommand({ Bucket: `probe-${Date.now()}` }));
await probe('PutObject other bucket', new PutObjectCommand({ Bucket: 'other-bucket', Key: 'x', Body: 'x' }));
await probe('PutObject own bucket', new PutObjectCommand({ Bucket: bucket, Key: scratch, Body: 'x' }));
await probe('DeleteObject own bucket', new DeleteObjectCommand({ Bucket: bucket, Key: scratch }));
s3.destroy(); // keep-alive сокеты иначе держат процесс до idle-таймаута S3