Files
mtusi2026lab7/student-tests/telemetry.py
T

86 lines
4.0 KiB
Python

"""Observe real signals through authenticated Grafana HTTPS datasource proxy."""
import base64
import json
from pathlib import Path
import ssl
import subprocess
import sys
import time
import urllib.request
import urllib.parse
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'scripts'))
from manage import env
def get(path):
credential=base64.b64encode(('admin:'+(ROOT/'secrets/grafana_password').read_text().strip()).encode()).decode()
request=urllib.request.Request('https://localhost:'+env()['GRAFANA_PORT']+path,headers={'Authorization':'Basic '+credential})
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca.crt'))
with urllib.request.urlopen(request,context=ctx,timeout=15) as response:
return json.load(response)
def query(source,path,**params):
return get('/api/datasources/proxy/uid/'+source+path+'?'+urllib.parse.urlencode(params))
def secret_values():
values=[]
def walk(v):
if isinstance(v,dict):
for item in v.values():walk(item)
elif isinstance(v,list):
for item in v:walk(item)
elif isinstance(v,str) and len(v)>=20 and '\n' not in v and not v.startswith(('-----','^')):
values.append(v)
for file in (ROOT/'secrets').glob('*'):
if not file.is_file() or file.suffix in ('.crt','.yaml'):continue
data=file.read_text()
try:walk(json.loads(data))
except ValueError:
if len(data.strip())>=20:values.append(data.strip())
operator=ROOT/'secrets/operator/bao-init.json'
if operator.exists():walk(json.loads(operator.read_text()))
return values
def main():
dashboard=get('/api/dashboards/uid/messenger')['dashboard']
assert len(dashboard['panels'])>=6
result={}
result['metrics']=query('prometheus','/api/v1/query',query='messenger_http_requests_total')
assert result['metrics']['data']['result'],'No HTTP counters stored'
result['jobs']=query('prometheus','/api/v1/query',query='messenger_jobs_total')
assert result['jobs']['data']['result'],'No worker metrics stored'
result['logs']=query('loki','/loki/api/v1/query_range',query='{service_name=~"messenger-api|messenger-worker"}',limit=1000,
start=str(time.time_ns()-3600*10**9),end=str(time.time_ns()))
assert result['logs']['data']['result'],'No API or worker logs stored'
services=set(stream['stream'].get('service_name') for stream in result['logs']['data']['result'])
assert {'messenger-api','messenger-worker'}<=services,services
trace_counts={}
for service in ('messenger-api','messenger-worker'):
traces=query('tempo','/api/search',q='{resource.service.name="'+service+'"}',limit=20)
assert traces.get('traces'),('No stored traces',service)
trace_counts[service]=len(traces['traces'])
trace_id=traces['traces'][0]['traceID']
result['trace_'+service]=get('/api/datasources/proxy/uid/tempo/api/traces/'+trace_id)
# Inspect returned records, not only Collector configuration.
payload=json.dumps(result)
for value in secret_values():
assert value not in payload,'Credential found in stored telemetry'
assert base64.b64encode(value.encode()).decode() not in payload,'Encoded credential found in telemetry'
assert 'BEGIN PRIVATE KEY' not in payload
# Container logs are scanned in memory and never saved as raw evidence.
logs=subprocess.check_output(['docker','compose','logs','--no-color'],cwd=ROOT).decode(errors='replace')
for value in secret_values():assert value not in logs,'Credential found in container logs'
summary={'grafana_https':True,'provisioned_panels':len(dashboard['panels']),
'http_metric_series':len(result['metrics']['data']['result']),'job_metric_series':len(result['jobs']['data']['result']),
'log_services':sorted(services),'trace_counts':trace_counts,'credential_scan':'PASS; returned telemetry and container logs'}
(ROOT/'evidence/telemetry.json').write_text(json.dumps(summary,indent=2),encoding='utf-8')
print(json.dumps(summary,indent=2))
if __name__=='__main__':main()