Files
mtusi2026lab3/scripts/verify_key_lifecycle.py

53 lines
2.5 KiB
Python

"""Real DB fault and synthetic 24h expiry boundary; no production clock manipulation."""
import json
import time
import uuid
import httpx
from stack import ROOT,docker,ready
def sql(q):
return docker('compose','exec','-T','db','psql','-U','messenger','-d','messenger','-Atc',q)
result={}
with httpx.Client(base_url='http://127.0.0.1:8080',timeout=12) as c:
ready(c)
name='expiry_'+uuid.uuid4().hex[:20]
password='expiry-password-123'
r=c.post('/api/v1/users',json={'username':name,'display_name':'Lifecycle','password':password})
assert r.status_code==201
uid=r.json()['id']
r=c.post('/api/v1/auth/sessions',auth=(name,password)); assert r.status_code==201
h={'Authorization':'Bearer '+r.json()['token']}
r=c.post('/api/v1/chats',headers=h,json={'title':'Lifecycle','member_ids':[uid]}); assert r.status_code==201
path='/api/v1/chats/'+r.json()['id']+'/messages'
key=uuid.uuid4().hex
headers={**h,'Idempotency-Key':key}
first=c.post(path,headers=headers,json={'text':'Original'}); assert first.status_code==201
seconds=float(sql("SELECT extract(epoch from expires_at-clock_timestamp()) FROM idempotency WHERE key='"+key+"'"))
assert 86390<seconds<=86400
# Isolated synthetic key only: fast-forward its DB expiry, never wall clock or other data.
sql("UPDATE idempotency SET expires_at=clock_timestamp()-interval '1 second' WHERE key='"+key+"'")
second=c.post(path,headers=headers,json={'text':'After expiry'})
assert second.status_code==201 and first.json()['id']!=second.json()['id']
result['ttl']={'observed_seconds_after_create':seconds,'expired_key_reusable':True}
newkey=uuid.uuid4().hex
docker('compose','stop','db')
try:
r=c.post(path,headers={**h,'Idempotency-Key':newkey},json={'text':'After transient failure'})
assert r.status_code==503
result['database_down_status']=r.status_code
finally: docker('compose','start','db')
ready(c)
assert sql("SELECT count(*) FROM idempotency WHERE key='"+newkey+"'")=='0'
# LB may still be waiting for its next readiness healthcheck.
deadline=time.monotonic()+10
while True:
r=c.post(path,headers={**h,'Idempotency-Key':newkey},json={'text':'After transient failure'})
if r.status_code==201: break
assert r.status_code==503 and time.monotonic()<deadline
time.sleep(.2)
result['transient_failure_not_recorded']=True
result['passed']=True
(ROOT/'evidence/key-lifecycle.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,indent=2))