Лабораторная 4: S3-хранилище и вложения

This commit is contained in:
Алиса Шурман
2026-11-12 22:27:32 +03:00
parent ec540a1a72
commit 7fbdef3a6a
25 changed files with 1447 additions and 23 deletions
+57
View File
@@ -0,0 +1,57 @@
"""Start ten simultaneous uploads; record actual container RSS via /proc."""
from concurrent.futures import ThreadPoolExecutor
import json
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client, check
from PIL import Image
import io
c=Client(timeout=45)
a,b,e,chat=c.bootstrap()
file=io.BytesIO()
# Incompressible ~9 MiB RGB PNG rather than ten tiny fixtures.
Image.frombytes('RGB',(1750,1750),os.urandom(1750*1750*3)).save(file,'PNG')
data=file.getvalue()
check(len(data)<=10485760,'fixture too large')
barrier=threading.Barrier(10)
finished=threading.Event()
samples=[]
def rss():
while not finished.is_set():
row={'seconds':round(time.monotonic()-start,3)}
for name in ['api1','api2']:
result=subprocess.run(['docker','compose','exec','-T',name,'python','-c',
"from pathlib import Path; print(next(x.split()[1] for x in Path('/proc/1/status').read_text().splitlines() if x.startswith('VmRSS:')))"] ,capture_output=True,text=True,check=True)
row[name+'_rss_kib']=int(result.stdout.strip())
samples.append(row)
finished.wait(0.1)
def upload(i):
barrier.wait()
response=Client(timeout=45).call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=load.png',
[201,503],actor=a,raw=data,headers={'Content-Type':'image/png'})
return {'status':response['status'],'seconds':round(response['elapsed'],3)}
start=time.monotonic()
with ThreadPoolExecutor(max_workers=1) as monitor:
future=monitor.submit(rss)
try:
with ThreadPoolExecutor(max_workers=10) as pool:
results=list(pool.map(upload,range(10)))
finally:
finished.set()
future.result()
check(samples,'no memory measurements')
report={'concurrency':10,'file_bytes':len(data),'results':results,'samples':samples,
'peak_rss_kib':{n:max(s[n+'_rss_kib'] for s in samples) for n in ['api1','api2']},
'sampling_note':'Sequential /proc sampling; very brief peaks may be missed. 503 is explicit admission control.'}
Path('evidence/memory.json').write_text(json.dumps(report,indent=2))
check(any(r['status']==201 for r in results),'no upload succeeded')
print(json.dumps({k:v for k,v in report.items() if k!='samples'},indent=2))
+66
View File
@@ -0,0 +1,66 @@
"""Exercise interrupted HTTP upload and unavailable S3 on this Compose project."""
import http.client
import json
import os
from pathlib import Path
import subprocess
import sys
import time
from urllib.parse import urlsplit
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client, check
c=Client(timeout=45)
a,b,e,chat=c.bootstrap()
att,png=c.attachment(a,chat)
base=urlsplit(c.base)
check(base.hostname in ('localhost','127.0.0.1'),'test is limited to the local lab')
# Close while the body is incomplete. No intent should be created before validation.
connection=http.client.HTTPConnection(base.hostname,base.port,timeout=5)
connection.putrequest('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=interrupted.png')
connection.putheader('Authorization','Bearer '+a['token'])
connection.putheader('Content-Type','image/png')
connection.putheader('Content-Length',str(len(png)))
connection.endheaders()
connection.send(png[:16])
connection.close()
# Query only the synthetic chat through stdin; credentials/tokens are never printed.
probe="""
import sys
sys.path.insert(0,'/srv/app')
import psycopg,storage
with psycopg.connect(storage.secret('DATABASE_URL')) as db:
n=db.execute("SELECT count(*) FROM attachments WHERE chat_id=%s", (CHAT,)).fetchone()[0]
assert n==1, 'interrupted upload created metadata'
print('PASS: interrupted upload did not create an attachment')
""".replace('CHAT',repr(chat['id']))
subprocess.run(['docker','compose','exec','-T','api1','python','-'],input=probe,text=True,check=True)
# Direct request within api1 ensures the API's structured 503 is tested,
# independently of HAProxy taking all unready instances out of rotation.
probe="""
import urllib.request,urllib.error
req=urllib.request.Request('http://localhost:8080/api/v1/attachments/ATT/content',headers={'Authorization':'Bearer TOKEN'})
try:
urllib.request.urlopen(req,timeout=20)
raise AssertionError('unavailable S3 returned success')
except urllib.error.HTTPError as error:
assert error.code==503, error.code
print('PASS: unavailable S3 returns 503 from API')
""".replace('ATT',att['id']).replace('TOKEN',a['token'])
try:
subprocess.run(['docker','compose','stop','s3'],check=True)
subprocess.run(['docker','compose','exec','-T','api1','python','-'],input=probe,text=True,check=True)
finally:
subprocess.run(['docker','compose','up','-d','--wait','s3'],check=True)
for attempt in range(30):
try:
result=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)
check(result['bytes']==png,'recovered file differs')
break
except AssertionError:
if attempt==29:
raise
time.sleep(1)
print('PASS: S3 recovery preserves the original bytes')
+60
View File
@@ -0,0 +1,60 @@
"""Run inside the API container: private bucket and cleanup failure recovery."""
import io
import json
from pathlib import Path
import sys
import uuid
import urllib.request
import urllib.error
sys.path.insert(0, '/srv/app')
import psycopg
import storage
from cleanup import sweep
prefix = uuid.uuid4().hex
ids = [str(uuid.uuid4()) for _ in range(3)]
keys = ['originals/'+i for i in ids]
user,chat = str(uuid.uuid4()),str(uuid.uuid4())
dsn=storage.secret('DATABASE_URL')
# Model a process stopping after S3 PUT but before final DB COMMIT.
# Also create a fresh intent and an old ready file; neither may be removed.
try:
with psycopg.connect(dsn) as db:
db.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)',
(user,'cleanup_'+prefix[:12],'Synthetic cleanup','not-a-login-hash'))
db.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (chat,'Synthetic cleanup'))
for i,(aid,key) in enumerate(zip(ids,keys)):
db.execute("""INSERT INTO attachments(id,chat_id,owner_id,filename,object_key,content_type,size_bytes,sha256,status,created_at)
VALUES (%s,%s,%s,'test.png',%s,'image/png',3,%s,%s,clock_timestamp()-%s*interval '1 hour')""",
(aid,chat,user,key,'0'*64,'ready' if i==2 else 'pending',2 if i!=1 else 0))
for key in keys:
storage.client.put_object(Bucket=storage.BUCKET,Key=key,Body=b'abc')
try:
urllib.request.urlopen('http://s3:9000/'+storage.BUCKET+'/'+keys[2],timeout=5)
raise AssertionError('Anonymous object access allowed')
except urllib.error.HTTPError as error:
assert error.code==403, error.code
# Roll back a simulated failed finalization; durable pending intent remains.
with psycopg.connect(dsn) as db:
db.execute("UPDATE attachments SET status='ready' WHERE id=%s", (ids[0],))
db.rollback()
sweep()
sweep() # Idempotent after completion.
with psycopg.connect(dsn) as db:
remaining={str(r[0]) for r in db.execute('SELECT id FROM attachments WHERE id=ANY(%s::uuid[])',(ids,))}
assert remaining==set(ids[1:]), remaining
try:
storage.client.head_object(Bucket=storage.BUCKET,Key=keys[0])
raise AssertionError('Abandoned object still exists')
except storage.ClientError as error:
assert error.response['ResponseMetadata']['HTTPStatusCode']==404
for key in keys[1:]:
storage.client.head_object(Bucket=storage.BUCKET,Key=key)
print('PASS: private bucket, failed finalization recovery, grace period, ready protection, repeated cleanup')
finally:
for key in keys:
storage.client.delete_object(Bucket=storage.BUCKET,Key=key)
with psycopg.connect(dsn) as db:
db.execute('DELETE FROM attachments WHERE id=ANY(%s::uuid[])',(ids,))
db.execute('DELETE FROM chats WHERE id=%s',(chat,))
db.execute('DELETE FROM users WHERE id=%s',(user,))
+50
View File
@@ -0,0 +1,50 @@
"""Offline checks of image content, size limits, and MIME detection."""
import io
from pathlib import Path
import struct
import sys
import unittest
import zlib
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'app'))
from PIL import Image
from images import validate_image, InvalidImage, TooManyPixels
class Images(unittest.TestCase):
def picture(self, fmt):
file = io.BytesIO()
Image.new('RGB', (320, 200), (20, 30, 40)).save(file, fmt)
file.seek(0)
return file
def test_png_and_jpeg(self):
for fmt, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]:
file = self.picture(fmt)
before = file.getvalue()
validate_image(file, mime)
self.assertEqual(file.tell(), 0)
self.assertEqual(file.read(), before)
def test_mime_substitution(self):
with self.assertRaises(InvalidImage):
validate_image(self.picture('PNG'), 'image/jpeg')
def test_not_image(self):
for content in [b'', b'hello', b'<script>alert(1)</script>']:
with self.assertRaises(InvalidImage):
validate_image(io.BytesIO(content), 'image/png')
def test_truncated_pixels(self):
file = self.picture('JPEG')
with self.assertRaises(InvalidImage):
validate_image(io.BytesIO(file.getvalue()[:-20]), 'image/jpeg')
def test_pixel_limit_before_decode(self):
def chunk(kind, data):
return struct.pack('>I', len(data))+kind+data+struct.pack('>I', zlib.crc32(kind+data)&0xffffffff)
huge = b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB', 8000,8000,8,2,0,0,0))
huge += chunk(b'IDAT', zlib.compress(b'\x00'))+chunk(b'IEND', b'')
with self.assertRaises(TooManyPixels):
validate_image(io.BytesIO(huge), 'image/png')
if __name__ == '__main__':
unittest.main(verbosity=2)
+46
View File
@@ -0,0 +1,46 @@
"""Black-box grade-4 checks; creates only synthetic data on the local lab."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
from pathlib import Path
import sys
import threading
import uuid
from urllib.parse import quote
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client, check
c = Client(timeout=45)
a,b,e,chat = c.bootstrap()
base = '/api/v1/chats/' + chat['id']
att, png = c.attachment(a, chat)
for name in ['../x.png', 'a\\b.png', '\x00.png', '\n.png']:
c.call('POST', base+'/attachments?filename='+quote(name, safe=''), 400, actor=a,
raw=png, headers={'Content-Type':'image/png'})
for data,mime,status in [(b'x'*(10485760+1),'image/png',413),
(b'not an image','image/png',415), (png,'image/jpeg',415),
(png[:20],'image/png',415)]:
c.call('POST', base+'/attachments?filename=x.png', status, actor=a,
raw=data, headers={'Content-Type':mime})
other = c.call('POST','/api/v1/chats',201,actor=a,
body={'title':'Other chat','member_ids':[a['id']]},schema='Chat')['json']
for target,ids,actor in [(other,[att['id']],a), (chat,[str(uuid.uuid4())],a), (chat,[att['id']],e)]:
c.call('POST','/api/v1/chats/'+target['id']+'/messages',404,actor=actor,
body={'text':'','attachment_ids':ids},headers={'Idempotency-Key':uuid.uuid4().hex})
for suffix in ['', '/content']:
c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=e)
# A member other than the uploader can attach and download the same file.
c.message(b, chat, '', attachments=[att['id']])
key = uuid.uuid4().hex
barrier = threading.Barrier(10)
def replay(_):
barrier.wait()
return Client(timeout=45).message(a,chat,'one logical message',key=key)['json']
with ThreadPoolExecutor(max_workers=10) as pool:
messages = list(pool.map(replay,range(10)))
check(all(m == messages[0] for m in messages), 'concurrent replay duplicated messages')
c.call('POST',base+'/messages',409,actor=a,body={'text':'different'},headers={'Idempotency-Key':key})
# Default [] and explicit [] are equivalent.
c.call('POST',base+'/messages',201,actor=a,body={'text':'one logical message','attachment_ids':[]},
headers={'Idempotency-Key':key},schema='Message')
print('PASS: invalid files, ACL, cross-chat references, concurrent idempotency')