Выполнить лабораторную 5: асинхронный pipeline и исследование идемпотентности

This commit is contained in:
wpyatzy
2026-11-20 18:47:23 +03:00
parent 276dbdad8a
commit ec277e7e64
72 changed files with 6521 additions and 27 deletions
+40
View File
@@ -0,0 +1,40 @@
"""Real broker outage and bounded admission, followed by complete recovery."""
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
import time
from lifecycle import compose,probe
from client import Client,check
def main():
c=Client('http://localhost:8085');started=time.monotonic()
try:
compose('stop','worker','publisher','broker')
alice,bob,eve,chat=c.bootstrap()
# Default deployment admits at most 100 pending logical jobs across APIs.
def upload(_):return Client(c.base).attachment(alice,chat)
with ThreadPoolExecutor(max_workers=8) as pool:accepted=list(pool.map(upload,range(100)))
fixture=accepted[0][1]
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=full.png',429,actor=alice,raw=fixture,headers={'Content-Type':'image/png'})
c.message(alice,chat,'messages remain writable while image queue is full')
for att,_ in (accepted[0],accepted[-1]):
c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=bob)
admitted_seconds=time.monotonic()-started
# Every 202 was accepted while the broker was genuinely stopped.
state=probe(accepted[0][0]['id'])
check(state['published_at'] is None and state['state']=='queued','upload depended on unavailable broker')
compose('start','broker','publisher','worker');recovery=time.monotonic()
for att,data in accepted:
ready=c.wait_ready(bob,att,wait_seconds=120)
check(len(ready['variants'])==3 and ready['sha256']==hashlib.sha256(data).hexdigest(),'recovery lost accepted metadata')
for att,data in (accepted[0],accepted[-1]):
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==data,'recovery lost original bytes')
print(json.dumps({'status':'PASS','accepted_while_broker_down':len(accepted),'next_upload_status':429,
'messages_available':True,'all_ready':len(accepted),'admission_seconds':round(admitted_seconds,3),
'drain_seconds':round(time.monotonic()-recovery,3),'lost_accepted':0,
'profile':'100 PNG 320x200, 8 upload clients, 1 serial worker; closed-loop; not a throughput benchmark'},indent=2))
finally:compose('start','broker','publisher','worker')
if __name__=='__main__':main()
+157
View File
@@ -0,0 +1,157 @@
#!/usr/bin/env python3
"""Research track: cache consistency and stale session protection for Valkey-backed sessions."""
import base64
import json
import os
import statistics
import time
import urllib.error
import urllib.request
import uuid
from concurrent.futures import ThreadPoolExecutor
BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
CACHER_URL = os.environ.get("CACHE_URL", "redis://localhost:6379/0")
def http_json(method, path, *, expected=200, headers=None, body=None):
req_headers = {"Accept": "application/json"}
if headers:
req_headers.update(headers)
data = None if body is None else json.dumps(body, ensure_ascii=False).encode("utf-8")
if data is not None:
req_headers.setdefault("Content-Type", "application/json")
request = urllib.request.Request(BASE_URL + path, data=data, headers=req_headers, method=method)
try:
with urllib.request.urlopen(request, timeout=10) as resp:
payload = resp.read()
if not payload:
return {"status": resp.status, "headers": dict(resp.headers), "body": None}
if resp.status not in (expected if isinstance(expected, (list, tuple, set)) else [expected]):
raise AssertionError(f"Expected {expected}, got {resp.status}")
return {"status": resp.status, "headers": dict(resp.headers), "body": json.loads(payload.decode("utf-8"))}
except urllib.error.HTTPError as exc:
payload = exc.read()
if payload:
try:
payload = json.loads(payload.decode("utf-8"))
except Exception:
payload = payload.decode("utf-8", errors="replace")
if exc.code not in (expected if isinstance(expected, (list, tuple, set)) else [expected]):
raise AssertionError(f"Expected status {expected}, got {exc.code} for {method} {path}: {payload}")
return {"status": exc.code, "headers": dict(exc.headers), "body": payload}
def call_with_latency(method, path, *, expected=200, headers=None, body=None):
start = time.perf_counter()
result = http_json(method, path, expected=expected, headers=headers, body=body)
elapsed_ms = (time.perf_counter() - start) * 1000.0
return result, elapsed_ms
def main():
import redis
r = redis.Redis.from_url(CACHER_URL, decode_responses=True, socket_connect_timeout=2, socket_timeout=2)
username = f"cache_{uuid.uuid4().hex[:12]}"
password = "123456789012"
body = {
"username": username,
"display_name": "Cache Consistency",
"password": password,
}
registration = http_json("POST", "/api/v1/users", expected=201, body=body)
assert registration["status"] == 201, registration
basic = "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()
session = http_json("POST", "/api/v1/auth/sessions", expected=201, headers={"Authorization": basic})
token = session["body"]["token"]
assert token, session
key = f"session:{token}"
assert r.get(key), "session was not populated in Valkey"
ttl = r.ttl(key)
assert ttl and ttl > 0, f"session TTL must be positive, got {ttl}"
latencies = []
for _ in range(10):
_, elapsed_ms = call_with_latency("GET", "/api/v1/users/me", expected=200, headers={"Authorization": "Bearer " + token})
latencies.append(elapsed_ms)
avg = sum(latencies) / len(latencies)
p95 = sorted(latencies)[int(len(latencies) * 0.95) - 1]
stale_payload = {
"token": token,
"user_id": str(uuid.uuid4()),
"expires_at": "2000-01-01T00:00:00Z",
"revoked_at": None,
"user": {"id": str(uuid.uuid4()), "username": "stale", "display_name": "stale", "created_at": "2020-01-01T00:00:00Z"},
}
r.setex(key, 120, json.dumps(stale_payload, separators=(",", ":"), ensure_ascii=False))
stale_result = http_json("GET", "/api/v1/users/me", expected=200, headers={"Authorization": "Bearer " + token})
assert stale_result["status"] == 200, stale_result
assert stale_result["body"]["username"] == username, stale_result
# An unexpired payload must not be able to substitute another identity.
stale_payload["expires_at"] = "2100-01-01T00:00:00Z"
r.setex(key, 120, json.dumps(stale_payload))
forged = http_json("GET", "/api/v1/users/me", headers={"Authorization": "Bearer " + token})
assert forged["body"]["id"] == session["body"]["user"]["id"], forged
assert forged["body"]["username"] == username, forged
r.setex(key, 120, json.dumps(stale_payload))
def read_identity(_):
return http_json("GET", "/api/v1/users/me", headers={"Authorization": "Bearer " + token})["body"]["id"]
with ThreadPoolExecutor(max_workers=8) as executor:
identities = list(executor.map(read_identity, range(8)))
assert identities == [session["body"]["user"]["id"]] * 8, identities
# Syntactically valid JSON with missing fields must be treated as a miss.
r.setex(key, 120, "{}")
malformed = http_json("GET", "/api/v1/users/me", headers={"Authorization": "Bearer " + token})
assert malformed["body"]["username"] == username, malformed
r.setex(key, 1, json.dumps({
"token": token,
"user_id": str(uuid.uuid4()),
"expires_at": "2100-01-01T00:00:00Z",
"revoked_at": None,
"user": {"id": str(uuid.uuid4()), "username": "ttl-recovery", "display_name": "ttl-recovery", "created_at": "2020-01-01T00:00:00Z"},
}, separators=(",", ":"), ensure_ascii=False))
time.sleep(2)
short_ttl = http_json("GET", "/api/v1/users/me", expected=200, headers={"Authorization": "Bearer " + token})
assert short_ttl["status"] == 200, short_ttl
assert short_ttl["body"]["username"] == username, short_ttl
revoke = http_json("DELETE", "/api/v1/auth/sessions/current", expected=204, headers={"Authorization": "Bearer " + token})
assert revoke["status"] == 204, revoke
assert not r.get(key), "revoked session key should be deleted from cache"
after_logout = http_json("GET", "/api/v1/users/me", expected=401, headers={"Authorization": "Bearer " + token})
assert after_logout["status"] == 401, after_logout
# Simulate a writer repopulating the cache after logout's DELETE.
stale_payload.update(session["body"])
stale_payload["user_id"] = session["body"]["user"]["id"]
stale_payload["revoked_at"] = None
r.setex(key, 120, json.dumps(stale_payload))
http_json("GET", "/api/v1/users/me", expected=401, headers={"Authorization": "Bearer " + token})
assert not r.exists(key), "stale key after logout must be removed"
print("cache_key_exists=True")
print(f"ttl_seconds={ttl}")
print(f"avg_latency_ms={avg:.2f}")
print(f"p95_latency_ms={p95:.2f}")
print("stale_cache_rejected=True")
print("forged_identity_rejected=True")
print("concurrent_identity_checks=8/8")
print("malformed_cache_recovers=True")
print("repopulated_revoked_cache_rejected=True")
print("short_ttl_recovers_from_db=True")
print("logout_revokes_cache=True")
if __name__ == "__main__":
main()
+75
View File
@@ -0,0 +1,75 @@
"""Conservative cleanup and actual subprocess timeout boundary; worker stopped."""
from datetime import datetime,timedelta,timezone
import json
from pathlib import Path
import subprocess
import sys
import time
import unittest.mock as mock
import uuid
sys.path.insert(0,str(Path(__file__).resolve().parent))
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from client import Client,check
from app import store,object_store
from pipeline import envelope,fetch_job,replay
from worker import handle
from janitor import sweep
def main():
store.pool.open(wait=True,timeout=20)
c=Client('http://lb:8080');alice,bob,eve,chat=c.bootstrap()
def upload():
att,data=c.attachment(alice,chat)
with store.connect() as conn:
jid=conn.execute('SELECT id FROM jobs WHERE attachment_id=%s',(att['id'],)).fetchone()[0]
msg=envelope(fetch_job(conn,jid))
return att,msg
rows=[]
try:
att,msg=upload()
real_run=subprocess.run
def slow_decoder(*args,**kwargs):
return real_run([sys.executable,'-c','import time; time.sleep(2)'],timeout=.05,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
start=time.monotonic()
with mock.patch('worker.subprocess.run',side_effect=slow_decoder):
check(handle(msg)=='retry','decoder timeout not classified as transient')
elapsed=time.monotonic()-start
with store.connect() as conn:
job=fetch_job(conn,msg['job_id']);check(job['state']=='queued' and job['error_code']=='processing_timeout','timeout not persisted')
conn.execute('UPDATE jobs SET next_at=now() WHERE id=%s',(job['id'],))
check(handle(msg)=='ready','timeout recovery failed')
rows.append(dict(case='real_child_timeout_with_test_budget_50ms',status='PASS',elapsed_ms=round(elapsed*1000,3)))
# Validate memory-exit classification without risking an OOM on the host.
att2,msg2=upload()
def exhausted(*args,**kwargs):
return real_run([sys.executable,'-c',"import resource; resource.setrlimit(resource.RLIMIT_AS,(32*1024**2,32*1024**2));\ntry: x=bytearray(128*1024**2)\nexcept MemoryError: raise SystemExit(3)"],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
with mock.patch('worker.subprocess.run',side_effect=exhausted):
check(handle(msg2)=='failed','memory failure not terminal')
with store.connect() as conn:check(fetch_job(conn,msg2['job_id'])['error_code']=='resource_limit','memory failure leaked details')
replay(store,msg2['job_id']);check(handle(msg2)=='ready','memory-failed replay did not complete')
rows.append(dict(case='real_child_address_space_limit_32MiB',status='PASS',error_code='resource_limit'))
active,msg3=upload()
orphan='staging/'+str(uuid.uuid4())
object_store.client.put_object(Bucket=object_store.bucket,Key=orphan,Body=b'orphan')
# Advance janitor's clock, leaving actual DB state/worker leases intact.
class Future(datetime):
@classmethod
def now(cls,tz=None):return datetime.now(tz)+timedelta(days=2)
with mock.patch('janitor.datetime',Future):
dry=sweep(False,86400)
check(orphan in dry['staging_candidates'],'orphan not detected')
check('staging/'+active['id'] not in dry['staging_candidates'],'active source scheduled for deletion')
object_store.client.head_object(Bucket=object_store.bucket,Key=orphan)
applied=sweep(True,86400)
check(orphan in applied['staging_candidates'],'orphan not deleted')
repeat=sweep(True,86400)
check(not repeat['staging_candidates'],'cleanup is not idempotent')
check(handle(msg3)=='ready','cleanup lost current job')
rows.append(dict(case='staging_dry_run_apply_repeat',status='PASS',candidates=len(applied['staging_candidates']),
repeat_candidates=0,active_retained=True,clock='advanced_2_days'))
print(json.dumps({'status':'PASS','rows':rows},indent=2))
finally:store.pool.close();object_store.close()
if __name__=='__main__':main()
+35
View File
@@ -0,0 +1,35 @@
"""Isolated crashable consumer using a real Streams consumer-group delivery."""
import argparse
import json
from pathlib import Path
import sys
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from app import store
from pipeline import broker,envelope,fetch_job,STREAM
from worker import handle
import redis
p=argparse.ArgumentParser();p.add_argument('job_id');p.add_argument('--crash',choices=['before_effect','after_effect','after_commit']);p.add_argument('--recover',action='store_true');args=p.parse_args()
store.pool.open(wait=True,timeout=20)
r=broker();group='fault-probes'
try:
try:r.xgroup_create(STREAM,group,id='$',mkstream=True)
except redis.ResponseError as exc:
if 'BUSYGROUP' not in str(exc):raise
with store.connect() as db:msg=envelope(fetch_job(db,args.job_id))
if args.recover:
entries=r.xautoclaim(STREAM,group,'recovered',min_idle_time=0,start_id='0-0',count=100)[1]
target=next(((mid,fields) for mid,fields in entries if json.loads(fields['job'])['job_id']==args.job_id),None)
if target is None:raise AssertionError('expected unacknowledged real broker delivery')
mid,fields=target;msg=json.loads(fields['job'])
else:
target_id=r.xadd(STREAM,{'job':json.dumps(msg)})
while True:
entries=r.xreadgroup(group,'crashable',{STREAM:'>'},count=100,block=1000)
target=next(((mid,fields) for _,batch in entries for mid,fields in batch if mid==target_id),None)
if target:mid,_=target;break
outcome=handle(msg,crash=args.crash)
if outcome!='defer':r.xack(STREAM,group,mid)
print(json.dumps({'outcome':outcome,'delivery_id':mid}),flush=True)
finally:
r.close();store.pool.close()
+37
View File
@@ -0,0 +1,37 @@
"""Concurrent shared-key requests through LB, real instance headers and history."""
from concurrent.futures import ThreadPoolExecutor
import json
import threading
import uuid
from client import Client, arguments, check, run
def main():
args = arguments(__doc__)
c = Client(args.base_url)
alice, bob, eve, chat = c.bootstrap()
key = uuid.uuid4().hex
barrier = threading.Barrier(16)
def worker(_):
local = Client(args.base_url)
barrier.wait()
return local.message(alice, chat, ' concurrent body ', key=key)
with ThreadPoolExecutor(max_workers=16) as pool:
responses = list(pool.map(worker, range(16)))
ids = {r['json']['id'] for r in responses}
instances = {r['headers']['X-Instance-Id'] for r in responses}
check(len(ids) == 1, 'concurrent duplicate messages')
check(len(instances) >= 2, 'concurrent requests did not reach two replicas')
path = '/api/v1/chats/' + chat['id'] + '/messages'
c.call('POST', path, 409, actor=alice, body={'text': 'concurrent body'}, headers={'Idempotency-Key': key})
again = c.call('POST', path, 201, actor=alice, body={'attachment_ids': [], 'text': ' concurrent body '}, headers={'Idempotency-Key': key}, schema='Message')
check(again['json'] == responses[0]['json'], 'semantic replay differs')
page = c.call('GET', path, actor=bob, schema='MessagePage')['json']
check(len(page['items']) == 1, 'history contains duplicate effects')
c.message(bob, chat, 'other user', key=key)
print(json.dumps({'parallel_requests': 16, 'observed_instances': sorted(instances), 'unique_messages': len(ids), 'conflict': 409, 'semantic_replay': True, 'user_scope': True}))
if __name__ == '__main__':
run(main)
+51
View File
@@ -0,0 +1,51 @@
"""Actual variant geometry, orientation, alpha, encoder metadata and hashes."""
import hashlib
import io
import json
from pathlib import Path
import sys
from PIL import Image
sys.path.insert(0,str(Path(__file__).resolve().parent))
from client import Client,check
def main():
c=Client('http://lb:8080');alice,bob,eve,chat=c.bootstrap();rows=[]
cases=[]
cases.append(('small_alpha',Image.new('RGBA',(80,40),(0,0,0,0)),'PNG',{},(80,40)))
cases.append(('exif_orientation',Image.new('RGB',(400,100),'red'),'JPEG',{'exif':Image.Exif()},(64,256)))
cases[-1][3]['exif'][274]=6
center=Image.new('RGB',(400,100),'red');center.paste('blue',(150,0,250,100))
cases.append(('center_crop',center,'PNG',{},(256,64)))
cases.append(('large_fit',Image.new('RGB',(1600,800),'green'),'PNG',{},(256,128)))
for name,image,fmt,options,expected in cases:
data=io.BytesIO();image.save(data,fmt,**options);payload=data.getvalue()
mime='image/png' if fmt=='PNG' else 'image/jpeg'
att=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename='+name,202,actor=alice,
raw=payload,headers={'Content-Type':mime},schema='Attachment')['json']
ready=c.wait_ready(alice,att)
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==payload,'original changed')
dimensions={}
for variant in ready['variants']:
result=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+variant['name'],actor=bob)
check(hashlib.sha256(result['bytes']).hexdigest()==variant['sha256'],'false checksum')
check(len(result['bytes'])==variant['size_bytes'],'false variant size')
with Image.open(io.BytesIO(result['bytes'])) as output:
check(not output.getexif(),'EXIF leaked')
check(output.size==(variant['width'],variant['height']),'false dimensions')
dimensions[variant['name']]=output.size
check(output.format==('WEBP' if variant['name']=='optimized' else 'JPEG'),'wrong encoder')
if variant['name']=='thumbnail':
check(output.size==expected,'thumbnail orientation/scale incorrect')
if name=='small_alpha':check(min(output.getpixel((10,10)))>245,'alpha not composited on white')
if variant['name']=='crop':
check(output.size==(128,128),'crop dimensions wrong')
if name=='center_crop':check(output.getpixel((64,64))[2]>240,'crop not centered')
if variant['name']=='optimized':
check(max(output.size)<=1280,'optimized too large')
if name=='large_fit':check(output.size==(1280,640),'optimized ratio wrong')
rows.append(dict(case=name,status='PASS',dimensions=dimensions,original_sha256=hashlib.sha256(payload).hexdigest()))
print(json.dumps({'status':'PASS','rows':rows},indent=2))
if __name__=='__main__':main()
+84
View File
@@ -0,0 +1,84 @@
"""Host orchestration: stopped worker, API kill, broker restart, real lease."""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
sys.path.insert(0,str(Path(__file__).resolve().parent))
from client import Client,check
ROOT=Path(__file__).resolve().parents[1]
COMPOSE=[str(ROOT/'scripts/compose.sh')]
def compose(*args,allow_failure=False):
p=subprocess.run(COMPOSE+list(args),cwd=ROOT,text=True,capture_output=True)
if p.returncode and not allow_failure:
raise AssertionError('Compose action failed: '+' '.join(args[:3])+': '+p.stderr[-500:])
return p
def probe(aid):
return json.loads(compose('run','--rm','--no-deps','ops','python','scripts/query_pipeline.py',aid).stdout)[-1]
def wait_api(c):
deadline=time.monotonic()+60
while time.monotonic()<deadline:
try:c.call('GET','/health/ready',schema='Health');return
except Exception:time.sleep(.3)
raise AssertionError('API recovery timeout')
def snapshot(services):
ids=compose('ps','-q',*services).stdout.split()
state=json.loads(subprocess.check_output(['docker','inspect',*ids],text=True))
return {x['Name'].lstrip('/'):{'id':x['Id'][:12],'started_at':x['State']['StartedAt'],
'volumes':sorted(m['Name'] for m in x['Mounts'] if m['Type']=='volume')} for x in state}
def main():
c=Client(os.environ.get('BASE_URL','http://localhost:8085'))
rows=[]
try:
compose('stop','worker','publisher')
alice,bob,eve,chat=c.bootstrap();att,data=c.attachment(alice,chat)
message=c.message(alice,chat,'',attachments=[att['id']])['json']
c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=alice)
check(probe(att['id'])['published_at'] is None,'publisher unexpectedly active')
before=snapshot(['api','broker'])
compose('kill','-s','SIGKILL','api');compose('start','api');wait_api(c)
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
page=c.call('GET','/api/v1/chats/'+chat['id']+'/messages',actor=bob,schema='MessagePage')['json']
check(any(m['id']==message['id'] for m in page['items']),'queued message lost')
compose('start','publisher')
deadline=time.monotonic()+20
while probe(att['id'])['published_at'] is None:
check(time.monotonic()<deadline,'outbox not delivered');time.sleep(.2)
length_before=int(compose('exec','-T','broker','valkey-cli','XLEN','attachments.v1').stdout)
compose('restart','broker')
length_after=int(compose('exec','-T','broker','valkey-cli','XLEN','attachments.v1').stdout)
check(length_after>=length_before>0,'broker lost durable messages')
after=snapshot(['api','broker'])
check(all(after[name]['started_at']!=row['started_at'] and after[name]['volumes']==row['volumes'] for name,row in before.items()),'restart did not preserve volumes')
start=time.monotonic();compose('start','worker');c.wait_ready(bob,att)
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==data,'accepted original lost')
rows.append(dict(scenario='stopped_worker_api_kill_outbox_broker_restart',status='PASS',attachment_id=att['id'],
stream_length_before=length_before,stream_length_after=length_after,ready_ms=round((time.monotonic()-start)*1000,3),
containers_before=before,containers_after=after))
compose('stop','worker','publisher')
att,data=c.attachment(alice,chat);jid=probe(att['id'])['job_id']
crash=compose('run','--rm','--no-deps','ops','python','tests/drive_job.py',jid,'--crash','after_effect',allow_failure=True)
check(crash.returncode==86,'worker failpoint did not crash')
check(probe(att['id'])['state']=='processing','processing lease missing')
start=time.monotonic();compose('start','publisher','worker');c.wait_ready(bob,att)
elapsed=time.monotonic()-start
check(elapsed>=20,'real lease expiry not exercised')
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==data,'lease recovery corrupted original')
rows.append(dict(scenario='crash_real_lease_expiry',status='PASS',attachment_id=att['id'],ready_ms=round(elapsed*1000,3),
job=probe(att['id']),lease_clock='real'))
print(json.dumps({'status':'PASS','rows':rows},ensure_ascii=False,indent=2))
finally:compose('start','api','broker','publisher','worker')
if __name__=='__main__':main()
+143
View File
@@ -0,0 +1,143 @@
"""Track 2: real crash processes, broker redelivery, version fencing and retries.
Run only with the normal worker and publisher stopped. Creates synthetic rows.
"""
import concurrent.futures
import hashlib
import io
import json
from pathlib import Path
import subprocess
import sys
import time
from PIL import Image
sys.path.insert(0,str(Path(__file__).resolve().parent))
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from client import Client,check,validate
from app import store,object_store
from pipeline import broker,envelope,fetch_job,MAX_ATTEMPTS,replay,upgrade,STREAM
from worker import handle
from publisher import publish_once
def main():
store.pool.open(wait=True,timeout=20)
c=Client('http://lb:8080');alice,bob,eve,chat=c.bootstrap();r=broker()
rows=[]
def upload():
att,data=c.attachment(alice,chat)
with store.connect() as conn:
jid=str(conn.execute('SELECT id FROM jobs WHERE attachment_id=%s',(att['id'],)).fetchone()[0])
msg=envelope(fetch_job(conn,jid))
validate(msg,json.loads((Path(__file__).resolve().parents[1]/'contracts/jobs.schema.json').read_text()))
return att,data,jid,msg
def metadata(att):return c.call('GET','/api/v1/attachments/'+att['id'],actor=alice,schema='Attachment')['json']
def objects(att,version=1):
return sorted(x['Key'] for x in object_store.client.list_objects_v2(Bucket=object_store.bucket,Prefix=f"results/{att['id']}/v{version}/").get('Contents',[]))
def invariant(att,data,version=1):
ready=metadata(att);check(ready['status']=='ready','lost accepted work')
check(len(ready['variants'])==3,'wrong number of variants')
check(len(objects(att,version))==4,'duplicate or missing objects')
for name in ('original','thumbnail','crop','optimized'):
result=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+name,actor=bob)
if name=='original':check(result['bytes']==data,'original mutated')
else:
v=next(x for x in ready['variants'] if x['name']==name)
check(hashlib.sha256(result['bytes']).hexdigest()==v['sha256'],'variant checksum mismatch')
with Image.open(io.BytesIO(result['bytes'])) as im:
check((im.width,im.height)==(v['width'],v['height']),'false dimensions')
check(not im.getexif(),'EXIF not stripped')
return ready
try:
for iteration in range(3):
for crash in ('before_effect','after_effect','after_commit'):
att,data,jid,msg=upload();start=time.monotonic()
result=subprocess.run([sys.executable,'tests/drive_job.py',jid,'--crash',crash],capture_output=True,text=True)
check(result.returncode==86,'failpoint did not kill the worker process')
before=objects(att)
check(len(before)==(0 if crash=='before_effect' else 4),'wrong crash window')
with store.connect() as conn:
j=fetch_job(conn,jid)
if crash!='after_commit':
check(j['state']=='processing','lease not persisted')
check(handle(msg)=='defer','live lease was stolen')
# Controlled clock acceleration for matrix speed. Separate
# persistence test exercises real 30-second lease timeout.
conn.execute("UPDATE jobs SET lease_until=now()-interval '1 second' WHERE id=%s",(jid,))
result=subprocess.run([sys.executable,'tests/drive_job.py',jid,'--recover'],capture_output=True,text=True)
check(result.returncode==0,'redelivery process failed')
check(json.loads(result.stdout)['outcome'] in ('ready','noop'),'redelivery did not complete')
ready=invariant(att,data)
# Successful duplicate must not update metadata or re-encode.
check(handle(msg)=='noop','ready duplicate was re-executed')
check(metadata(att)==ready,'ready changed after duplicate')
with store.connect() as conn:attempts=fetch_job(conn,jid)['attempt']
rows.append(dict(iteration=iteration+1,scenario=crash,status='PASS',attempts=attempts,
recovery_ms=round((time.monotonic()-start)*1000,3),objects=4,lease_expiry='accelerated' if crash!='after_commit' else 'not_needed'))
att,data,jid,msg=upload();start=time.monotonic()
outcomes=[]
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
outcomes=list(pool.map(lambda _:handle(msg),range(8)))
invariant(att,data)
check(outcomes.count('ready')==1,'concurrent duplicate produced multiple effects')
rows.append(dict(iteration=iteration+1,scenario='concurrent_duplicates',status='PASS',deliveries=8,
effects=1,recovery_ms=round((time.monotonic()-start)*1000,3),outcomes=outcomes,objects=4))
# New version overtakes an unprocessed old version.
att,data,jid,old=upload();new_jid=upgrade(store,att['id'])
with store.connect() as conn:new=envelope(fetch_job(conn,new_jid))
start=time.monotonic();check(handle(new)=='ready','new version failed')
newest=invariant(att,data,2)
for _ in range(5):check(handle(old)=='noop','stale job not fenced')
check(metadata(att)==newest and not objects(att,1),'old version overwrote new')
rows.append(dict(iteration=iteration+1,scenario='reorder_stale_version',status='PASS',old_deliveries=5,
current_version=2,old_objects=0,objects=4,recovery_ms=round((time.monotonic()-start)*1000,3)))
# Upgrade an already published result, then redeliver the old version.
att,data,jid,old=upload();check(handle(old)=='ready','v1 failed')
v1=invariant(att,data)
new_jid=upgrade(store,att['id'])
with store.connect() as conn:new=envelope(fetch_job(conn,new_jid))
check(handle(new)=='ready','upgrade failed');v2=invariant(att,data,2)
check(v1['variants']!=v2['variants'],'version settings did not change result')
check(handle(old)=='noop' and metadata(att)==v2,'published old version replaced upgraded result')
rows.append(dict(scenario='published_v1_then_v2_then_stale_v1',status='PASS',current_version=2,objects=4))
# Permanent errors, explicit audited replay, ready replay refused.
att,data,jid,msg=upload();check(handle(msg,force_error='permanent')=='failed','permanent failure retried')
check(metadata(att)['status']=='failed','failed not exposed')
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=alice,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':'failed-test'})
replay(store,jid);check(handle(msg)=='ready','operator replay did not recover')
invariant(att,data)
try:replay(store,jid);raise AssertionError('ready replay allowed')
except ValueError:pass
rows.append(dict(scenario='permanent_failed_replay',status='PASS',objects=4))
# Transient retry scheduling respects backoff and exhausts the bound.
att,data,jid,msg=upload();delays=[]
for attempt in range(MAX_ATTEMPTS):
check(handle(msg,force_error='temporary')=='retry','temporary failure not handled')
with store.connect() as conn:
j=fetch_job(conn,jid)
if attempt<MAX_ATTEMPTS-1:
delay=conn.execute('SELECT extract(epoch FROM next_at-now()) FROM jobs WHERE id=%s',(jid,)).fetchone()[0]
check(delay>0,'no backoff');delays.append(float(delay))
check(handle(msg)=='defer','retry ignored schedule')
conn.execute("UPDATE jobs SET next_at=now()-interval '1 second' WHERE id=%s",(jid,))
check(metadata(att)['error_code']=='retry_exhausted','retry was not bounded')
replay(store,jid);check(handle(msg)=='ready','retry exhausted replay failed');invariant(att,data)
rows.append(dict(scenario='bounded_retry_jitter',status='PASS',max_attempts=MAX_ATTEMPTS,delays_seconds=delays))
# COMMIT -> publish recovery, and a lost publish confirm duplicates safely.
att,data,jid,msg=upload()
with store.connect() as conn:check(conn.execute('SELECT published_at FROM outbox WHERE job_id=%s',(jid,)).fetchone()[0] is None,'outbox already published')
publish_once(r)
with store.connect() as conn:
conn.execute('UPDATE outbox SET published_at=NULL WHERE job_id=%s',(jid,))
publish_once(r)
check(handle(msg)=='ready' and handle(msg)=='noop','republish was unsafe');invariant(att,data)
rows.append(dict(scenario='outbox_republish',status='PASS',objects=4))
with store.connect() as conn:
accepted=conn.execute('SELECT count(*) FROM attachments').fetchone()[0]
result={'status':'PASS','track':2,'matrix_repeats':3,'rows':rows,'accepted_in_database':accepted,
'invariants':{'accepted_tasks_lost':0,'duplicate_variant_sets':0,'stale_version_overwrites':0},
'limitations':['matrix lease expiry accelerated with SQL','single host, worker processing is serial except intentional duplicate probe','no disk-loss or network partition proof']}
print(json.dumps(result,ensure_ascii=False,indent=2))
finally:r.close();store.pool.close();object_store.close()
if __name__=='__main__':main()
+53
View File
@@ -0,0 +1,53 @@
"""Anonymous access outside API and least-privilege negative checks."""
import json
from pathlib import Path
import sys
import urllib.error
import urllib.request
from botocore.exceptions import ClientError
sys.path.insert(0,str(Path(__file__).resolve().parent))
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from client import Client,check,run
def main():
from app import store,object_store
c=Client('http://lb:8080',timeout=15)
alice,bob,eve,chat=c.bootstrap()
att,_=c.attachment(alice,chat)
c.wait_ready(alice,att)
key='results/'+att['id']+'/v1/original'
anonymous=[]
for suffix in ('','/'+key):
try:
urllib.request.urlopen('http://s3:9000/'+object_store.bucket+suffix,timeout=3)
raise AssertionError('private bucket allowed anonymous access')
except urllib.error.HTTPError as exc:
check(exc.code==403,'anonymous access failed for an unexpected reason')
anonymous.append(exc.code)
# MinIO returns a filtered ListBuckets response to a ListBucket principal.
visible=[b['Name'] for b in object_store.client.list_buckets().get('Buckets',[])]
check(set(visible)<={object_store.bucket},'unrelated bucket names exposed')
denied=[]
for name,operation in [('create_bucket',lambda:object_store.client.create_bucket(Bucket='must-not-create-lab4')),
('get_bucket_policy',lambda:object_store.client.get_bucket_policy(Bucket=object_store.bucket)),
('write_outside_prefix',lambda:object_store.client.put_object(Bucket=object_store.bucket,Key='outside-policy',Body=b'no'))]:
try:
operation()
raise AssertionError('application credentials have excessive privileges: '+name)
except ClientError as exc:
check(exc.response['Error']['Code']=='AccessDenied','unexpected permission error')
denied.append(name)
# The console is bound to 127.0.0.1 inside S3 and browser UI is disabled.
import socket
try:
socket.create_connection(('s3',9001),timeout=1).close()
raise AssertionError('S3 console reachable from another container')
except OSError:
pass
print(json.dumps({'status':'PASS','anonymous_bucket_and_object_status':anonymous,
'application_admin_operations_denied':denied,'visible_bucket_names':visible,'console_reachable':False},indent=2))
object_store.close()
if __name__=='__main__':
run(main)
+129
View File
@@ -0,0 +1,129 @@
"""Contract boundaries and object authorization; runs in Compose ops network."""
import hashlib
import http.client
import io
import json
from pathlib import Path
import socket
import struct
import sys
import time
from urllib.parse import quote, urlsplit
import uuid
import zlib
from PIL import Image
sys.path.insert(0,str(Path(__file__).resolve().parent))
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from client import Client, check, run
def main():
c=Client('http://lb:8080',timeout=15)
alice,bob,eve,chat=c.bootstrap()
path='/api/v1/chats/'+chat['id']+'/attachments'
fixture=(Path(__file__).parent/'fixtures/sample.png').read_bytes()
cases=[]
def bad(label,status,data=fixture,mime='image/png',filename='test.png',actor=None):
c.call('POST',path+'?filename='+quote(filename,safe=''),status,actor=actor or alice,raw=data,headers={'Content-Type':mime})
cases.append({'case':label,'status':status})
bad('corrupt_png',415,b'not an image')
bad('truncated_png',415,fixture[:50])
bad('mime_spoof',415,mime='image/jpeg')
bad('unsupported_mime',415,mime='application/octet-stream')
bad('empty_payload',415,b'')
for filename in ('../secret.png','a\\b.png','x\x00.png','x\n.png','x\u202e.png','x'*256):
bad('unsafe_filename',400,filename=filename)
bad('foreign_chat_upload',404,actor=eve)
c.call('POST',path+'?filename=x.png',401,raw=fixture,headers={'Content-Type':'image/png'})
cases.append({'case':'unauthenticated_upload','status':401})
# Oversized dimensions are rejected using headers before a full raster decode.
data=bytearray(fixture)
data[16:24]=struct.pack('>II',10000,4001)
data[29:33]=struct.pack('>I',zlib.crc32(data[12:29])&0xffffffff)
bad('over_40_million_pixels',413,bytes(data))
# No large allocation or body transfer: reject declared size before reading.
parsed=urlsplit(c.base)
conn=http.client.HTTPConnection(parsed.hostname,parsed.port,timeout=10)
conn.putrequest('POST',path+'?filename=big.png')
for k,v in {'Authorization':'Bearer '+alice['token'],'Content-Type':'image/png','Content-Length':str(10485761)}.items():
conn.putheader(k,v)
conn.endheaders()
response=conn.getresponse()
check(response.status==413,'oversized content-length accepted')
response.read();conn.close()
cases.append({'case':'oversized_content_length_before_body','status':413})
# True streamed overflow, no Content-Length; response is read after the last
# chunk, even if the peer stopped accepting bytes once it knew the limit.
conn=http.client.HTTPConnection(parsed.hostname,parsed.port,timeout=15)
conn.putrequest('POST',path+'?filename=chunked.png')
conn.putheader('Authorization','Bearer '+alice['token'])
conn.putheader('Content-Type','image/png')
conn.putheader('Transfer-Encoding','chunked')
conn.endheaders()
try:
block=b'x'*65536
for _ in range(161):
conn.send(b'10000\r\n'+block+b'\r\n')
conn.send(b'0\r\n\r\n')
except (BrokenPipeError,ConnectionResetError):
pass
response=conn.getresponse()
check(response.status==413,'streamed byte limit not enforced')
response.read();conn.close()
cases.append({'case':'chunked_oversize','status':413})
att,content=c.attachment(alice,chat)
# Another member can reference an attachment; ownership is not required.
msg=c.message(bob,chat,'',attachments=[att['id']])['json']
check(msg['attachment_ids']==[att['id']],'member could not link attachment')
for suffix in ('','/content'):
c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=eve)
c.wait_ready(alice,att)
c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=unknown',404,actor=alice)
cases.append({'case':'foreign_attachment_metadata_and_bytes','status':404})
other=c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'other','member_ids':[alice['id']]},schema='Chat')['json']
other_path='/api/v1/chats/'+other['id']+'/messages'
for aid in (att['id'],str(uuid.uuid4())):
c.call('POST',other_path,404,actor=alice,body={'text':'','attachment_ids':[aid]},headers={'Idempotency-Key':uuid.uuid4().hex})
cases.append({'case':'cross_chat_and_unknown_attachment','status':404})
message_path='/api/v1/chats/'+chat['id']+'/messages'
for ids in ([att['id'],att['id']],['bad-id'],[str(uuid.uuid4()) for _ in range(11)]):
c.call('POST',message_path,400,actor=alice,body={'text':'','attachment_ids':ids},headers={'Idempotency-Key':uuid.uuid4().hex})
key=uuid.uuid4().hex
first=c.message(alice,chat,'',key=key,attachments=[att['id']])['json']
second=c.message(alice,chat,'',key=key,attachments=[att['id']])['json']
check(first==second,'attachment message replay changed')
c.call('POST',message_path,409,actor=alice,body={'text':'different','attachment_ids':[att['id']]},headers={'Idempotency-Key':key})
cases.append({'case':'attachment_idempotency_and_conflict','status':'201/409'})
# Full JPEG validation, including truncated entropy-coded body.
stream=io.BytesIO()
Image.new('RGB',(320,200),'blue').save(stream,'JPEG')
jpeg=stream.getvalue()
uploaded=c.call('POST',path+'?filename=photo.jpg',202,actor=alice,raw=jpeg,headers={'Content-Type':'image/jpeg'},schema='Attachment')['json']
c.wait_ready(alice,uploaded)
downloaded=c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content',actor=bob)
check(downloaded['bytes']==jpeg,'JPEG original changed')
bad('truncated_jpeg',415,jpeg[:-20],mime='image/jpeg')
# A disconnect before receiving all bytes creates neither intent nor object.
from app import store,object_store
store.pool.open(wait=True,timeout=15)
try:
def counts():
with store.connect() as db:
n=db.execute('SELECT count(*) FROM attachments').fetchone()[0]
return n,len(object_store.client.list_objects_v2(Bucket=object_store.bucket,Prefix='staging/').get('Contents',[]))
before=counts()
conn=http.client.HTTPConnection(parsed.hostname,parsed.port,timeout=5)
conn.putrequest('POST',path+'?filename=interrupted.png')
conn.putheader('Authorization','Bearer '+alice['token'])
conn.putheader('Content-Type','image/png')
conn.putheader('Content-Length',str(len(fixture)))
conn.endheaders();conn.send(fixture[:50]);conn.close()
time.sleep(1)
check(counts()==before,'aborted upload persisted partial data')
cases.append({'case':'interrupted_http_body','metadata_or_object_added':False})
finally:
store.pool.close();object_store.close()
print(json.dumps({'status':'PASS','cases':cases,'count':len(cases)},ensure_ascii=False,indent=2))
if __name__=='__main__':
run(main)