Files
mtusi2026lab7/student-tests/telemetry.py
T

55 lines
4.1 KiB
Python

#!/usr/bin/env python3
"""Verify actual TLS OTLP/queries, trace chain, provisioned Grafana and privacy."""
import importlib.util,json,time,urllib.parse,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
s=importlib.util.spec_from_file_location('sec',ROOT/'student-tests/security.py');sec=importlib.util.module_from_spec(s);s.loader.exec_module(sec)
from client import Client
def query(url,**extra):
r=sec.probe(Kind='http',URL=url,Cert='operator',ReturnBody=True,**extra)
if not r['ok']:raise RuntimeError('telemetry query not ready')
return json.loads(r['body'])
def wait(fn,seconds=60):
start=time.monotonic()
while time.monotonic()-start<seconds:
try:
r=fn()
if r:return r
except (RuntimeError,KeyError,ValueError):pass
time.sleep(1)
raise AssertionError('telemetry did not become visible')
def main():
c=Client(sec.BASE,ca_file=sec.CA);a,b,o,chat=c.bootstrap();traceid=uuid.uuid4().hex;parent=uuid.uuid4().hex[:16]
r=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=synthetic.png',202,actor=a,raw=(ROOT/'tests/fixtures/sample.png').read_bytes(),headers={'Content-Type':'image/png','traceparent':'00-'+traceid+'-'+parent+'-01'},schema='Attachment');c.wait_ready(a,r['json'])
def chain():
raw=query('https://tempo:3200/api/traces/'+traceid);spans=[]
for batch in raw.get('batches',raw.get('resourceSpans',[])):
attrs={x['key']:x['value'].get('stringValue') for x in batch.get('resource',{}).get('attributes',[])}
for scope in batch.get('scopeSpans',batch.get('instrumentationLibrarySpans',[])):
for x in scope.get('spans',[]):spans.append({'service':attrs.get('service.name'),'name':x['name'],'id':x.get('spanId'),'parent':x.get('parentSpanId')})
if not {'queue.publish','queue.consume','s3.request','image.transform'}.issubset({x['name'] for x in spans}):return None
for x in spans:
if x['name']=='queue.consume' and x['parent'] not in {s['id'] for s in spans if s['name']=='queue.publish'}:return None
serialized=json.dumps(raw)
for actor in [a,b,o]:assert actor['token'] not in serialized and actor['registration']['password'] not in serialized
return spans
spans=wait(chain)
params={'query':'{service_name=~"messenger-(api|worker|dispatcher)"} | trace_id="'+traceid+'"','start':str(int((time.time()-180)*1e9)),'end':str(int(time.time()*1e9)),'limit':'100'}
logs=wait(lambda:query('https://loki:3100/loki/api/v1/query_range?'+urllib.parse.urlencode(params))['data']['result'])
assert {'messenger-api','messenger-worker'}.issubset({x['stream']['service_name'] for x in logs})
serialized=json.dumps(logs)
for actor in [a,b,o]:assert actor['token'] not in serialized and actor['registration']['password'] not in serialized
metrics=query('https://prometheus:9090/api/v1/query?'+urllib.parse.urlencode({'query':'sum(http_server_requests_total)'}));assert metrics['data']['result']
grafana=wait(lambda:query('https://grafana:3000/api/dashboards/uid/messenger-lab7',Auth='grafana'))
# Verify provisioned datasource TLS settings by doing actual backend health checks as Grafana.
ds={}
for uid,path in [('prometheus','/api/v1/query?query=1'),('loki','/loki/api/v1/query_range?'+urllib.parse.urlencode(params)),('tempo','/api/traces/'+traceid)]:
# Tempo12 plugin has no health method; exercise real Grafana proxy queries.
value=query('https://grafana:3000/api/datasources/proxy/uid/'+uid+path,Auth='grafana')
assert value,(uid,'empty Grafana query')
ds[uid]='actual query via Grafana proxy succeeded'
result={'trace_id':traceid,'spans':spans,'services':sorted({x['service'] for x in spans}),'log_services':sorted({x['stream']['service_name'] for x in logs}),'log_lines':sum(len(x['values']) for x in logs),'known_synthetic_tokens_passwords_absent':True,'dashboard':{'uid':grafana['dashboard']['uid'],'panels':len(grafana['dashboard']['panels'])},'actual_grafana_datasource_health':ds,'network_protocol':'all queries and OTLP use verified TLS/mTLS; native loopback remains inside gateway boundary'}
(ROOT/'evidence/telemetry.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: real TLS trace/log/metrics chain, privacy and all three provisioned Grafana datasource connections',flush=True)
if __name__=='__main__':main()