#!/usr/bin/env python3 from pathlib import Path import yaml,json,subprocess,tempfile,time,socket,urllib.request import argparse import os parser = argparse.ArgumentParser(description="Local service-log config/masking tests; no cluster or real S3 access") parser.add_argument('--collector-bin', required=True) parser.add_argument('--vector-bin', required=True) args = parser.parse_args() repo = Path(__file__).resolve().parents[2] temporary = tempfile.TemporaryDirectory(prefix='service-log-check-') root = Path(temporary.name) with socket.socket() as port_socket: port_socket.bind(('127.0.0.1', 0)) port = port_socket.getsockname()[1] cfg=yaml.safe_load((repo / 'infrastructure/opentelemetry-collector/uralkal/opentelemetry-collector.yaml').read_text())['spec']['values']['alternateConfig'] config={'receivers':{'otlp':{'protocols':{'http':{'endpoint':'127.0.0.1:' + str(port)}}}},'processors':{'transform/mask_logs':cfg['processors']['transform/mask_logs']},'exporters':{'file/test':{'path':str(root/'masked.json')}},'service':{'pipelines':{'logs':{'receivers':['otlp'],'processors':['transform/mask_logs'],'exporters':['file/test']}},'telemetry':{'logs':{'level':'warn'},'metrics':{'level':'none'}}}} p=root/'collector-test.yaml';p.write_text(yaml.safe_dump(config,sort_keys=False)) bin=args.collector_bin r=subprocess.run([bin,'validate','--config',str(p)],capture_output=True,text=True);print('validate',r.returncode);print(r.stderr[:3000] if r.returncode else '');assert not r.returncode (root/'masked.json').unlink(missing_ok=True) errors=open(root/'collector-stderr.txt','w') proc=subprocess.Popen([bin,'--config',str(p)],stdout=subprocess.DEVNULL,stderr=errors) try: for i in range(100): if proc.poll() is not None:raise RuntimeError((root/'collector-stderr.txt').read_text()[:3000]) try: with socket.create_connection(('127.0.0.1',port),timeout=.2):break except OSError:time.sleep(.1) def v(x): if isinstance(x,str):return {'stringValue':x} if isinstance(x,dict):return {'kvlistValue':{'values':[{'key':k,'value':v(a)} for k,a in x.items()]}} if isinstance(x,list):return {'arrayValue':{'values':[v(a) for a in x]}} if isinstance(x,int):return {'intValue':str(x)} jwt='a'*24+'.'+'b'*24+'.'+'c'*20 bodies=[ 'healthy-msg password="SYNTH_PWD" token=SYNTH_TOKEN Authorization: Bearer SYNTH_BEARER '+jwt+' https://synthetic-user:SYNTH_URL@local/path', json.dumps({'message':'healthy-json','nested':{'password':'SYNTH_JSON'},'cookie':'SYNTH_COOKIE'}), {'message':'healthy-map','nested':{'client_secret':'SYNTH_MAP'},'token':834891}, ] resource={'service.name':'mask-test','k8s.namespace.name':'synthetic-ns','nested':{'password':'SYNTH_RESOURCE','keep':'visible'},'url':'https://u:SYNTH_RESOURCE_URL@local/path'} attrs={'nested':{'api_key':'SYNTH_ATTR_KEY','keep':'retained'},'cookies':['SYNTH_ARRAY_COOKIE'],'message':'Bearer SYNTH_ATTR_BEARER','count':42} data={'resourceLogs':[{'resource':{'attributes':[{'key':k,'value':v(a)} for k,a in resource.items()]},'scopeLogs':[{'scope':{'name':'offline-mask-test'},'logRecords':[{'timeUnixNano':str(time.time_ns()),'body':v(body),'attributes':[{'key':k,'value':v(a)} for k,a in attrs.items()]} for body in bodies]}]}]} req=urllib.request.Request('http://127.0.0.1:' + str(port) + '/v1/logs',data=json.dumps(data).encode(),headers={'Content-Type':'application/json'},method='POST') with urllib.request.urlopen(req,timeout=10) as response:print('OTLP HTTP',response.status,response.read().decode()) for _ in range(100): if (root/'masked.json').exists() and (root/'masked.json').stat().st_size>0:break time.sleep(.1) finally: proc.terminate();proc.wait(timeout=10);errors.close() text=(root/'masked.json').read_text() for value in ['SYNTH_PWD','SYNTH_TOKEN','SYNTH_BEARER',jwt,'SYNTH_URL','SYNTH_JSON','SYNTH_COOKIE','SYNTH_MAP','834891','SYNTH_RESOURCE','SYNTH_RESOURCE_URL','SYNTH_ATTR_KEY','SYNTH_ARRAY_COOKIE','SYNTH_ATTR_BEARER']: assert value not in text,'Unmasked synthetic value: '+value for value in ['healthy-msg','healthy-json','healthy-map','synthetic-ns','mask-test','visible','retained']: assert value in text,'Lost nonsensitive value: '+value print('Synthetic redaction and metadata preservation: PASS') # Validate the complete gateway/agent configs with only synthetic Kafka credentials/CA. subprocess.run(['openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', str(root / 'synthetic.key'), '-out', str(root / 'synthetic-ca.crt'), '-days', '1', '-subj', '/CN=synthetic-offline-validation'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True) kafka = cfg['exporters']['kafka/traces'] kafka['auth']['sasl']['username'] = 'synthetic' kafka['auth']['sasl']['password'] = 'synthetic' kafka['auth']['tls']['ca_file'] = str(root / 'synthetic-ca.crt') full = root / 'gateway-full.yaml' full.write_text(yaml.safe_dump(cfg, sort_keys=False)) env = dict(os.environ, MY_POD_IP='127.0.0.1', CONTOUR='uralkal', KAFKA_BROKERS='127.0.0.1:19092', S3_BUCKET='service-logs', S3_ENDPOINT='http://127.0.0.1:19000') for path in [full, repo / 'infrastructure/opentelemetry-agent/base/collector.yaml']: subprocess.run([bin, 'validate', '--config', str(path)], env=env, check=True) vector = yaml.safe_load((repo / 'infrastructure/vector/base/vector.yaml').read_text()) vector['data_dir'] = str(root / 'vector-data') (root / 'vector-data').mkdir() vector['sinks']['minio_logs']['batch_encoding']['schema_file'] = str(repo / 'infrastructure/vector/base/logs.schema') credentials = root / 'synthetic-aws-credentials' credentials.write_text('[default]\naws_access_key_id = synthetic\naws_secret_access_key = synthetic\n') credentials.chmod(0o600) vector['sinks']['minio_logs']['auth']['credentials_file'] = str(credentials) vector['tests'] = yaml.safe_load((repo / 'ci/security/service-log-vector-tests.yaml').read_text())['tests'] path = root / 'vector-check.yaml' path.write_text(yaml.safe_dump(vector, sort_keys=False)) subprocess.run([args.vector_bin, 'validate', '--skip-healthchecks', str(path)], env=env, check=True) subprocess.run([args.vector_bin, 'test', str(path)], env=env, check=True) # Exercise the actual pod argv, stopping at a deliberately missing config before any listeners/sinks start. statefulset = next(d for d in yaml.safe_load_all((repo / 'infrastructure/vector/base/statefulset.yaml').read_text()) if d.get('kind') == 'StatefulSet') container = next(c for c in statefulset['spec']['template']['spec']['containers'] if c['name'] == 'vector') startup_args = list(container['args']) missing_config = root / 'missing-vector-startup-config.yaml' startup_args[startup_args.index('--config') + 1] = str(missing_config) startup = subprocess.run([args.vector_bin, *startup_args], env=env, text=True, capture_output=True, timeout=10) assert startup.returncode != 0 and str(missing_config) in startup.stdout + startup.stderr, \ 'Vector pod arguments were rejected before config loading: ' + startup.stdout + startup.stderr print('Vector pod CLI arguments accepted') temporary.cleanup() print('All local service-log checks passed. Live MinIO/Vault/registry delivery is not tested.')