forked from mtusi2026/mtusi2026lab4
completed lab4
This commit is contained in:
Executable
+63
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Negative attachment authorization and validation checks against a running lab4 API."""
|
||||
from urllib.parse import quote, urlsplit
|
||||
from client import Client, LAB, arguments, check, run
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
import http.client, json, ssl, struct, zlib
|
||||
|
||||
def check_oversize_rejected(base_url, actor, path):
|
||||
parts=urlsplit(base_url or 'http://localhost:8080')
|
||||
conn_cls=http.client.HTTPSConnection if parts.scheme=='https' else http.client.HTTPConnection
|
||||
kwargs={'timeout':120}
|
||||
if parts.scheme=='https': kwargs['context']=ssl.create_default_context()
|
||||
conn=conn_cls(parts.hostname,parts.port,**kwargs)
|
||||
target=path
|
||||
conn.putrequest('POST',target)
|
||||
conn.putheader('Host',parts.netloc)
|
||||
conn.putheader('Accept','application/json')
|
||||
conn.putheader('Authorization','Bearer '+actor['token'])
|
||||
conn.putheader('Content-Type','image/png')
|
||||
conn.putheader('Content-Length',str(10485761))
|
||||
conn.putheader('Connection','close')
|
||||
conn.endheaders()
|
||||
response=conn.getresponse(); payload=json.loads(response.read())
|
||||
check(response.status==413,'10 MiB plus one byte was not rejected with 413')
|
||||
check(response.getheader('X-Request-Id')==payload['error']['request_id'],'oversize response request_id mismatch')
|
||||
conn.close()
|
||||
|
||||
def pixel_limit_fixture(width=6401,height=6401):
|
||||
def chunk(tag,data): return struct.pack('>I',len(data))+tag+data+struct.pack('>I',zlib.crc32(tag+data)&0xffffffff)
|
||||
encoder=zlib.compressobj(1); compressed=bytearray(); row=b'\0'+bytes(width*3)
|
||||
for _ in range(height): compressed.extend(encoder.compress(row))
|
||||
compressed.extend(encoder.flush())
|
||||
header=struct.pack('>IIBBBBB',width,height,8,2,0,0,0)
|
||||
return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',header)+chunk(b'IDAT',compressed)+chunk(b'IEND',b'')
|
||||
|
||||
def main():
|
||||
a=arguments('Attachment negative checks; creates synthetic users, chats, messages')
|
||||
check(LAB==4,'this scenario targets synchronous lab4 attachments')
|
||||
c=Client(a.base_url,a.ca_file,timeout=120); alice,bob,eve,chat=c.bootstrap()
|
||||
base='/api/v1/chats/'+chat['id']+'/attachments?filename='
|
||||
c.call('POST',base+quote('../bad.png'),400,actor=alice,raw=b'bad',headers={'Content-Type':'image/png'})
|
||||
fixture=(Path(__file__).parent/'fixtures/sample.png').read_bytes()
|
||||
for content,mime,expected,label in [(b'not an image','image/png',415,'corrupt bytes'),(fixture,'image/jpeg',415,'spoofed MIME')]:
|
||||
print('checking '+label,flush=True)
|
||||
r=c.call('POST',base+quote('bad.png'),expected,actor=alice,raw=content,headers={'Content-Type':mime})
|
||||
print('checking too large',flush=True)
|
||||
check_oversize_rejected(a.base_url,alice,base+quote('bad.png'))
|
||||
print('checking too many pixels',flush=True)
|
||||
c.call('POST',base+quote('bad.png'),413,actor=alice,raw=pixel_limit_fixture(),headers={'Content-Type':'image/png'})
|
||||
# Upload real file, then verify outsider and wrong-chat references are hidden.
|
||||
print('uploading valid image',flush=True)
|
||||
att=c.call('POST',base+quote('sample.png'),201,actor=alice,raw=fixture,headers={'Content-Type':'image/png'},schema='Attachment')['json']
|
||||
jpeg=(Path(__file__).parent/'fixtures/sample.jpg').read_bytes()
|
||||
jpeg_att=c.call('POST',base+quote('sample.jpg'),201,actor=alice,raw=jpeg,headers={'Content-Type':'image/jpeg'},schema='Attachment')['json']
|
||||
downloaded=c.call('GET','/api/v1/attachments/'+jpeg_att['id']+'/content',actor=bob)
|
||||
check(downloaded['bytes']==jpeg and jpeg_att['content_type']=='image/jpeg','real JPEG round-trip mismatch')
|
||||
c.call('GET','/api/v1/attachments/'+att['id'],404,actor=eve)
|
||||
c.call('GET','/api/v1/attachments/'+att['id']+'/content',404,actor=eve)
|
||||
other=c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Другой чат','member_ids':[alice['id'],bob['id']]},schema='Chat')['json']
|
||||
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=bob,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid4().hex})
|
||||
print('PASS: real PNG/JPEG, pixel/byte limits, corrupt image, MIME spoof, outsider access, and cross-chat binding checked')
|
||||
if __name__=='__main__': run(main)
|
||||
+3
-1
@@ -122,7 +122,9 @@ class Client:
|
||||
response = error
|
||||
except (urllib.error.URLError,TimeoutError,OSError) as exc:
|
||||
# Do not print URL query, headers, request body, or credentials.
|
||||
raise Failure(method + ' ' + path.split('?')[0] + ': connection/TLS failure (' + type(exc).__name__ + ')') from None
|
||||
reason=getattr(exc,'reason',None)
|
||||
reason_type=type(reason).__name__ if reason is not None else type(exc).__name__
|
||||
raise Failure(method + ' ' + path.split('?')[0] + ': connection/TLS failure (' + reason_type + ')') from None
|
||||
with response:
|
||||
status = response.code
|
||||
rh = response.headers
|
||||
|
||||
Vendored
+2
@@ -6,4 +6,6 @@ sample.png: RGB PNG 320×200, создан программно специаль
|
||||
- SHA-256: `99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75`.
|
||||
- Обязательный thumbnail с lab5: JPEG 256×160.
|
||||
|
||||
`sample.jpg` — JPEG 320×200, полученный преобразованием этой же синтетической картинки; SHA-256: `88585921771cc8ab0afac847728ab899c418c92d8d5ee2cdfeeda8b84a3c61de`. Он нужен для проверки реального JPEG upload/download в lab4.
|
||||
|
||||
Проверяющий читает SHA-256 оригинала, metadata вариантов и реальные размеры JPEG, а не только JSON-обещание сервера. Повреждённые, oversized и decompression-bomb fixtures для собственного negative suite создавайте отдельно; не храните огромные файлы в Git.
|
||||
|
||||
Vendored
BIN
Binary file not shown.
|
After Width: | Height: | Size: 8.3 KiB |
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stop RustFS briefly; confirm upload fails cleanly without DB metadata and recover it."""
|
||||
import subprocess, sys, time
|
||||
from pathlib import Path
|
||||
from client import Client, LAB, arguments, check, run
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
def compose(*args): subprocess.run(['docker','compose',*args],cwd=ROOT,check=True,stdout=subprocess.DEVNULL)
|
||||
def attachment_count():
|
||||
code="from app.main import pool\nwith pool.connection() as c: print(c.execute('SELECT count(*) AS n FROM attachments').fetchone()['n'])"
|
||||
# A dedicated short-lived process reads the count; no values other than the integer are emitted.
|
||||
out=subprocess.run(['docker','compose','exec','-T','api','python','-c',code],cwd=ROOT,check=True,capture_output=True,text=True).stdout.strip()
|
||||
return int(out.splitlines()[-1])
|
||||
def main():
|
||||
a=arguments('RustFS outage check; briefly stops the local RustFS service')
|
||||
check(LAB==4,'scenario targets lab4')
|
||||
c=Client(a.base_url,a.ca_file,timeout=10); alice,bob,eve,chat=c.bootstrap()
|
||||
raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
before=attachment_count(); stopped=False
|
||||
try:
|
||||
compose('stop','rustfs'); stopped=True
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=outage.png',503,actor=alice,raw=raw,headers={'Content-Type':'image/png'})
|
||||
finally:
|
||||
if stopped: compose('start','rustfs')
|
||||
deadline=time.monotonic()+60
|
||||
while True:
|
||||
try:
|
||||
c.call('GET','/health/ready')
|
||||
break
|
||||
except Exception:
|
||||
check(time.monotonic()<deadline,'RustFS/API did not recover within 60 seconds')
|
||||
time.sleep(.5)
|
||||
after=attachment_count()
|
||||
check(after==before,'failed S3 upload left attachment metadata behind')
|
||||
print('PASS: S3 outage returned 503; no attachment metadata persisted; RustFS recovered')
|
||||
if __name__=='__main__': run(main)
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""10-way bounded-memory image upload experiment; output contains no credentials."""
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
import hashlib, json, math, os, pty, random, re, struct, subprocess, threading, time, zlib
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from client import Client, LAB, arguments, check, run
|
||||
|
||||
def png_noise(width, height, seed):
|
||||
rng=random.Random(seed); raw=bytearray()
|
||||
for _ in range(height): raw.append(0); raw.extend(rng.randbytes(width*3))
|
||||
def chunk(tag,data): return struct.pack('>I',len(data))+tag+data+struct.pack('>I',zlib.crc32(tag+data)&0xffffffff)
|
||||
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(bytes(raw),1))+chunk(b'IEND',b'')
|
||||
|
||||
STATS_RE=re.compile(r'(mtusi_lab4_solution-api-[^|\s]+)\|([\d.]+)(GiB|MiB|KiB|B) / [^|\s]+\|([\d.]+)%')
|
||||
def parse_stats_text(text):
|
||||
vals={}
|
||||
for name,number,unit,cpu in STATS_RE.findall(text):
|
||||
scale={'GiB':1024,'MiB':1,'KiB':1/1024,'B':1/(1024*1024)}[unit]
|
||||
vals[name]={'memory_mib':float(number)*scale,'cpu_percent':float(cpu)}
|
||||
return vals
|
||||
|
||||
def main():
|
||||
a=arguments('Synthetic image upload experiment with sampled Docker API memory')
|
||||
check(LAB==4,'experiment targets synchronous lab4 uploads')
|
||||
c=Client(a.base_url,a.ca_file,timeout=30); alice,bob,eve,chat=c.bootstrap()
|
||||
profiles=[('small',512,512),('large',2048,1536)]
|
||||
result={'date_utc':datetime.now(timezone.utc).isoformat(),'concurrency':10,'profiles':[],'method':'10 workers start together; small profile repeats 10 times per worker and large 3 times; same generated PNG payload per profile; Docker stats streamed in a pseudo-terminal at Docker default cadence (~1s); no retries'}
|
||||
for name,w,h in profiles:
|
||||
repetitions=10 if name=='small' else 3
|
||||
payload=png_noise(w,h,20261106+w)
|
||||
barrier=threading.Barrier(10); samples=[]; stop=threading.Event()
|
||||
master,slave=pty.openpty()
|
||||
monitor_process=subprocess.Popen(['docker','stats','--format','{{.Name}}|{{.MemUsage}}|{{.CPUPerc}}'],stdin=slave,stdout=slave,stderr=slave,close_fds=True)
|
||||
os.close(slave)
|
||||
def monitor():
|
||||
buf=''
|
||||
while not stop.is_set():
|
||||
try: chunk=os.read(master,8192)
|
||||
except OSError: break
|
||||
if not chunk: break
|
||||
buf=(buf+chunk.decode('utf-8','ignore'))[-16384:]
|
||||
point=parse_stats_text(buf)
|
||||
if point: samples.append(point)
|
||||
mt=threading.Thread(target=monitor,daemon=True); mt.start()
|
||||
def upload(i):
|
||||
local=Client(a.base_url,a.ca_file,timeout=30); barrier.wait(); time.sleep(.2); out=[]
|
||||
for j in range(repetitions):
|
||||
t=time.monotonic()
|
||||
try:
|
||||
local.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename='+name+'-'+str(i)+'-'+str(j)+'.png',201,actor=alice,raw=payload,headers={'Content-Type':'image/png'},schema='Attachment')
|
||||
out.append({'ok':True,'latency_ms':(time.monotonic()-t)*1000})
|
||||
except Exception as e:
|
||||
out.append({'ok':False,'error_type':type(e).__name__,'latency_ms':(time.monotonic()-t)*1000})
|
||||
return out
|
||||
started=time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=10) as pool: items=[item for group in pool.map(upload,range(10)) for item in group]
|
||||
elapsed=time.monotonic()-started; stop.set(); monitor_process.terminate(); monitor_process.wait(timeout=3); mt.join(timeout=3); os.close(master)
|
||||
lat=sorted(x['latency_ms'] for x in items if x['ok'])
|
||||
peak={}
|
||||
for snap in samples:
|
||||
for service,m in snap.items(): peak[service]=max(peak.get(service,0),m['memory_mib'])
|
||||
def pct(p): return round(lat[max(0,math.ceil(p*len(lat))-1)],2) if lat else None
|
||||
result['profiles'].append({'name':name,'dimensions':[w,h],'pixels':w*h,'payload_bytes':len(payload),'sha256':hashlib.sha256(payload).hexdigest(),'uploads_per_worker':repetitions,'successes':sum(x['ok'] for x in items),'failures':sum(not x['ok'] for x in items),'elapsed_seconds':round(elapsed,3),'successful_rps':round(sum(x['ok'] for x in items)/elapsed,3),'latency_ms':{'p50':pct(.50),'p95':pct(.95),'p99':pct(.99)},'api_peak_memory_mib_sampled':peak,'sampling_interval_seconds':1,'sample_count':len(samples)})
|
||||
dest=Path('evidence/upload-load.json'); dest.parent.mkdir(parents=True,exist_ok=True); dest.write_text(json.dumps(result,indent=2)+'\n')
|
||||
print(json.dumps(result,indent=2))
|
||||
check(all(x['failures']==0 and x['successes']==10*x['uploads_per_worker'] for x in result['profiles']),'one or more uploads failed')
|
||||
if __name__=='__main__': run(main)
|
||||
Reference in New Issue
Block a user