"""Host-side backend queries and genuine trace/log correlation. No tokens saved.""" import base64 import ssl import json import os from pathlib import Path import time import urllib.error import urllib.parse import urllib.request import uuid from client import Client,check ROOT=Path(__file__).resolve().parents[1] TLS=ssl.create_default_context(cafile=str(ROOT/'.secrets/ca.crt')) TLS.load_cert_chain(str(ROOT/'.secrets/roles/operator/service.pem')) def get(url,headers=None): with urllib.request.urlopen(urllib.request.Request(url,headers=headers or {}),context=TLS,timeout=8) as response: return json.load(response) def prom(expr): return get('https://localhost:9097/api/v1/query?'+urllib.parse.urlencode({'query':expr}))['data']['result'] def logs(trace_id=None,service='messenger-api'): query='{service_name="'+service+'"}' if trace_id:query+=' |= "'+trace_id+'"' return get('https://localhost:3107/loki/api/v1/query_range?'+urllib.parse.urlencode({'query':query,'since':'15m','limit':1000}))['data']['result'] def trace_data(trace_id): return get('https://localhost:3207/api/traces/'+trace_id) def flatten(data): rows=[] for batch in data.get('batches',data.get('resourceSpans',[])): attrs={a['key']:a['value'].get('stringValue',a['value'].get('intValue')) for a in batch.get('resource',{}).get('attributes',[])} for scope in batch.get('scopeSpans',batch.get('instrumentationLibrarySpans',[])): for s in scope.get('spans',[]):rows.append({**s,'service':attrs.get('service.name')}) return rows def wait_for(call,predicate=lambda x:bool(x),timeout=60): deadline=time.monotonic()+timeout;last=None while time.monotonic()=2 and all(r['value'][1]=='1' for r in rows)) c=Client('https://localhost:8443',ca_file=str(ROOT/'.secrets/ca.crt'));alice,bob,eve,chat=c.bootstrap() trace_id=uuid.uuid4().hex;parent=uuid.uuid4().hex[:16] carrier='00-'+trace_id+'-'+parent+'-01' payload=(ROOT/'tests/fixtures/sample.png').read_bytes() att=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=probe.png',202,actor=alice, raw=payload,headers={'Content-Type':'image/png','traceparent':carrier},schema='Attachment')['json'] c.wait_ready(alice,att) data=wait_for(lambda:trace_data(trace_id),lambda x: any(s['name']=='queue.process' for s in flatten(x))) rows=flatten(data) required={'queue.publish','queue.process','s3.put_object','db.transaction'} check(required<={r['name'] for r in rows},'incomplete upload -> broker -> worker -> S3/DB trace') api=next(r for r in rows if r['service']=='messenger-api' and r['kind'] in ('SPAN_KIND_SERVER',2)) producer=next(r for r in rows if r['name']=='queue.publish') consumer=next(r for r in rows if r['name']=='queue.process') # Tempo JSON may serialize IDs as base64 or hex depending on version. check(producer['parentSpanId'] in {s['spanId'] for s in rows if s['service']=='messenger-api'},'producer not parented to acceptance trace') check(consumer['parentSpanId']==producer['spanId'],'consumer not parented to producer') api_logs=wait_for(lambda:logs(trace_id)) worker_logs=wait_for(lambda:logs(trace_id,'messenger-worker')) check(api_logs and worker_logs,'missing correlated logs') queries=['sum(messenger_http_requests_total{service_name="messenger-api"})', 'sum(messenger_jobs_total{service_name="messenger-worker",outcome="ready"})', 'sum(messenger_http_duration_seconds_bucket{service_name="messenger-api",le="0.5"})', 'max(messenger_queue_depth{service_name="messenger-observer"})', 'max(messenger_db_pool_used{service_name="messenger-api"})'] observations={q:wait_for(lambda q=q:prom(q)) for q in queries} secret_values=[alice['token'],bob['token'],eve['token'],alice['registration']['password'],bob['registration']['password'],eve['registration']['password']] text=json.dumps([data,api_logs,worker_logs]) check(not any(secret in text for secret in secret_values),'credential in telemetry') secrets=dict(line.split('=',1) for line in (ROOT/'.env').read_text().splitlines() if '=' in line) credentials=base64.b64encode(('admin:'+secrets['GRAFANA_PASSWORD']).encode()).decode() uid=json.loads((ROOT/'infra/grafana/dashboards/messenger.json').read_text())['uid'] dashboard=wait_for(lambda:get('https://localhost:3007/api/dashboards/uid/'+uid,{'Authorization':'Basic '+credentials})) check(len(dashboard['dashboard']['panels'])>=15,'provisioned dashboard missing') proxied={} for name,path in [('prometheus','/api/v1/query?query=up'),('loki','/loki/api/v1/labels'),('tempo','/api/search?limit=1')]: wait_for(lambda name=name,path=path:get('https://localhost:3007/api/datasources/proxy/uid/'+name+path,{'Authorization':'Basic '+credentials})) proxied[name]='PASS via Grafana mTLS client' (ROOT/'evidence/correlated-trace.json').write_text(json.dumps(data,indent=2)) (ROOT/'evidence/correlated-logs.json').write_text(json.dumps({'api':api_logs,'worker':worker_logs},indent=2)) result={'status':'PASS','trace_id':trace_id,'attachment_id':att['id'], 'span_count':len(rows),'services':sorted({r['service'] for r in rows}), 'producer_parent_api':True,'consumer_parent_producer':True,'api_and_worker_logs':True, 'metric_queries':observations,'dashboard_uid':dashboard['dashboard']['uid'],'dashboard_panels':len(dashboard['dashboard']['panels']), 'known_credentials_absent':True,'grafana_proxied_backends':proxied} print(json.dumps(result,indent=2)) if __name__=='__main__':main()