Выполнение работы на 4.

This commit is contained in:
2026-11-13 21:41:50 +03:00
parent ec540a1a72
commit 6308f21ec7
104 changed files with 7310 additions and 13 deletions
+56
View File
@@ -0,0 +1,56 @@
# Проверки вложений lab4
Запущенный стенд нужен заранее. Публичные `tests/` и контракт не изменяются.
Сценарии используют только синтетические данные и не выводят токены.
```sh
python -X utf8 scripts/wait-ready.py --base-url http://localhost:18084
python -X utf8 tests/smoke.py --base-url http://localhost:18084
python -u -X utf8 student-tests/attachments.py --base-url http://localhost:18084
```
Проверяются PNG и JPEG, оригинальные bytes, metadata DTO, ACL, авторизация,
повреждения/CRC, подмена MIME, имена файлов, превышение bytes и пикселей,
PNG с распаковкой больше заявленных размеров, ссылки на вложения в сообщениях,
пустой текст с вложением, повторы и конфликт Idempotency-Key.
`fixtures/sample.jpg` — синтетический JPEG 8×8; PNG берётся из публичного fixture.
Явная проверка отказов (останавливает и восстанавливает только контейнеры lab4):
```sh
python -u -X utf8 student-tests/attachments.py --base-url http://localhost:18084 --faults
```
Требует Docker CLI и доступа к daemon. Сначала выполняются обычные проверки,
затем останавливается API-контейнер, принявший upload, и файл скачивается через
другой. После этого проверяются недоступность S3 и restart всех сервисов со
старыми сессиями и теми же volumes. Тест оставляет стенд работающим.
Тестовые пользователи/чаты/сообщения остаются в учебной БД: обязательный API
не содержит delete. Сброс volumes не является частью сценария.
## Уровень 4
```sh
dotnet test scr/Messenger.Api.Tests/Messenger.Api.Tests.csproj --filter FullyQualifiedName~UploadCleanupTests
python -u -X utf8 student-tests/s3_bootstrap.py --base-url http://localhost:18084
python -u -X utf8 student-tests/upload_memory.py --base-url http://localhost:18084
```
`UploadCleanupTests` внедряет отказ после реального S3 PUT, проверяет устойчивый
журнал при пересоздании API, grace period, защиту ready, повтор после отказа S3,
запоздавший PUT, блокировки параллельных очистителей и сохранение старого tombstone.
Используются отдельные Testcontainers PostgreSQL/MinIO; timestamps изменяются
только в тестовой БД, production grace не уменьшается.
`s3_bootstrap.py` дважды выполняет bootstrap при существующем файле и проверяет,
что файл/доступ API сохранились. Затем проверяет закрытые порты/консоль, отсутствие
root credentials у API и прямые S3-операции ограниченными ключами.
`upload_memory.py` сначала обрывает реальный TCP upload, затем для двух размеров
PNG запускает по 10 barrier-synchronized запросов без retries. Скрипт **перезапускает
API перед каждым размером**, измеряет kernel cgroup high-water памяти (v1/v2),
VmHWM/VmRSS процесса и CPU usage delta. Результаты: `evidence/upload-memory.json`.
Клиент генерирует изображения в собственной памяти, она не входит в память API.
После нагрузки проверяется успешная новая загрузка. 503 из ограниченной очереди
фиксируется отдельно от успешных запросов; для p50/p95/p99 используются только успешные.
+158
View File
@@ -0,0 +1,158 @@
#!/usr/bin/env python3
"""Black-box attachment tests. --faults explicitly stops/restarts only this Compose project."""
import argparse
import binascii
import json
from pathlib import Path
import struct
import subprocess
import sys
import time
import urllib.error
import urllib.request
from urllib.parse import quote
import uuid
import zlib
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check, run
def docker(*args):
return subprocess.check_output(['docker', 'compose', '--env-file', '.env', *args],
cwd=ROOT, stderr=subprocess.STDOUT, text=True)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--base-url', default='http://localhost:8080')
parser.add_argument('--faults', action='store_true')
args = parser.parse_args()
c = Client(args.base_url, timeout=20)
alice, bob, eve, chat = c.bootstrap()
path = '/api/v1/chats/' + chat['id']
png = (ROOT / 'tests/fixtures/sample.png').read_bytes()
def upload(raw=png, mime='image/png', name='sample.png', actor=alice, expected=201):
return c.call('POST', path+'/attachments?filename='+quote(name, safe=''), expected,
actor=actor, raw=raw, headers={'Content-Type': mime},
schema='Attachment' if expected == 201 else None)
uploaded = upload()
att = uploaded['json']
content_path = '/api/v1/attachments/'+att['id']+'/content'
check(att['status'] == 'ready' and att['variants'] == [] and att['error_code'] is None, 'invalid ready metadata')
check(c.call('GET', content_path, actor=bob)['bytes'] == png, 'original changed')
for suffix in ('', '/content'):
c.call('GET', '/api/v1/attachments/'+att['id']+suffix, 404, actor=eve)
c.call('GET', '/api/v1/attachments/'+str(uuid.uuid4())+suffix, 404, actor=alice)
upload(actor=eve, expected=404)
c.call('POST', path+'/attachments?filename=sample.png', 401, raw=png,
headers={'Content-Type': 'image/png'})
c.call('GET', content_path+'?variant=thumbnail', 404, actor=bob)
check(c.call('GET', content_path+'?variant=original', actor=bob)['bytes'] == png, 'original variant changed')
print('PASS: ready metadata, original bytes, authentication and chat ACL.')
jpeg = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes()
jpg_att = upload(jpeg, 'image/jpeg', 'sample.jpg')['json']
check(c.call('GET', '/api/v1/attachments/'+jpg_att['id']+'/content', actor=bob)['bytes'] == jpeg, 'JPEG changed')
upload(png, 'image/jpeg', expected=415)
upload(jpeg, 'image/png', expected=415)
upload(b'not an image', expected=415)
upload(b'', expected=415)
upload(png[:40], expected=415)
damaged = bytearray(png)
damaged[len(damaged)//2] ^= 1
upload(bytes(damaged), expected=415)
upload(jpeg[:-2], 'image/jpeg', expected=415)
upload(mime='application/octet-stream', expected=415)
for name in ('../x.png', 'x\\y.png', 'x\x00.png', 'x\n.png', '', 'a'*256):
upload(name=name, expected=400)
upload(b'x'*(10485760+1), expected=413)
def chunk(kind, data):
return struct.pack('>I', len(data))+kind+data+struct.pack('>I', binascii.crc32(kind+data)&0xffffffff)
huge = b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR', struct.pack('>IIBBBBB',10000,10000,8,2,0,0,0))
huge += chunk(b'IDAT',zlib.compress(b''))+chunk(b'IEND',b'')
upload(huge, expected=413)
bomb = b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',8,8,8,2,0,0,0))
bomb += chunk(b'IDAT',zlib.compress(b'\0'*(1024*1024)))+chunk(b'IEND',b'')
upload(bomb, expected=415)
print('PASS: PNG/JPEG, MIME spoofing, damaged files, filenames, byte and pixel limits.')
key = uuid.uuid4().hex
msg = c.message(bob, chat, '', key=key, attachments=[att['id']])['json']
check(c.message(bob, chat, '', key=key, attachments=[att['id']])['json'] == msg, 'replay changed')
c.call('POST',path+'/messages',409,actor=bob,body={'text':'','attachment_ids':[jpg_att['id']]},headers={'Idempotency-Key':key})
for ids, expected in (([att['id']]*2,400), ([att['id']]*11,400), ([str(uuid.uuid4())],404)):
c.call('POST',path+'/messages',expected,actor=alice,body={'text':'','attachment_ids':ids},headers={'Idempotency-Key':uuid.uuid4().hex})
another = c.call('POST','/api/v1/chats',201,actor=alice,
body={'title':'Another','member_ids':[alice['id']]},schema='Chat')['json']
c.call('POST','/api/v1/chats/'+another['id']+'/messages',404,actor=alice,
body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
items = c.call('GET',path+'/messages',actor=alice,schema='MessagePage')['json']['items']
check(msg in items, 'attachment message missing from history')
print('PASS: attachment-only messages, other uploader in same chat, idempotency and foreign attachment rejection.')
if not args.faults:
return
def wait_ready():
deadline = time.monotonic()+60
while time.monotonic() < deadline:
try:
c.call('GET','/health/ready',schema='Health')
return
except AssertionError:
time.sleep(.5)
raise AssertionError('API did not recover')
instances = {c.call('GET',content_path,actor=bob)['headers']['X-Instance-Id'] for _ in range(12)}
check(len(instances)>=2, 'two replicas not observed')
target = uploaded['headers']['X-Instance-Id']
containers = docker('ps','-q','api').split()
matching = [cid for cid in containers if cid.startswith(target)]
check(len(matching)==1, 'uploading container not found')
target_id = matching[0]
try:
subprocess.check_output(['docker','stop','--time','5',target_id],stderr=subprocess.STDOUT)
downloaded = c.call('GET',content_path,actor=bob)
check(downloaded['bytes']==png and downloaded['headers']['X-Instance-Id']!=target, 'failover lost attachment')
print('PASS: stopping the uploading API replica preserves the file on another replica.')
finally:
subprocess.check_output(['docker','start',target_id],stderr=subprocess.STDOUT)
wait_ready()
try:
docker('stop','s3')
time.sleep(3)
try:
urllib.request.urlopen(args.base_url+'/health/ready',timeout=10)
raise AssertionError('S3 outage left readiness healthy')
except urllib.error.HTTPError as ex:
check(ex.code==503,'S3 outage must give 503')
for method, url, data in [('GET', content_path, None), ('POST',path+'/attachments?filename=outage.png',png)]:
request = urllib.request.Request(args.base_url+url,data=data,method=method,
headers={'Authorization':'Bearer '+alice['token'],'Content-Type':'image/png'})
try:
urllib.request.urlopen(request,timeout=10)
raise AssertionError('S3 outage unexpectedly served attachment')
except urllib.error.HTTPError as ex:
check(ex.code==503,'attachment route during S3 outage must give 503')
print('PASS: S3 outage makes readiness unavailable (503).')
finally:
docker('start','s3')
wait_ready()
check(c.call('GET',content_path,actor=bob)['bytes']==png, 'S3 restart lost file')
docker('restart','db','cache','s3','api','lb')
wait_ready()
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
check(c.call('GET',content_path,actor=bob)['bytes']==png,'stack restart lost original')
c.call('GET','/api/v1/attachments/'+att['id'],actor=bob,schema='Attachment')
items = c.call('GET',path+'/messages',actor=bob,schema='MessagePage')['json']['items']
check(msg in items,'stack restart lost attachment message')
print('PASS: restarting DB, cache, S3, API and LB preserves sessions, metadata, messages and original bytes.')
if __name__ == '__main__':
run(main)
Binary file not shown.

After

Width:  |  Height:  |  Size: 631 B

+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env python3
"""Repeat bootstrap with an existing API object, then check least-privilege S3 access."""
import argparse
import json
from pathlib import Path
import subprocess
import sys
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client, check, run
def compose(*args):
return subprocess.check_output(['docker','compose','--env-file','.env',*args],cwd=ROOT,
stderr=subprocess.STDOUT,text=True)
def main():
p=argparse.ArgumentParser()
p.add_argument('--base-url',default='http://localhost:18084')
args=p.parse_args()
c=Client(args.base_url,timeout=30)
alice,bob,eve,chat=c.bootstrap()
attachment,original=c.attachment(alice,chat)
for _ in range(2):
compose('run','--rm','--no-deps','s3-init')
downloaded=c.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=bob)
check(downloaded['bytes']==original,'bootstrap changed an existing object or API credentials')
print('PASS: two bootstrap runs preserve an existing API attachment and credentials.')
config=json.loads(compose('config','--format','json'))
check(not config['services']['s3'].get('ports'),'S3 ports are published')
check(config['services']['s3']['environment']['MINIO_BROWSER']=='off','admin console is enabled')
keys={x['source'] for x in config['services']['api']['secrets']}
check(not keys.intersection({'s3_root_user','s3_root_password'}),'API has root credentials')
print('PASS: S3 has no published ports or browser console; API has no root credentials.')
output=compose('run','--rm','--no-deps','s3-check')
for line in output.splitlines():
if line.startswith('PASS:'): print(line)
if __name__=='__main__':
run(main)
+174
View File
@@ -0,0 +1,174 @@
#!/usr/bin/env python3
"""Ten simultaneous real PNG uploads; kernel cgroup peak/RSS after a fresh API restart."""
import argparse
import binascii
import concurrent.futures
import hashlib
import http.client
import json
import os
from pathlib import Path
import random
import struct
import subprocess
import sys
import threading
import time
from urllib.parse import urlsplit
import zlib
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client, check, run
def compose(*args):
return subprocess.check_output(['docker','compose','--env-file','.env',*args],cwd=ROOT,
stderr=subprocess.STDOUT,text=True)
def wait(c):
deadline=time.monotonic()+90
while time.monotonic()<deadline:
try:
c.call('GET','/health/ready',schema='Health')
return
except AssertionError:
time.sleep(.5)
raise AssertionError('API did not recover')
def png(width):
def chunk(kind,data):
return struct.pack('>I',len(data))+kind+data+struct.pack('>I',binascii.crc32(kind+data)&0xffffffff)
rng=random.Random(20261113+width)
pixels=b''.join(b'\0'+rng.randbytes(width*3) for _ in range(width))
return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,width,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(pixels,1))+chunk(b'IEND',b'')
def memory(containers):
result={}
for cid in containers:
# Cgroup includes managed/native allocations and charged file cache;
# VmHWM is the kernel high-water RSS for the dotnet process.
raw=subprocess.check_output(['docker','exec',cid,'sh','-c',
'if [ -f /sys/fs/cgroup/memory.current ]; then cat /sys/fs/cgroup/memory.current /sys/fs/cgroup/memory.peak /sys/fs/cgroup/memory.max; '
'else cat /sys/fs/cgroup/memory/memory.usage_in_bytes /sys/fs/cgroup/memory/memory.max_usage_in_bytes /sys/fs/cgroup/memory/memory.limit_in_bytes; fi; '
'sed -n "/^VmRSS:/p; /^VmHWM:/p" /proc/1/status'],text=True)
lines=raw.splitlines()
fields={line.split(':')[0]:int(line.split()[1])*1024 for line in lines[3:]}
result[cid[:12]]={'cgroup_current_bytes':int(lines[0]),'cgroup_peak_bytes':int(lines[1]),
'limit_bytes':None if lines[2]=='max' else int(lines[2]),
'rss_bytes':fields['VmRSS'],'rss_peak_bytes':fields['VmHWM']}
return result
def cpu_usage(containers):
result={}
for cid in containers:
raw=subprocess.check_output(['docker','exec',cid,'sh','-c',
'if [ -f /sys/fs/cgroup/cpuacct/cpuacct.usage ]; then cat /sys/fs/cgroup/cpuacct/cpuacct.usage; '
'else while read key value; do if [ "$key" = usage_usec ]; then echo $((value * 1000)); fi; done < /sys/fs/cgroup/cpu.stat; fi'],text=True)
result[cid[:12]]=int(raw.strip())
return result
def main():
p=argparse.ArgumentParser()
p.add_argument('--base-url',default='http://localhost:18084')
p.add_argument('--output',default='evidence/upload-memory.json')
p.add_argument('--concurrency',type=int,default=10)
args=p.parse_args()
check(args.concurrency>=10,'at least ten concurrent requests are required')
c=Client(args.base_url,timeout=40)
wait(c)
alice,bob,eve,chat=c.bootstrap()
path='/api/v1/chats/'+chat['id']+'/attachments?filename=memory.png'
# Drop a real TCP upload mid-body. Nothing may be published or sent to S3.
def counts():
return compose('exec','-T','db','psql','-U','messenger','-d','messenger','-At','-c',
'SELECT (SELECT count(*) FROM attachments), (SELECT count(*) FROM upload_intents)').strip()
before=counts()
url=urlsplit(args.base_url)
connection=http.client.HTTPConnection(url.hostname,url.port or 80,timeout=5)
connection.putrequest('POST',path)
connection.putheader('Authorization','Bearer '+alice['token'])
connection.putheader('Content-Type','image/png')
connection.putheader('Content-Length','1048576')
connection.endheaders()
connection.send(b'\x89PNG\r\n\x1a\n'+b'\0'*512)
connection.close()
time.sleep(2)
check(counts()==before,'interrupted HTTP upload published an attachment or intent')
containers=compose('ps','-q','api').split()
check(len(containers)>=2,'two API replicas required')
for cid in containers:
spool=subprocess.check_output(['docker','exec',cid,'sh','-c',
'find /tmp -maxdepth 1 -type f -name "attachment-*" | wc -l'],text=True)
check(int(spool.strip())==0,'interrupted upload left a temporary file')
print('PASS: interrupted TCP upload publishes nothing and leaves no temporary files.',flush=True)
config=json.loads(compose('config','--format','json'))
limits=config['services']['api'].get('deploy',{}).get('resources',{}).get('limits',{})
results=[]
for width in (1024,1600):
content=png(width)
check(len(content)<=10485760,'generated PNG exceeds contract')
compose('restart','api') # Reset kernel high-water counters for this trial.
wait(c)
containers=compose('ps','-q','api').split()
baseline=memory(containers)
cpu_before=cpu_usage(containers)
barrier=threading.Barrier(args.concurrency)
def upload(index):
client=Client(args.base_url,timeout=40)
barrier.wait(timeout=30)
response=client.call('POST',path,[201,503],actor=alice,raw=content,
headers={'Content-Type':'image/png'})
body=json.loads(response['bytes'])
if response['status']==201:
check(body['sha256']==hashlib.sha256(content).hexdigest(),'wrong upload SHA-256')
else:
check(body['error']['code']=='unavailable','overload must be 503 unavailable')
return {'status':response['status'],'latency_seconds':round(response['elapsed'],4),
'instance':response['headers']['X-Instance-Id']}
started=time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as pool:
responses=list(pool.map(upload,range(args.concurrency)))
elapsed=time.monotonic()-started
cpu_after=cpu_usage(containers)
peak=memory(containers)
successful=sum(x['status']==201 for x in responses)
check(successful>0,'no upload succeeded')
sorted_latencies=sorted(x['latency_seconds'] for x in responses if x['status']==201)
def percentile(p): return sorted_latencies[max(0,int(len(sorted_latencies)*p+.999)-1)]
result={'width':width,'height':width,'size_bytes':len(content),'concurrency':args.concurrency,
'successful':successful,'overload_503':len(responses)-successful,'elapsed_seconds':round(elapsed,4),
'successful_rps':round(successful/elapsed,3),'p50_success_seconds':percentile(.5),
'p95_success_seconds':percentile(.95),'p99_success_seconds':percentile(.99),
'cpu_core_seconds':{cid:round((cpu_after[cid]-cpu_before[cid])/1e9,4) for cid in cpu_before},
'average_cpu_percent_of_one_core':{cid:round((cpu_after[cid]-cpu_before[cid])/1e9/elapsed*100,2) for cid in cpu_before},
'baseline':baseline,'after':peak,'responses':responses}
results.append(result)
check(all(v['limit_bytes'] is None or v['cgroup_peak_bytes']<v['limit_bytes'] for v in peak.values()),'API reached its memory limit')
print('PASS: '+json.dumps({k:result[k] for k in ('size_bytes','concurrency','successful','overload_503')})+
' cgroup_peak_MiB='+str({k:round(v['cgroup_peak_bytes']/1048576,2) for k,v in peak.items()})+
' RSS_peak_MiB='+str({k:round(v['rss_peak_bytes']/1048576,2) for k,v in peak.items()}),flush=True)
wait(c)
sample=(ROOT/'tests/fixtures/sample.png').read_bytes()
c.call('POST',path,201,actor=alice,raw=sample,headers={'Content-Type':'image/png'},schema='Attachment')
host=subprocess.check_output(['docker','info','--format','{{.NCPU}} {{.MemTotal}}'],text=True).split()
report={'date':'2026-11-13','method':'10 barrier-synchronized HTTP requests, no retries; fresh API restart per size; kernel cgroup high-water (v1/v2) and /proc/1/status VmHWM; cgroup CPU usage delta',
'docker_host':{'logical_cpus':int(host[0]),'memory_bytes':int(host[1])},
'api_limits':limits,'docker':subprocess.check_output(['docker','version','--format','{{.Server.Version}}'],text=True).strip(),
'interrupted_upload':'PASS','trials':results,'post_load_recovery':'PASS',
'limitations':'Two file sizes, one run each. Closed workload, client setup included in elapsed time; kernel peak since restart includes readiness/warmup. No claim about maximum sustainable throughput.'}
output=ROOT/args.output
output.parent.mkdir(parents=True,exist_ok=True)
output.write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8')
print('PASS: memory experiment saved to '+args.output,flush=True)
if __name__=='__main__':
run(main)