Files
mtusi2026lab7-fork/student-tests/observability_tls.py

56 lines
3.4 KiB
Python

"""Verify lab6 signals after adding lab7 trust boundaries."""
import base64,json,sys,time,uuid,urllib.parse,urllib.request
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path[:0]=[str(ROOT/'scripts'),str(ROOT/'tests')]
from local_https import get
from client import Client,check
import ssl
c=Client('https://localhost:8443',str(ROOT/'secrets/ca/ca.crt'));a,b,_,chat=c.bootstrap()
reply=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png',202,actor=a,raw=(ROOT/'tests/fixtures/sample.png').read_bytes(),headers={'Content-Type':'image/png','traceparent':'00-'+uuid.uuid4().hex+'-1234567890abcdef-01','tracestate':'lab=lab7'},schema='Attachment')
c.wait_ready(b,reply['json']);tid=reply['headers']['X-Trace-Id']
def wait(fn):
for _ in range(45):
try:
value=fn()
if value:return value
except OSError:pass
time.sleep(1)
raise AssertionError('Telemetry not available')
def spans():
data=get('tempo','/api/traces/'+tid);found=[]
def walk(item):
if isinstance(item,dict):
if 'spanId' in item and 'name' in item:found.append(item)
for value in item.values():walk(value)
elif isinstance(item,list):
for value in item:walk(value)
walk(data)
names={s['name'] for s in found}
return found if {'attachment.publish','attachment.consume','s3.put','postgresql.transaction'}<=names else None
found=wait(spans)
for span in found:
if span['name'] in ('attachment.publish','attachment.consume'):check(span.get('traceState')=='lab=lab7','lost tracestate')
query=urllib.parse.urlencode({'query':'{service_name=~"messenger-.*"} |= "'+tid+'"','since':'1h','limit':1000})
def logs():
rows=get('loki','/loki/api/v1/query_range?'+query)['data']['result']
return rows if {'messenger-api','messenger-worker','messenger-publisher'}<={r['stream']['service_name'] for r in rows} else None
wait(logs)
q=urllib.parse.urlencode({'query':'messenger_http_duration_seconds_bucket'})
wait(lambda:get('prometheus','/api/v1/query?'+q)['data']['result'])
health=get('prometheus','/api/v1/query?'+urllib.parse.urlencode({'query':'up'}))['data']['result']
check(all(row['value'][1]=='1' for row in health),'scrape TLS failed')
# Unique canary and session token must be absent from persisted logs/traces.
canary='PRIVATE_'+uuid.uuid4().hex
c.message(a,chat,canary);time.sleep(5)
for secret in (canary,a['token']):
q=urllib.parse.urlencode({'query':'{service_name=~"messenger-.*"} |= "'+secret+'"','since':'1h','limit':10})
check(not get('loki','/loki/api/v1/query_range?'+q)['data']['result'],'sensitive data in logs')
password=(ROOT/'secrets/operator/grafana_password').read_text().strip()
auth='Basic '+base64.b64encode(('admin:'+password).encode()).decode()
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca/ca.crt'))
request=urllib.request.Request('https://localhost:17400/api/dashboards/uid/messenger',headers={'Authorization':auth})
with urllib.request.urlopen(request,context=ctx,timeout=10) as response:dashboard=json.load(response)
check(len(dashboard['dashboard']['panels'])==14,'provisioning missing')
(ROOT/'evidence/observability-tls.json').write_text(json.dumps({'trace_id':tid,'span_names':[s['name'] for s in found],'all_three_log_services':True,'prometheus_scrapes_tls':True,'grafana_panels':14,'body_token_absent_from_logs':True},indent=2)+'\n')
print('PASS TLS metrics/logs/traces and Grafana provisioning')