109 lines
7.3 KiB
Python
109 lines
7.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Live root rollover: TLS overlap, data/session retention, latency/resource samples."""
|
|
import argparse,hashlib,json,math,os,ssl,subprocess,sys,threading,time,urllib.error,urllib.request
|
|
from pathlib import Path
|
|
ROOT=Path(__file__).resolve().parent.parent
|
|
sys.path.insert(0,str(ROOT/'tests'))
|
|
from client import Client,check
|
|
sys.path.insert(0,str(ROOT/'scripts'))
|
|
import pki_state as pki
|
|
|
|
|
|
def percentile(values,p):
|
|
if not values:return None
|
|
return round(sorted(values)[max(0,math.ceil(len(values)*p)-1)],3)
|
|
|
|
def memory_bytes(text):
|
|
import re
|
|
match=re.fullmatch(r'([0-9.]+)\s*([A-Za-z]+)',text.strip())
|
|
if not match:raise ValueError('Unavailable memory sample')
|
|
value,unit=match.groups()
|
|
factor={'B':1,'kB':1000,'KB':1000,'MB':1000**2,'GB':1000**3,'KiB':1024,'MiB':1024**2,'GiB':1024**3}[unit]
|
|
return float(value)*factor
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser();parser.add_argument('--base-url',default=os.environ.get('BASE_URL','https://localhost:8443'));args=parser.parse_args()
|
|
os.environ['BASE_URL']=args.base_url
|
|
before=pki.fingerprint(ROOT/'certs/ca.crt')
|
|
client=Client(args.base_url,str(ROOT/'certs/ca.crt'))
|
|
alice,bob,eve,chat=client.bootstrap()
|
|
original=client.message(alice,chat,'CA rollover confirmed data')['json']
|
|
attachment,content=client.attachment(alice,chat);client.wait_ready(alice,attachment)
|
|
checks=[]
|
|
def retained(phase):
|
|
# Explicitly reload the distributed trust bundle; keep the same bearer tokens.
|
|
c=Client(args.base_url,str(ROOT/'certs/ca.crt'))
|
|
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
|
history=c.call('GET','/api/v1/chats/'+chat['id']+'/messages?limit=100',actor=bob,schema='MessagePage')['json']['items']
|
|
check(any(m==original for m in history),'Confirmed message changed during rollover')
|
|
data=c.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=bob)['bytes']
|
|
check(data==content,'Attachment changed during rollover')
|
|
checks.append({'phase':phase,'existing_session':'PASS','message':'PASS','attachment_sha256':hashlib.sha256(data).hexdigest(),'trusted_roots':(ROOT/'certs/ca.crt').read_text().count('BEGIN CERTIFICATE')})
|
|
retained('before')
|
|
stopping=threading.Event();samples=[];resources={};resource_failures=[];started=time.monotonic()
|
|
def load():
|
|
while not stopping.is_set():
|
|
now=time.monotonic();status='200'
|
|
try:
|
|
ctx=ssl.create_default_context(cafile=str(ROOT/'certs/ca.crt'))
|
|
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
|
|
with opener.open(args.base_url+'/health/ready',timeout=2) as r:assert r.status==200
|
|
except urllib.error.HTTPError as e:status=str(e.code)
|
|
except (OSError,ValueError) as e:
|
|
cause=e.reason if isinstance(e,urllib.error.URLError) else e
|
|
status=type(cause).__name__
|
|
samples.append({'seconds':round(time.monotonic()-started,3),'latency_ms':round((time.monotonic()-now)*1000,3),'status':status})
|
|
stopping.wait(.25)
|
|
def stats():
|
|
while not stopping.is_set():
|
|
try:
|
|
r=subprocess.run([str(ROOT/'scripts/docker.sh'),'stats','--no-stream','--format','{{json .}}'],text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=8)
|
|
for line in r.stdout.splitlines():
|
|
row=json.loads(line);name=row['Name']
|
|
if not name.startswith('lab7-') or not name.endswith('-1'):continue
|
|
cpu=float(row['CPUPerc'].rstrip('%'));memory=memory_bytes(row['MemUsage'].split('/')[0])
|
|
entry=resources.setdefault(name,{'max_sampled_cpu_percent':0.,'max_sampled_memory_bytes':0.,'samples':0})
|
|
entry['max_sampled_cpu_percent']=max(entry['max_sampled_cpu_percent'],cpu)
|
|
entry['max_sampled_memory_bytes']=max(entry['max_sampled_memory_bytes'],memory);entry['samples']+=1
|
|
except (OSError,ValueError,KeyError,subprocess.TimeoutExpired):resource_failures.append(time.monotonic()-started)
|
|
stopping.wait(3)
|
|
threads=[threading.Thread(target=load),threading.Thread(target=stats)]
|
|
for thread in threads:thread.start()
|
|
result={'status':'RUNNING','old_root':before,'profile':'one sequential HTTPS readiness client, 250ms pause, 2s request timeout; nearest-rank percentiles','warmup':'fixture creation before sampling','hardware':{'logical_cpus':os.cpu_count(),'mem_total':next((s.strip() for s in Path('/proc/meminfo').read_text().splitlines() if s.startswith('MemTotal:')),None)},'data_checks':checks}
|
|
try:
|
|
for phase in ('prepare','reissue','retire'):
|
|
print('Running CA phase: '+phase,flush=True)
|
|
log=ROOT/'secrets/operator'/('ca-'+phase+'.log')
|
|
fd=os.open(log,os.O_WRONLY|os.O_CREAT|os.O_TRUNC,0o600)
|
|
with os.fdopen(fd,'wb') as f:
|
|
r=subprocess.run([str(ROOT/'scripts/ca-rollover.sh'),phase],cwd=ROOT,stdout=f,stderr=f,timeout=240)
|
|
check(r.returncode==0,'CA '+phase+' failed; inspect private operator log')
|
|
retained(phase)
|
|
if phase=='reissue':
|
|
old=pki.authority(pki.state()['old'])/'issuer.crt'
|
|
try:
|
|
urllib.request.urlopen(args.base_url+'/health/ready',context=ssl.create_default_context(cafile=str(old)),timeout=3)
|
|
raise AssertionError('Old-root-only client still trusts the new server')
|
|
except urllib.error.URLError as e:
|
|
check(isinstance(e.reason,ssl.SSLCertVerificationError),'Old-only client failed for a non-certificate reason')
|
|
result['old_root_only_client']='rejected with certificate verification error'
|
|
result['new_root']=pki.fingerprint(ROOT/'certs/ca.crt')
|
|
check(result['old_root']!=result['new_root'],'Root fingerprint did not change')
|
|
stopping.wait(2)
|
|
stopping.set()
|
|
for thread in threads:
|
|
thread.join()
|
|
check(resources,'No resource samples collected')
|
|
check(any(s['status']=='200' for s in samples),'No successful HTTPS readiness samples')
|
|
check(not any(s['status']=='SSLCertVerificationError' for s in samples),'Unexpected certificate verification error under dual trust')
|
|
result['status']='PASS'
|
|
finally:
|
|
stopping.set()
|
|
for thread in threads:thread.join(timeout=10)
|
|
elapsed=time.monotonic()-started;good=[s['latency_ms'] for s in samples if s['status']=='200'];all_times=[s['latency_ms'] for s in samples]
|
|
result.update(elapsed_seconds=round(elapsed,3),requests=len(samples),successes=len(good),errors=len(samples)-len(good),successful_rps=round(len(good)/elapsed,3),latency_ms={'all':{f'p{int(p*100)}':percentile(all_times,p) for p in (.5,.95,.99)},'successful':{f'p{int(p*100)}':percentile(good,p) for p in (.5,.95,.99)}},resource_samples=resources,resource_sampler_failures=len(resource_failures),raw_requests=samples)
|
|
if result['status']=='RUNNING':result['status']='FAIL'
|
|
(ROOT/'evidence/ca-rollover-load.json').write_text(json.dumps(result,indent=2,ensure_ascii=False)+'\n')
|
|
print('PASS: three CA phases, old-root rejection, same session/message/attachment preserved; metrics saved',flush=True)
|
|
if __name__=='__main__':main()
|