Fix attachment contract and reconcile storage safely across API replicas
This commit is contained in:
@@ -55,3 +55,20 @@ make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.
|
||||
## Что ещё остаётся доказать
|
||||
|
||||
Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production.
|
||||
|
||||
## Дополнительные проверки реализации lab4
|
||||
|
||||
Windows: используйте `py` вместо `python3`. Все команды выполняются из корня.
|
||||
|
||||
- `py tests/extended.py`: MIME, corrupt/oversize, filename, принадлежность вложений, 24 конкурентных повтора сообщения через две реплики, 20 PNG по ~8.3 MiB при concurrency=10, RSS samples и logout.
|
||||
- `py tests/resilience.py --mode persistence --action-script scripts/restart.cmd`: перезапуск PostgreSQL, Redis, MinIO, обеих API и LB; прежняя сессия и checksum. На Linux используйте `scripts/restart.sh`.
|
||||
- `py tests/resilience.py --mode failover --action-script scripts/stop-one.cmd`: остановка конкретной реплики; после проверки `docker compose up -d api`. На Linux используйте `.sh`.
|
||||
- `py tests/track2.py`: только изолированный стенд. Перед запуском задайте `RECONCILER_INTERVAL_MS=3000`, `RECONCILER_GRACE_PERIOD_MINUTES=1`, `RECONCILER_DRY_RUN=true` и пересоздайте API (`docker compose up -d --no-deps api`). Скрипт создаёт orphan и missing, выдерживает grace, проверяет dry-run, пересоздаёт API с apply и проверяет повтор и сохранность свежего объекта. Вывод не содержит токенов. Тест требует Docker CLI и права оператора. После проверки верните переменные к defaults и пересоздайте API.
|
||||
|
||||
Модульные проверки: JDK 21, `./gradlew test` (`gradlew.bat test` в Windows). Они не требуют работающих хранилищ. Black-box проверки работают с реальным PostgreSQL/S3, не с моками. `BASE_URL=http://127.0.0.1:8080` исключает задержки разрешения localhost на Windows.
|
||||
|
||||
`py tests/faults.py`: private bucket, остановка/возврат S3, отказ INSERT метаданных через временный DB trigger; trigger удаляется в finally. Требует изолированного стенда и прав оператора.
|
||||
|
||||
`py tests/locking.py`: задержка INSERT на 6s через временный DB trigger, проверка невидимости метаданных и запрета exclusive advisory lock в реальном окне PUT/COMMIT. Затем сверка bytes. `py tests/aborted.py`: частичное тело HTTP и разрыв соединения, сверка отсутствия изменений БД/S3. Запускать последовательно без других инъекций/нагрузки. Оба сценария предназначены для изолированного стенда.
|
||||
|
||||
Пять замечаний review (06.11.2026): `py tests/review_regressions.py`, требуется Pillow. Синтетические PNG/JPEG, точные 33 bytes PNG, filename traversal, Message/ACL и PNG ровно 1770843 bytes; сравнение БД/S3 при отказе. BASE_URL задаётся окружением. При резервировании Windows порта 8080 используйте `docker compose -f docker-compose.yml -f compose.review.yaml up -d` и `$env:BASE_URL='http://127.0.0.1:18080'`.
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Interrupted client body must not produce metadata or S3 writes."""
|
||||
from client import Client, check, run
|
||||
from track2 import sql, mc
|
||||
import socket,time
|
||||
|
||||
def main():
|
||||
c=Client(); a,b,e,chat=c.bootstrap()
|
||||
before=sql('select count(*) from attachments;')
|
||||
objects=mc('mc ls proof/messenger-attachments/')
|
||||
with socket.create_connection(('127.0.0.1',8080),timeout=5) as connection:
|
||||
headers=('POST /api/v1/chats/'+chat['id']+'/attachments?filename=partial.png HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer '+a['token']+'\r\nContent-Type: image/png\r\nContent-Length: 1048576\r\n\r\n')
|
||||
connection.sendall(headers.encode()+b'partial')
|
||||
time.sleep(2)
|
||||
check(sql('select count(*) from attachments;')==before,'partial metadata committed')
|
||||
check(mc('mc ls proof/messenger-attachments/')==objects,'partial object stored')
|
||||
print('PASS interrupted upload: connection closed before full body; metadata and S3 object listing unchanged')
|
||||
|
||||
if __name__ == '__main__': run(main)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Additional contract and cross-replica concurrency tests. No secrets in output."""
|
||||
from client import Client, check, run
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
import uuid, json, time, subprocess, threading, zlib, struct, os
|
||||
|
||||
def main():
|
||||
c=Client(timeout=30)
|
||||
a,b,e,chat=c.bootstrap()
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400,actor=a,body={'text':True},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
data=Path('tests/fixtures/sample.png').read_bytes()
|
||||
path='/api/v1/chats/'+chat['id']+'/attachments?filename=test.png'
|
||||
def upload(raw=data, mime='image/png', expected=201, target=path):
|
||||
return c.call('POST',target,expected,actor=a,raw=raw,headers={'Content-Type':mime},schema='Attachment' if expected==201 else None)
|
||||
upload(data,'image/jpeg',415)
|
||||
upload(data[:40],expected=415)
|
||||
ihdr=struct.pack('>IIBBBBB',7000,7000,8,2,0,0,0)
|
||||
bomb=b'\x89PNG\r\n\x1a\n'+struct.pack('>I',13)+b'IHDR'+ihdr+struct.pack('>I',zlib.crc32(b'IHDR'+ihdr)&0xffffffff)
|
||||
upload(bomb,expected=413)
|
||||
upload(b'x'*10485761,expected=413)
|
||||
upload(target=path.replace('test.png','bad%7F.png'),expected=400)
|
||||
att=upload()['json']
|
||||
other=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'other','member_ids':[a['id']]},schema='Chat')['json']
|
||||
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=a,body={'text':'x','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
for ids in ([att['id']]*2,[str(uuid.uuid4())]):
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',400 if len(ids)==2 else 404,actor=a,body={'text':'x','attachment_ids':ids},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
print('PASS negative: MIME, corrupt, oversized, filename, duplicate/unknown/cross-chat attachments')
|
||||
key=uuid.uuid4().hex
|
||||
def message(_):
|
||||
return c.call('POST','/api/v1/chats/'+chat['id']+'/messages',201,actor=a,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':key},schema='Message')
|
||||
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||
replies=list(pool.map(message,range(24)))
|
||||
check(len({r['json']['id'] for r in replies})==1,'duplicate message')
|
||||
instances={r['headers']['X-Instance-Id'] for r in replies}
|
||||
check(len(instances)>=2,'need two replicas')
|
||||
print('PASS 24 simultaneous idempotent requests across',len(instances),'replicas; one message')
|
||||
def chunk(kind, body):
|
||||
return struct.pack('>I',len(body))+kind+body+struct.pack('>I',zlib.crc32(kind+body)&0xffffffff)
|
||||
width=1700
|
||||
large=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,width,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(b''.join(b'\0'+os.urandom(width*3) for _ in range(width))))+chunk(b'IEND',b'')
|
||||
samples=[]; done=threading.Event()
|
||||
def sample():
|
||||
while not done.is_set():
|
||||
samples.append(subprocess.check_output(['docker','stats','--no-stream','--format','{{.Name}} {{.MemUsage}}'],text=True))
|
||||
sampler=threading.Thread(target=sample); sampler.start()
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
started=time.monotonic(); results=list(pool.map(lambda _:upload(large),range(20)))
|
||||
check(len({r['json']['id'] for r in results})==20,'uploads collided')
|
||||
done.set(); sampler.join()
|
||||
print('image_bytes=',len(large),'memory_samples=',samples)
|
||||
print('PASS 20 uploads concurrency=10 elapsed_seconds=',round(time.monotonic()-started,3))
|
||||
print(subprocess.check_output(['docker','stats','--no-stream','--format','{{.Name}} {{.MemUsage}}'],text=True))
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=a)
|
||||
for _ in range(10): c.call('GET','/api/v1/users/me',401,actor=a)
|
||||
print('PASS logout across replicas')
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Dependency and commit failure checks on a local isolated stand."""
|
||||
from client import Client, check, run
|
||||
from track2 import sql, mc, command
|
||||
import time, uuid
|
||||
|
||||
def main():
|
||||
c=Client(timeout=30); a,b,e,chat=c.bootstrap()
|
||||
att,data=c.attachment(a,chat)
|
||||
key=sql("select object_key from attachments where id='"+att['id']+"';")
|
||||
code=command(['docker','compose','exec','-T','minio','sh','-c','curl -s -o /dev/null -w "%{http_code}" http://localhost:9000/messenger-attachments/'+key])
|
||||
check(code=='403','bucket public')
|
||||
print('PASS direct anonymous GET existing object returns 403',flush=True)
|
||||
command(['docker','compose','stop','minio'])
|
||||
try:
|
||||
c.call('GET','/health/ready',503)
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=x.png',503,actor=a,raw=data,headers={'Content-Type':'image/png'})
|
||||
print('PASS S3 outage: readiness and upload return 503',flush=True)
|
||||
finally: command(['docker','compose','start','minio'])
|
||||
time.sleep(3)
|
||||
# DB trigger rejects metadata after successful PUT. Transaction rolls back; S3 compensation is tested.
|
||||
before=sql('select count(*) from attachments;')
|
||||
objects=mc('mc ls proof/messenger-attachments/')
|
||||
sql("create function proof_reject() returns trigger language plpgsql as $$ begin raise exception 'injected'; end; $$; create trigger proof_reject before insert on attachments for each row execute function proof_reject();")
|
||||
try:
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=x.png',500,actor=a,raw=data,headers={'Content-Type':'image/png'})
|
||||
finally:
|
||||
sql('drop trigger proof_reject on attachments; drop function proof_reject();')
|
||||
check(sql('select count(*) from attachments;')==before,'metadata committed')
|
||||
# saveAndFlush makes rejection observable before compensation, otherwise reconciler cleans after grace.
|
||||
print('PASS DB failure: no success response, no committed metadata; orphan cleanup covered by track2',flush=True)
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Barrier experiment: probe DB fencing during PUT -> metadata commit window."""
|
||||
from client import Client, check, run
|
||||
from track2 import sql
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import time
|
||||
|
||||
def main():
|
||||
c=Client(timeout=30); a,b,e,chat=c.bootstrap()
|
||||
before=sql('select count(*) from attachments;')
|
||||
sql("create function proof_delay() returns trigger language plpgsql as $$ begin perform pg_sleep(6); return NEW; end; $$; create trigger proof_delay before insert on attachments for each row execute function proof_delay();")
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
task=pool.submit(c.attachment,a,chat)
|
||||
for _ in range(30):
|
||||
if sql("select count(*) from pg_stat_activity where wait_event='PgSleep';")!='0': break
|
||||
time.sleep(.2)
|
||||
check(sql('select count(*) from attachments;')==before,'metadata visible before commit')
|
||||
check(sql('select pg_try_advisory_xact_lock(741204);')=='f','reconciler could enter active upload')
|
||||
att,data=task.result()
|
||||
check(sql('select pg_try_advisory_xact_lock(741204);')=='t','lock leaked after commit')
|
||||
received=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)['bytes']
|
||||
check(received==data,'bytes lost in commit window')
|
||||
print('PASS PUT/COMMIT barrier: uncommitted metadata invisible; exclusive reconcile lock denied during upload; released after commit; other member downloads identical bytes')
|
||||
finally:
|
||||
sql('drop trigger proof_delay on attachments; drop function proof_delay();')
|
||||
|
||||
if __name__ == '__main__': run(main)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Five review regressions, real Compose stack. JPEG fixture generation needs Pillow."""
|
||||
from client import Client, check, run
|
||||
from track2 import sql, mc
|
||||
from pathlib import Path
|
||||
from PIL import Image
|
||||
import io, os, struct, zlib, uuid, hashlib, time, urllib.request
|
||||
|
||||
|
||||
def png_large():
|
||||
def chunk(kind, data):
|
||||
return struct.pack('>I', len(data))+kind+data+struct.pack('>I',zlib.crc32(kind+data)&0xffffffff)
|
||||
width=700
|
||||
data=b''.join(b'\0'+os.urandom(width*3) for _ in range(width))
|
||||
base=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,width,8,2,0,0,0))+chunk(b'IDAT',zlib.compress(data))
|
||||
extra=1770843-len(base)-12-12
|
||||
return base+chunk(b'tEXt',b'proof\0'+b'x'*(extra-6))+chunk(b'IEND',b'')
|
||||
|
||||
|
||||
def main():
|
||||
print('2026-11-06 Europe/Moscow; current working tree; synthetic data only',flush=True)
|
||||
c=Client(base_url=os.environ.get('BASE_URL','http://127.0.0.1:8080'),timeout=30)
|
||||
for _ in range(90):
|
||||
try:
|
||||
c.call('GET','/health/ready',schema='Health');break
|
||||
except Exception: time.sleep(1)
|
||||
else: raise AssertionError('API not ready')
|
||||
a,b,e,chat=c.bootstrap()
|
||||
png=Path('tests/fixtures/sample.png').read_bytes()
|
||||
out=io.BytesIO(); Image.new('RGB',(32,24),(12,50,100)).save(out,format='JPEG'); jpeg=out.getvalue()
|
||||
path='/api/v1/chats/'+chat['id']+'/attachments?filename='
|
||||
def upload(data,mime='image/png',filename='proof.png',expected=201):
|
||||
return c.call('POST',path+filename,expected,actor=a,raw=data,headers={'Content-Type':mime},schema='Attachment' if expected==201 else None)
|
||||
def count(): return sql("select count(*) from attachments where chat_id='"+chat['id']+"';")
|
||||
before=int(count()); attachments=[]; instances=set()
|
||||
for data,mime,name in [(png,'image/png','proof.png'),(jpeg,'image/jpeg','proof.jpg')]*5:
|
||||
response=upload(data,mime,name); att=response['json']; attachments.append(att)
|
||||
instances.add(response['headers']['X-Instance-Id'])
|
||||
got=c.call('GET','/api/v1/attachments/'+att['id'],actor=b,schema='Attachment')['json']
|
||||
check(got['content_type']==mime and got['status']=='ready','bad MIME/status')
|
||||
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)['bytes']==data,'bytes differ')
|
||||
check(int(count())-before==10,'unexpected metadata count')
|
||||
print('PASS PNG/JPEG: 10 uploads -> 201; 10 metadata GET -> 200; 10 downloads identical; DB +10; instances='+str(len(instances)),flush=True)
|
||||
plain=c.message(a,chat,'plain')['json'];check(plain['attachment_ids']==[],'missing empty attachment_ids')
|
||||
attached=c.message(a,chat,'',attachments=[attachments[0]['id']])['json'];check(attached['attachment_ids']==[attachments[0]['id']],'attachment lost')
|
||||
other=c.call('POST','/api/v1/chats',201,actor=a,body={'title':'other','member_ids':[a['id']]},schema='Chat')['json']
|
||||
for actor,target,ids in [(a,other,[attachments[0]['id']]),(a,chat,[str(uuid.uuid4())]),(e,chat,[attachments[0]['id']])]:
|
||||
c.call('POST','/api/v1/chats/'+target['id']+'/messages',404,actor=actor,body={'text':'x','attachment_ids':ids},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
print('PASS messages: plain attachment_ids=[]; file-only POST -> 201; cross-chat/unknown/outsider -> 404',flush=True)
|
||||
before=count(); objects=mc('mc ls proof/messenger-attachments/')
|
||||
for _ in range(10): upload(png[:33],expected=415)
|
||||
upload(png,filename='..%2Fx.png',expected=400)
|
||||
check(count()==before,'rejected upload persisted metadata')
|
||||
check(mc('mc ls proof/messenger-attachments/')==objects,'rejected upload changed objects')
|
||||
print('PASS sample.png[:33]: 10 x 415; ../x.png: 400; DB and S3 unchanged',flush=True)
|
||||
large=png_large();check(len(large)==1770843,'fixture size mismatch')
|
||||
with Image.open(io.BytesIO(large)) as image: image.load()
|
||||
att=upload(large)['json']
|
||||
result=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)
|
||||
check(result['bytes']==large,'large PNG differs')
|
||||
print('PASS valid PNG exactly 1770843 bytes: POST -> 201 through LB; download checksum matches',flush=True)
|
||||
print('PASS all five review regressions',flush=True)
|
||||
|
||||
|
||||
if __name__=='__main__': run(main)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Controlled DB/S3 fault injection; use an isolated local Compose stack."""
|
||||
from client import Client, check, run
|
||||
from pathlib import Path
|
||||
import subprocess, time, uuid, os, json
|
||||
|
||||
def command(args, data=None):
|
||||
r=subprocess.run(args,input=data,text=True,capture_output=True)
|
||||
check(r.returncode==0,'operator command failed: '+args[0])
|
||||
return r.stdout.strip()
|
||||
|
||||
def sql(query):
|
||||
return command(['docker','compose','exec','-T','db','sh','-c','psql -U "$(cat /run/secrets/postgres_user)" -d "$(cat /run/secrets/postgres_db)" -At'],query)
|
||||
|
||||
def mc(action):
|
||||
return command(['docker','compose','exec','-T','minio','sh','-c',
|
||||
'mc alias set proof http://localhost:9000 "$(cat /run/secrets/minio_root_user)" "$(cat /run/secrets/minio_root_password)" >/dev/null && '+action])
|
||||
|
||||
def main():
|
||||
c=Client(timeout=30); a,b,e,chat=c.bootstrap()
|
||||
protected,protected_data=c.attachment(a,chat)
|
||||
c.message(a,chat,'protected',attachments=[protected['id']])
|
||||
protected_key=sql("select object_key from attachments where id='"+protected['id']+"';")
|
||||
att,data=c.attachment(a,chat)
|
||||
key=sql("select object_key from attachments where id='"+att['id']+"';")
|
||||
orphan='proof-'+uuid.uuid4().hex
|
||||
mc('mc cp /etc/hostname proof/messenger-attachments/'+orphan)
|
||||
sql("update attachments set created_at=now()-interval '20 minutes' where id='"+att['id']+"';")
|
||||
mc('mc rm proof/messenger-attachments/'+key)
|
||||
fresh='fresh-'+uuid.uuid4().hex
|
||||
# Objects must age past the configured one-minute test grace before scanning.
|
||||
time.sleep(62)
|
||||
mc('mc cp /etc/hostname proof/messenger-attachments/'+fresh)
|
||||
# API replicas run scheduled reconciliation with dry-run=true, interval=3s, grace=1min.
|
||||
time.sleep(6)
|
||||
check(sql("select status from attachments where id='"+att['id']+"';")=='READY','dry-run mutated DB')
|
||||
mc('mc stat proof/messenger-attachments/'+orphan)
|
||||
logs=command(['docker','compose','logs','--no-log-prefix','api'])
|
||||
proof='\n'.join(line for line in logs.splitlines() if 'Reconcile' in line)
|
||||
Path('evidence/reconciler-dry-run-log.txt').write_text(proof)
|
||||
check('orphan dryRun=true' in proof and 'missing dryRun=true' in proof,'dry-run did not report findings')
|
||||
print('PASS dry-run: old orphan and missing metadata detected; no mutations',flush=True)
|
||||
env=dict(os.environ,RECONCILER_INTERVAL_MS='3000',RECONCILER_GRACE_PERIOD_MINUTES='1',RECONCILER_DRY_RUN='false')
|
||||
r=subprocess.run(['docker','compose','up','-d','--no-deps','api'],env=env,capture_output=True)
|
||||
check(r.returncode==0,'recreate failed')
|
||||
for _ in range(90):
|
||||
if sql("select status from attachments where id='"+att['id']+"';")=='BROKEN': break
|
||||
time.sleep(1)
|
||||
check(sql("select status from attachments where id='"+att['id']+"';")=='BROKEN','missing not repaired')
|
||||
check(orphan not in mc('mc ls proof/messenger-attachments/'),'orphan retained')
|
||||
mc('mc stat proof/messenger-attachments/'+fresh)
|
||||
print('PASS apply: orphan removed, missing marked BROKEN, fresh object retained',flush=True)
|
||||
time.sleep(5)
|
||||
check(sql("select status from attachments where id='"+att['id']+"';")=='BROKEN','repeat changed result')
|
||||
mc('mc stat proof/messenger-attachments/'+protected_key)
|
||||
check(sql("select status from attachments where id='"+protected['id']+"';")=='READY','used attachment damaged')
|
||||
logs=command(['docker','compose','logs','--no-log-prefix','api'])
|
||||
Path('evidence/reconciler-apply-log.txt').write_text('\n'.join(line for line in logs.splitlines() if 'Reconcile' in line))
|
||||
print('PASS repeat is idempotent; referenced attachment and bytes retained',flush=True)
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user