forked from mtusi2026/mtusi2026lab4
ЛР4: MinIO, вложения и reconciler на оценку 5
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
"""Black-box validation of attachment security and message compatibility."""
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
import struct
|
||||
import urllib.parse
|
||||
import uuid
|
||||
import zlib
|
||||
from common import ROOT, Client, check, save
|
||||
|
||||
|
||||
def chunk(kind, data):
|
||||
return struct.pack('!I',len(data))+kind+data+struct.pack('!I',zlib.crc32(kind+data)&0xffffffff)
|
||||
|
||||
|
||||
def png(width=32, height=32):
|
||||
return (b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!IIBBBBB',width,height,8,2,0,0,0))+
|
||||
chunk(b'IDAT',zlib.compress((b'\0'+bytes([43,100,201])*width)*height))+chunk(b'IEND',b''))
|
||||
|
||||
|
||||
def main():
|
||||
c=Client(timeout=40)
|
||||
alice,bob,eve,chat=c.bootstrap()
|
||||
path='/api/v1/chats/'+chat['id']
|
||||
payload=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
passed=[]
|
||||
def upload(data, status, name='image.png', mime='image/png', actor=alice):
|
||||
result=c.call('POST',path+'/attachments?filename='+urllib.parse.quote(name,safe=''),status,
|
||||
actor=actor,raw=data,headers={'Content-Type':mime},schema='Attachment' if status==201 else None)
|
||||
return result
|
||||
upload(b'x'*(10485760+1),413);passed.append('byte limit before decode')
|
||||
upload(b'not an image',415)
|
||||
upload(payload[:40],415)
|
||||
upload(payload,415,mime='image/jpeg')
|
||||
upload(payload,415,mime='text/plain')
|
||||
upload(b'',415);passed.append('corrupt, empty, MIME spoof')
|
||||
# Valid header with impossible dimensions: rejection precedes allocation.
|
||||
huge=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!IIBBBBB',40000001,1,8,2,0,0,0))
|
||||
upload(huge,413);passed.append('pixel limit before full decode')
|
||||
for name in ('../a.png','a/b.png','a\\b.png','x\x00.png','x\n.png','x\x7f.png',' '*4,'a'*256):
|
||||
upload(payload,400,name=name)
|
||||
passed.append('unsafe filename')
|
||||
upload(payload,404,actor=eve)
|
||||
c.call('POST',path+'/attachments?filename=a.png',401,raw=payload,headers={'Content-Type':'image/png'})
|
||||
att=upload(payload,201,name='Фотография 😀.png')['json']
|
||||
check(att['sha256']==hashlib.sha256(payload).hexdigest(),'bad original hash')
|
||||
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)
|
||||
foreign=c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'other','member_ids':[alice['id'],bob['id']]},schema='Chat')['json']
|
||||
c.call('POST','/api/v1/chats/'+foreign['id']+'/messages',404,actor=alice,
|
||||
body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
passed.append('foreign attachment and chat ACL')
|
||||
for body in ({'text':'','attachment_ids':[att['id'],att['id']]},
|
||||
{'text':'','attachment_ids':None}, {'text':'x','attachment_ids':['not-uuid']},
|
||||
{'text':'x','sender_id':eve['id']}, {'text':' '}):
|
||||
c.call('POST',path+'/messages',400,actor=alice,body=body,headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
key=uuid.uuid4().hex
|
||||
first=c.message(alice,chat,'',key,[att['id']])['json']
|
||||
repeat=c.message(alice,chat,'',key,[att['id']])['json']
|
||||
check(first==repeat,'attachment message replay changed')
|
||||
c.call('POST',path+'/messages',409,actor=alice,body={'text':'changed','attachment_ids':[att['id']]},headers={'Idempotency-Key':key})
|
||||
key=uuid.uuid4().hex
|
||||
plain=c.message(alice,chat,'text only',key)['json']
|
||||
check(plain==c.message(alice,chat,'text only',key,[])['json'],'omitted != empty attachment_ids')
|
||||
key=uuid.uuid4().hex
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
|
||||
messages=list(pool.map(lambda _:Client().message(alice,chat,'concurrent',key,[att['id']])['json'],range(12)))
|
||||
check(len({m['id'] for m in messages})==1,'concurrent idempotency created duplicates')
|
||||
response=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)
|
||||
check(response['bytes']==payload,'download changed bytes')
|
||||
check(response['headers'].get_content_type()=='image/png','wrong download MIME')
|
||||
c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=thumbnail',404,actor=alice)
|
||||
passed.append('attachment-only, text-only, replay, concurrent replay, exact download')
|
||||
jpeg=(ROOT/'student-tests/fixtures/sample.jpg').read_bytes()
|
||||
item=upload(jpeg,201,name='valid.jpg',mime='image/jpeg')['json']
|
||||
check(c.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=bob)['bytes']==jpeg,'JPEG changed')
|
||||
passed.append('real JPEG exact download')
|
||||
save('attachments.json',{'complete':True,'passed':passed})
|
||||
print('PASS attachment validation, ACL and compatibility')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Shared operator/test helpers. Never print credentials or HTTP bodies."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT/'tests'))
|
||||
from client import Client as PublicClient, check
|
||||
|
||||
|
||||
class Client(PublicClient):
|
||||
"""Use the published IPv4 loopback by default; respect explicit targets."""
|
||||
def __init__(self, base_url=None, ca_file=None, timeout=10):
|
||||
super().__init__(base_url or os.environ.get('BASE_URL') or 'http://127.0.0.1:8080',
|
||||
ca_file=ca_file, timeout=timeout)
|
||||
|
||||
|
||||
def command(args, *, capture=True, timeout=600, input=None):
|
||||
result = subprocess.run(args, cwd=ROOT, input=input, text=True,
|
||||
encoding='utf-8', errors='replace', capture_output=capture,
|
||||
timeout=timeout)
|
||||
if result.returncode:
|
||||
# Child output may contain environment-specific details. Full command
|
||||
# does not contain secrets, but do not echo arbitrary child stderr.
|
||||
raise RuntimeError('command failed: '+str(args[0])+' (exit '+str(result.returncode)+')')
|
||||
return result.stdout.strip() if capture else None
|
||||
|
||||
|
||||
def compose(*args, **kwargs):
|
||||
return command(['docker', 'compose', *args], **kwargs)
|
||||
|
||||
|
||||
def sql(query):
|
||||
return compose('exec', '-T', 'db', 'psql', '-X', '-v', 'ON_ERROR_STOP=1',
|
||||
'-U', 'messenger', '-d', 'messenger', '-At', '-c', query)
|
||||
|
||||
|
||||
def mc(script):
|
||||
setup = ('set -eu\nmc alias set local http://s3:9000 '
|
||||
'"$(cat /run/secrets/s3_root_user)" '
|
||||
'"$(cat /run/secrets/s3_root_password)" >/dev/null\n')
|
||||
return compose('run', '--rm', '--no-deps', '-T', '--entrypoint', '/bin/sh',
|
||||
's3-init', '-c', setup+script)
|
||||
|
||||
|
||||
def reconcile(apply=False, grace=60):
|
||||
args = ['exec', '-T', 'api', '/messenger', 'reconcile', '--grace-seconds', str(grace)]
|
||||
if apply:
|
||||
args.append('--apply')
|
||||
report = json.loads(compose(*args))
|
||||
check(report['complete'], 'incomplete reconciler report')
|
||||
return report
|
||||
|
||||
|
||||
def wait_ready(base=None, seconds=90, count=1):
|
||||
deadline = time.monotonic()+seconds
|
||||
client=Client(base, timeout=2)
|
||||
observed=set()
|
||||
last_error=None
|
||||
while time.monotonic()<deadline:
|
||||
try:
|
||||
response=client.call('GET','/health/ready',schema='Health')
|
||||
observed.add(response['headers']['X-Instance-Id'])
|
||||
if len(observed)>=count:return
|
||||
except (OSError,AssertionError) as exc:
|
||||
last_error=type(exc).__name__
|
||||
observed.clear()
|
||||
time.sleep(.1)
|
||||
raise RuntimeError('stack did not become ready: expected '+str(count)+
|
||||
' distinct replicas, observed '+str(len(observed))+
|
||||
'; last probe '+(last_error or 'HTTP 200'))
|
||||
|
||||
|
||||
def save(name, data):
|
||||
(ROOT/'evidence').mkdir(exist_ok=True)
|
||||
(ROOT/'evidence'/name).write_text(json.dumps(data, ensure_ascii=False, indent=2)+'\n', encoding='utf-8')
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Sequential infrastructure faults; restores every stopped service in finally."""
|
||||
import http.client
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
from common import ROOT, Client, check, command, compose, mc, sql, wait_ready, save
|
||||
|
||||
|
||||
def inside(program, data=None):
|
||||
return command(['docker','run','--rm','-i','--network','mtusi-lab4_default',
|
||||
'--mount','type=bind,source='+str(ROOT)+',target=/workspace',
|
||||
'mtusi-messenger:lab4-tests','python','-X','utf8','-c',program],
|
||||
input=json.dumps(data) if data is not None else '')
|
||||
|
||||
|
||||
def main():
|
||||
c=Client(timeout=40)
|
||||
alice,bob,eve,chat=c.bootstrap()
|
||||
att,content=c.attachment(alice,chat)
|
||||
results=[]
|
||||
key='original/'+att['id']
|
||||
status=inside("import urllib.request,urllib.error;\ntry:\n r=urllib.request.urlopen('http://s3:9000/messenger-attachments/"+key+"');print(r.status)\nexcept urllib.error.HTTPError as e: print(e.code)")
|
||||
check(status=='403','anonymous S3 access was not denied')
|
||||
results.append('private bucket anonymous GET: 403')
|
||||
guard=inside("""import urllib.request,urllib.error
|
||||
cases=[('/messenger-attachments/original/guard-test',{'X-Amz-Content-Sha256':'STREAMING-UNSIGNED-PAYLOAD-TRAILER'},'PUT'),
|
||||
('/minio/storage/v63/rmpl',{},'POST'),('/messenger-attachments/x?select&select-type=2',{},'POST'),
|
||||
('/messenger-attachments/x',{'X-Minio-Source-Replication-Request':'true'},'PUT')]
|
||||
for path,headers,method in cases:
|
||||
try:
|
||||
response=urllib.request.urlopen(urllib.request.Request('http://s3:9000'+path,data=b'',headers=headers,method=method))
|
||||
assert response.status==403
|
||||
except urllib.error.HTTPError as e: assert e.code==403
|
||||
print('PASS')""")
|
||||
check(guard=='PASS','MinIO network guard failed')
|
||||
results.append('unsigned trailers, storage REST, S3 Select and replication headers blocked at private proxy')
|
||||
# API identity can use only this bucket/prefix, never administrative APIs.
|
||||
denied=mc('mc alias set app http://s3:9000 "$(cat /run/secrets/s3_access_key_id)" "$(cat /run/secrets/s3_secret_access_key)" >/dev/null\n'
|
||||
'if mc admin user list app >/dev/null 2>&1; then exit 10; fi\n'
|
||||
'if mc mb app/forbidden-bucket >/dev/null 2>&1; then exit 11; fi\n'
|
||||
'if printf x | mc pipe app/messenger-attachments/outside-prefix >/dev/null 2>&1; then exit 12; fi\n'
|
||||
'echo denied')
|
||||
check(denied=='denied','S3 API policy too broad')
|
||||
results.append('API account cannot administer, create bucket or write outside original/')
|
||||
# Check bootstrap twice without replacing secrets or losing bytes.
|
||||
compose('run','--rm','--no-deps','-T','s3-init')
|
||||
compose('run','--rm','--no-deps','-T','s3-init')
|
||||
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==content,'bootstrap lost original')
|
||||
results.append('idempotent bootstrap preserves data and credentials')
|
||||
try:
|
||||
compose('stop','s3')
|
||||
# Readiness removes both replicas from LB, so query internal API to
|
||||
# distinguish the application JSON error from the LB transport error.
|
||||
program='''import sys,json
|
||||
sys.path.insert(0,'tests')
|
||||
from client import Client
|
||||
x=json.load(sys.stdin);c=Client('http://api:8080',timeout=40)
|
||||
c.call('GET','/health/live',schema='Health')
|
||||
c.call('GET','/health/ready',503)
|
||||
c.call('POST','/api/v1/chats/'+x['chat']+'/attachments?filename=a.png',503,actor=x['actor'],raw=open('tests/fixtures/sample.png','rb').read(),headers={'Content-Type':'image/png'})
|
||||
c.call('GET','/api/v1/attachments/'+x['attachment']+'/content',503,actor=x['actor'])
|
||||
print('PASS')'''
|
||||
check(inside(program,{'actor':alice,'chat':chat['id'],'attachment':att['id']})=='PASS','S3 outage error mapping')
|
||||
finally:
|
||||
compose('start','s3');wait_ready()
|
||||
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==content,'S3 restart lost data')
|
||||
results.append('S3 outage: live 200, ready/upload/content 503, restart retains bytes')
|
||||
response=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=uploader.png',201,
|
||||
actor=alice,raw=content,headers={'Content-Type':'image/png'},schema='Attachment')
|
||||
uploader=response['headers']['X-Instance-Id'];uploaded=response['json']
|
||||
ids=compose('ps','-q','api').split()
|
||||
selected=[]
|
||||
for container in ids:
|
||||
hostname=command(['docker','inspect','--format','{{.Config.Hostname}}',container])
|
||||
if hostname==uploader:selected.append(container)
|
||||
check(len(selected)==1,'uploading replica did not map to exactly one container')
|
||||
try:
|
||||
command(['docker','stop','--time','9',selected[0]])
|
||||
wait_ready()
|
||||
download=c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content',actor=bob)
|
||||
check(download['bytes']==content,'replica failover changed original')
|
||||
check(download['headers']['X-Instance-Id']!=uploader,'download still used stopped uploader')
|
||||
finally:
|
||||
compose('up','-d','--no-deps','--scale','api=2','api');wait_ready()
|
||||
results.append('exact uploading container stopped; another replica returned identical original with old session')
|
||||
# An interrupted body must not reach PUT or metadata insertion.
|
||||
before=sql('SELECT count(*) FROM attachments')
|
||||
url=urllib.parse.urlsplit(c.base)
|
||||
conn=http.client.HTTPConnection(url.hostname,url.port or 80,timeout=5)
|
||||
conn.putrequest('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=abort.png')
|
||||
conn.putheader('Authorization','Bearer '+alice['token'])
|
||||
conn.putheader('Content-Type','image/png');conn.putheader('Content-Length',str(len(content)+1000));conn.endheaders()
|
||||
conn.send(content[:30]);conn.close();time.sleep(.5)
|
||||
check(sql('SELECT count(*) FROM attachments')==before,'aborted upload created metadata')
|
||||
results.append('interrupted body creates no metadata; dependency recovers')
|
||||
save('failures.json',{'complete':True,'passed':results})
|
||||
print('PASS private bucket, least privilege, bootstrap, S3 outage, aborted body')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 651 B |
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"time"
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
func main() {
|
||||
samples:=[]float64{}
|
||||
for i:=0;i<5;i++ {
|
||||
start:=time.Now()
|
||||
hash:=argon2.IDKey([]byte("synthetic-diagnostic-password"),[]byte("synthetic-salt12"),3,64*1024,1,32)
|
||||
runtime.KeepAlive(hash)
|
||||
samples=append(samples,float64(time.Since(start).Microseconds())/1000)
|
||||
debug.FreeOSMemory()
|
||||
}
|
||||
stats,_:=os.ReadFile("/sys/fs/cgroup/cpu.stat")
|
||||
json.NewEncoder(os.Stdout).Encode(map[string]any{"kdf_ms":samples,"cpu_stat":string(stats),"gomaxprocs":runtime.GOMAXPROCS(0)})
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Ten simultaneous uploads, two file sizes; sampled cgroup memory and CPU."""
|
||||
import concurrent.futures
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
import re
|
||||
import statistics
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
from common import Client, check, command, compose, save, wait_ready
|
||||
from attachments import chunk
|
||||
|
||||
|
||||
def image(side):
|
||||
rng=random.Random(104729+side)
|
||||
pixels=b''.join(b'\0'+rng.randbytes(side*3) for _ in range(side))
|
||||
return (b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!IIBBBBB',side,side,8,2,0,0,0))+
|
||||
chunk(b'IDAT',zlib.compress(pixels,1))+chunk(b'IEND',b''))
|
||||
|
||||
|
||||
def bytes_value(value):
|
||||
number,unit=re.fullmatch(r'([0-9.]+)\s*([A-Za-z]+)',value.strip()).groups()
|
||||
return round(float(number)*{'B':1,'KiB':1024,'MiB':1024**2,'GiB':1024**3,'kB':1000,'MB':1000**2,'GB':1000**3}[unit])
|
||||
|
||||
|
||||
def main():
|
||||
c=Client(timeout=40);alice,bob,eve,chat=c.bootstrap()
|
||||
ids=compose('ps','-q','api').split()
|
||||
check(len(ids)>=2,'need two API containers')
|
||||
cases=[]
|
||||
for side in (256,1536):
|
||||
compose('up','-d','--no-deps','--force-recreate','--scale','api=2','api');wait_ready(count=2)
|
||||
ids=compose('ps','-q','api').split()
|
||||
baseline_cgroup=[json.loads(command(['docker','exec',i,'/messenger','memory-snapshot'])) for i in ids]
|
||||
payload=image(side);samples=[];sampling_errors=[];stop=threading.Event();timing={}
|
||||
barrier=threading.Barrier(11,action=lambda:timing.update(start=time.monotonic()))
|
||||
def sample():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
raw=command(['docker','stats','--no-stream','--format','{{json .}}',*ids],timeout=20)
|
||||
except Exception as exc:
|
||||
sampling_errors.append(type(exc).__name__);return
|
||||
rows=[json.loads(line) for line in raw.splitlines()]
|
||||
samples.append({'t':time.monotonic(),'total_bytes':sum(bytes_value(r['MemUsage'].split('/')[0]) for r in rows),
|
||||
'containers':[{k:r[k] for k in ('Name','MemUsage','CPUPerc')} for r in rows]})
|
||||
stop.wait(.1)
|
||||
monitor=threading.Thread(target=sample,daemon=True);monitor.start()
|
||||
while not samples:
|
||||
if sampling_errors:raise RuntimeError('Docker memory sampler failed')
|
||||
time.sleep(.05)
|
||||
def upload(_):
|
||||
client=Client(timeout=40);barrier.wait(timeout=90)
|
||||
start=time.monotonic()
|
||||
result=client.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=memory.png',[201,503],
|
||||
actor=alice,raw=payload,headers={'Content-Type':'image/png'})
|
||||
return result['status'],time.monotonic()-start
|
||||
try:
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:
|
||||
pending=[pool.submit(upload,i) for i in range(10)]
|
||||
barrier.wait(timeout=90);results=[f.result() for f in pending]
|
||||
elapsed=time.monotonic()-timing['start']
|
||||
# Keep sampling after the burst to catch the next Docker sample.
|
||||
time.sleep(2)
|
||||
finally:
|
||||
stop.set();monitor.join(timeout=20)
|
||||
successes=[latency for status,latency in results if status==201]
|
||||
check(not sampling_errors,'Docker memory sampling failed')
|
||||
peaks=[json.loads(command(['docker','exec',i,'/messenger','memory-snapshot'])) for i in ids]
|
||||
check(len(successes)==10,'all ten simultaneous uploads must complete successfully')
|
||||
ordered=sorted(successes)
|
||||
percentile=lambda q:ordered[min(len(ordered)-1,max(0,math.ceil(len(ordered)*q)-1))]
|
||||
cases.append({'file_bytes':len(payload),'pixels':side*side,'concurrency':10,'requests':10,
|
||||
'success':len(successes),'backpressure_503':len(results)-len(successes),
|
||||
'error_fraction':(len(results)-len(successes))/len(results),
|
||||
'successful_rps':len(successes)/elapsed,'duration_seconds':elapsed,
|
||||
'p50_seconds':percentile(.5),'p95_seconds':percentile(.95),'p99_seconds':percentile(.99),
|
||||
'baseline_bytes':samples[0]['total_bytes'],'sampled_peak_bytes':max(x['total_bytes'] for x in samples),
|
||||
'baseline_cgroups':baseline_cgroup,'peak_cgroups':peaks,
|
||||
'sum_cgroup_peaks_bytes':sum(x['memory.peak'] for x in peaks),
|
||||
'samples':samples})
|
||||
save('upload-memory.json',{'complete':True,'method':'10 simultaneous clients, no retries; docker stats CPU/RAM plus kernel cgroup-v2 memory.peak; API cgroups recreated per case. Sum of individual peaks is an upper bound on simultaneous total peak.',
|
||||
'cases':cases})
|
||||
print('PASS 10-client memory experiment at two sizes (see upload-memory.json)')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Regression checks for private readiness probes; public client is unchanged."""
|
||||
import os
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from common import Client, wait_ready
|
||||
|
||||
|
||||
class ReadinessTests(unittest.TestCase):
|
||||
def test_local_default_matches_published_address(self):
|
||||
with patch.dict(os.environ, {}, clear=True):
|
||||
self.assertEqual(Client().base, 'http://127.0.0.1:8080')
|
||||
|
||||
def test_custom_environment_and_direct_backend_are_preserved(self):
|
||||
with patch.dict(os.environ, {'BASE_URL': 'http://test.example:8080/'}):
|
||||
self.assertEqual(Client().base, 'http://test.example:8080')
|
||||
self.assertEqual(Client('http://api:8080').base, 'http://api:8080')
|
||||
|
||||
def test_one_ready_replica_does_not_satisfy_two(self):
|
||||
with patch('common.Client') as client, patch('common.time.sleep'):
|
||||
client.return_value.call.side_effect = [
|
||||
{'headers': {'X-Instance-Id': name}}
|
||||
for name in ('one', 'one', 'two')]
|
||||
wait_ready(count=2)
|
||||
self.assertEqual(client.return_value.call.call_count, 3)
|
||||
|
||||
def test_unavailable_interval_invalidates_old_observations(self):
|
||||
with patch('common.Client') as client, patch('common.time.sleep'):
|
||||
client.return_value.call.side_effect = [
|
||||
{'headers': {'X-Instance-Id': 'old'}},
|
||||
AssertionError('not ready'),
|
||||
{'headers': {'X-Instance-Id': 'new-one'}},
|
||||
{'headers': {'X-Instance-Id': 'new-two'}}]
|
||||
wait_ready(count=2)
|
||||
self.assertEqual(client.return_value.call.call_count, 4)
|
||||
|
||||
def test_timeout_reports_missing_replica_count(self):
|
||||
with patch('common.Client') as client, patch('common.time.sleep'), \
|
||||
patch('common.time.monotonic', side_effect=[0, 0, 2]):
|
||||
client.return_value.call.return_value = {'headers': {'X-Instance-Id': 'one'}}
|
||||
with self.assertRaisesRegex(RuntimeError, 'expected 2 distinct replicas, observed 1'):
|
||||
wait_ready(count=2, seconds=1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Track 2: injected PostgreSQL/S3 faults, dry-run, repeatability and scan cost."""
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from common import ROOT, Client, check, command, compose, mc, sql, reconcile, save
|
||||
|
||||
|
||||
def objects():
|
||||
raw=mc('mc ls --json --recursive local/messenger-attachments/original/')
|
||||
# mc lists keys relative to the supplied prefix.
|
||||
return {'original/'+line['key'].removeprefix('original/') for line in
|
||||
(json.loads(x) for x in raw.splitlines() if x.strip()) if line.get('type')=='file'}
|
||||
|
||||
|
||||
def main():
|
||||
c=Client(timeout=40);alice,bob,eve,chat=c.bootstrap()
|
||||
original=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
path='/api/v1/chats/'+chat['id']+'/attachments?filename='
|
||||
used,_=c.attachment(alice,chat)
|
||||
missing,_=c.attachment(alice,chat)
|
||||
c.message(alice,chat,'referenced old attachment',attachments=[used['id'],missing['id']])
|
||||
baseline=objects()
|
||||
marker='fault_'+uuid.uuid4().hex+'.png'
|
||||
# Fault only our unique synthetic filename. No production test hooks.
|
||||
sql("CREATE FUNCTION student_reject_attachment() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='"+marker+"' THEN RAISE EXCEPTION 'injected metadata failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER student_reject_attachment BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION student_reject_attachment()")
|
||||
try:
|
||||
c.call('POST',path+marker,503,actor=alice,raw=original,headers={'Content-Type':'image/png'})
|
||||
finally:
|
||||
sql('DROP TRIGGER IF EXISTS student_reject_attachment ON attachments; DROP FUNCTION IF EXISTS student_reject_attachment()')
|
||||
orphaned=objects()-baseline
|
||||
check(len(orphaned)==1,'injected commit-side failure did not leave exactly one orphan')
|
||||
old_orphan=next(iter(orphaned))
|
||||
check(sql("SELECT count(*) FROM attachments WHERE object_key='"+old_orphan+"'")=='0','orphan has metadata')
|
||||
print('Waiting 65 seconds for the real S3 LastModified grace (no timestamp forgery).',flush=True)
|
||||
deadline=time.monotonic()+65
|
||||
while time.monotonic()<deadline:time.sleep(min(1,deadline-time.monotonic()))
|
||||
# Fresh orphan is uploaded with admin fixture tools; private, unique key.
|
||||
fresh_key='original/'+str(uuid.uuid4())
|
||||
mc("printf 'fresh-uncommitted-fixture' >/tmp/fresh; mc cp /tmp/fresh local/messenger-attachments/"+fresh_key+" >/dev/null")
|
||||
mc('mc rm local/messenger-attachments/original/'+missing['id']+' >/dev/null')
|
||||
metadata_before=sql('SELECT count(*) FROM attachments')
|
||||
before=objects()
|
||||
dry=reconcile(False)
|
||||
check(dry['old_orphans']>=1 and dry['missing']>=1,'dry-run did not detect both failure directions')
|
||||
check(objects()==before,'dry-run changed S3')
|
||||
check(sql("SELECT missing_since IS NULL FROM attachments WHERE id='"+missing['id']+"'")=='t','dry-run changed DB')
|
||||
apply=reconcile(True)
|
||||
after=objects()
|
||||
check(old_orphan not in after,'old orphan not removed')
|
||||
check(fresh_key in after,'fresh orphan was deleted')
|
||||
check('original/'+used['id'] in after,'referenced object was deleted')
|
||||
check(sql('SELECT count(*) FROM attachments')==metadata_before,'missing metadata was deleted')
|
||||
check(sql("SELECT count(*) FROM message_attachments WHERE attachment_id='"+missing['id']+"'")=='1','message reference was lost')
|
||||
c.call('GET','/api/v1/attachments/'+missing['id'],503,actor=bob)
|
||||
c.call('GET','/api/v1/attachments/'+missing['id'],404,actor=eve)
|
||||
repeat=reconcile(True)
|
||||
check(repeat['deleted']==0 and repeat['marked_unavailable']==0,'second apply is not idempotent')
|
||||
# Restore exact bytes from the fixture; only matching SHA-256 clears marker.
|
||||
# Binary stdin avoids encoding files or credential-bearing process args.
|
||||
import subprocess
|
||||
script=('set -eu\nmc alias set local http://s3:9000 "$(cat /run/secrets/s3_root_user)" '
|
||||
'"$(cat /run/secrets/s3_root_password)" >/dev/null\n'
|
||||
'cat >/tmp/original; mc cp /tmp/original local/messenger-attachments/original/'+missing['id']+' >/dev/null')
|
||||
subprocess.run(['docker','compose','run','--rm','--no-deps','-T','--entrypoint','/bin/sh','s3-init','-c',script],
|
||||
cwd=ROOT,input=original,stdout=subprocess.DEVNULL,check=True,timeout=60)
|
||||
recovered=reconcile(True)
|
||||
check(recovered['recovered']==1 and recovered['cleared_unavailable']==1,'restore not verified/repaired')
|
||||
check(c.call('GET','/api/v1/attachments/'+missing['id']+'/content',actor=bob)['bytes']==original,'restored bytes differ')
|
||||
# Reconciler while legitimate concurrent uploads commit: no live object loss.
|
||||
barrier=threading.Barrier(4)
|
||||
def upload(_):
|
||||
client=Client(timeout=40)
|
||||
barrier.wait(timeout=90)
|
||||
return client.call('POST',path+'race.png',[201,503],actor=alice,raw=original,headers={'Content-Type':'image/png'})
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
|
||||
pending=[pool.submit(upload,i) for i in range(3)]
|
||||
barrier.wait(timeout=90)
|
||||
during=reconcile(True)
|
||||
created=[json.loads(x['bytes']) for x in (f.result() for f in pending) if x['status']==201]
|
||||
for item in created:
|
||||
check(c.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=bob)['bytes']==original,'concurrent upload was deleted')
|
||||
# Two scan sizes with controlled synthetic orphans. None are eligible during
|
||||
# measurement; their cleanup is the ordinary grace-based reconciler task.
|
||||
counts=[]
|
||||
for batch in (10,100):
|
||||
keys=['original/'+str(uuid.uuid4()) for _ in range(batch)]
|
||||
mc("printf 'scan-fixture' >/tmp/scan\n"+'\n'.join("mc cp /tmp/scan local/messenger-attachments/"+k+" >/dev/null" for k in keys))
|
||||
timings=[reconcile(False) for _ in range(3)]
|
||||
counts.append({'added_objects':batch,'runs':timings})
|
||||
final=reconcile(False)
|
||||
save('research.json',{'complete':True,'track':2,'grace_seconds':60,
|
||||
'hypothesis':'Per-key locks, durable PostgreSQL rechecks and age threshold remove only old unreferenced objects; missing metadata is retained and recoverable.',
|
||||
'faults':['PostgreSQL INSERT exception after successful S3 PUT','S3 object removed after acknowledged upload'],
|
||||
'dry_run':dry,'apply':apply,'repeat_apply':repeat,'recovery':recovered,'concurrent':during,
|
||||
'fresh_orphan_protected':fresh_key in objects(),'used_original_checksum':hashlib.sha256(original).hexdigest(),
|
||||
'scan_cost':counts,'final':final})
|
||||
print('PASS Track 2: both failures, dry-run, repair, repeat, fresh/used protection and measured scan cost')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Run private Go tests in a temporary source copy; public files stay untouched."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
subprocess.run([sys.executable, '-X', 'utf8', str(ROOT/'student-tests/readiness_test.py')], cwd=ROOT, check=True)
|
||||
with tempfile.TemporaryDirectory(prefix='lab4-student-') as folder:
|
||||
target=Path(folder)
|
||||
for path in ROOT.glob('*.go'):
|
||||
shutil.copyfile(path,target/path.name)
|
||||
for name in ('go.mod','go.sum'):
|
||||
shutil.copyfile(ROOT/name,target/name)
|
||||
shutil.copytree(ROOT/'migrations',target/'migrations')
|
||||
shutil.copyfile(ROOT/'student-tests/validation_test.go',target/'validation_test.go')
|
||||
subprocess.run(['go','test','-tags','studentvalidation','-count=1','-v','./...'],cwd=target,check=True)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,121 @@
|
||||
//go:build studentvalidation
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
)
|
||||
|
||||
func TestAttachmentFilename(t *testing.T) {
|
||||
for _, name := range []string{"", " ", "../file.png", "a/b", "a\\b", "a\x00b", "a\nb", "a\x7fb", strings.Repeat("я", 256), string([]byte{255})} {
|
||||
if validFilename(name) {
|
||||
t.Fatalf("unsafe filename accepted: %q", name)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"photo.png", "Фотография 😀.jpg", strings.Repeat("я", 255)} {
|
||||
if !validFilename(name) {
|
||||
t.Fatalf("valid display name rejected: %q", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentMessageValidation(t *testing.T) {
|
||||
id := "12345678-1234-4234-8234-123456789abc"
|
||||
for _, raw := range []string{`{}`, `{"text":null}`, `{"text":" "}`, `{"text":"ok","attachment_ids":null}`, `{"text":"ok","attachment_ids":[null]}`, `{"text":"ok","attachment_ids":["invalid"]}`, `{"text":"","attachment_ids":["` + id + `","` + strings.ToUpper(id) + `"]}`} {
|
||||
var body map[string]json.RawMessage
|
||||
json.Unmarshal([]byte(raw), &body)
|
||||
if _, _, err := messageFields(body); err == nil {
|
||||
t.Fatalf("invalid message accepted: %s", raw)
|
||||
}
|
||||
}
|
||||
for _, raw := range []string{`{"text":"ok"}`, `{"text":"ok","attachment_ids":[]}`, `{"text":"","attachment_ids":["` + id + `"]}`} {
|
||||
var body map[string]json.RawMessage
|
||||
json.Unmarshal([]byte(raw), &body)
|
||||
_, ids, err := messageFields(body)
|
||||
if err != nil || ids == nil {
|
||||
t.Fatalf("valid message rejected or null IDs: %s", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUntrustedImagesRejectedBeforeStorage(t *testing.T) {
|
||||
folder := t.TempDir()
|
||||
t.Setenv("TMPDIR", folder)
|
||||
t.Setenv("TMP", folder)
|
||||
t.Setenv("TEMP", folder)
|
||||
var encoded bytes.Buffer
|
||||
png.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, 20, 10)))
|
||||
pngBytes := append([]byte(nil), encoded.Bytes()...)
|
||||
encoded.Reset()
|
||||
jpeg.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, 20, 10)), nil)
|
||||
jpegBytes := append([]byte(nil), encoded.Bytes()...)
|
||||
// Correct IHDR CRC: a valid header proves the pixel guard runs before Decode.
|
||||
huge := append([]byte(nil), pngBytes...)
|
||||
binary.BigEndian.PutUint32(huge[16:20], 40000001)
|
||||
binary.BigEndian.PutUint32(huge[20:24], 1)
|
||||
binary.BigEndian.PutUint32(huge[29:33], crc32.ChecksumIEEE(huge[12:29]))
|
||||
for _, tc := range []struct {
|
||||
name, mime string
|
||||
data []byte
|
||||
length int64
|
||||
status int
|
||||
}{
|
||||
{"empty", "image/png", nil, 0, 415},
|
||||
{"invalid bytes", "image/png", []byte("fake"), 4, 415},
|
||||
{"truncated PNG", "image/png", pngBytes[:40], 40, 415},
|
||||
{"truncated JPEG", "image/jpeg", jpegBytes[:len(jpegBytes)/2], -1, 415},
|
||||
{"spoof PNG", "image/jpeg", pngBytes, -1, 415},
|
||||
{"spoof JPEG", "image/png", jpegBytes, -1, 415},
|
||||
{"unsupported MIME", "text/plain", pngBytes, -1, 415},
|
||||
{"large header", "image/png", pngBytes, maxUploadBytes + 1, 413},
|
||||
{"chunked bytes limit", "image/png", bytes.Repeat([]byte("x"), int(maxUploadBytes+1)), -1, 413},
|
||||
{"pixel guard", "image/png", huge, -1, 413},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
app := App{uploadSlots: make(chan struct{}, 2), decodeSlot: make(chan struct{}, 1)}
|
||||
request := httptest.NewRequest("POST", "/attachments?filename=image.png", bytes.NewReader(tc.data))
|
||||
request.ContentLength = tc.length
|
||||
request.Header.Set("Content-Type", tc.mime)
|
||||
_, err := app.upload(context.Background(), httptest.NewRecorder(), request, "chat", "user")
|
||||
var failure apiError
|
||||
if !errors.As(err, &failure) || failure.status != tc.status {
|
||||
t.Fatalf("expected %d; got %v", tc.status, err)
|
||||
}
|
||||
entries, e := os.ReadDir(folder)
|
||||
if e != nil || len(entries) != 0 {
|
||||
t.Fatal("temporary upload leaked")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReconcilerDistinguishesStorageFaults(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
err error
|
||||
absent bool
|
||||
}{
|
||||
{nil, false}, {minio.ErrorResponse{Code: "NoSuchKey", StatusCode: 404}, true},
|
||||
{minio.ErrorResponse{Code: "AccessDenied", StatusCode: 403}, false},
|
||||
{minio.ErrorResponse{Code: "NoSuchBucket", StatusCode: 404}, false},
|
||||
{minio.ErrorResponse{Code: "InternalError", StatusCode: 500}, false},
|
||||
{context.DeadlineExceeded, false},
|
||||
} {
|
||||
if absentObject(tc.err) != tc.absent {
|
||||
t.Fatalf("unsafe missing inference: %v", tc.err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user