#!/usr/bin/env python3 """Create ignored local PKI/secrets, initialize OpenBao, and start the grade-3 stack.""" import json import os from pathlib import Path import secrets import shutil import socket import ssl import subprocess import time import urllib.error import urllib.request ROOT=Path(__file__).resolve().parents[1] LOCAL=ROOT/'.local' PKI=LOCAL/'pki' BAO=LOCAL/'openbao' ROLES=LOCAL/'approles' ENV=ROOT/'.env' def run(*args,stdout=None): return subprocess.run(args,cwd=ROOT,check=True,stdout=stdout) def write(path,data,mode=0o600): path.parent.mkdir(parents=True,exist_ok=True) path.write_text(data,encoding='utf-8') path.chmod(mode) def make_env(): required={'POSTGRES_ADMIN_PASSWORD','POSTGRES_API_PASSWORD','POSTGRES_WORKER_PASSWORD', 'S3_API_ACCESS_KEY','S3_API_SECRET_KEY','S3_WORKER_ACCESS_KEY','S3_WORKER_SECRET_KEY', 'S3_ADMIN_ACCESS_KEY','S3_ADMIN_SECRET_KEY','RABBIT_ADMIN_USER','RABBIT_ADMIN_PASSWORD', 'RABBIT_API_USER','RABBIT_API_PASSWORD','RABBIT_WORKER_USER','RABBIT_WORKER_PASSWORD','GRAFANA_PASSWORD'} if ENV.exists(): existing=env_values() if required <= set(existing) and all(existing[k] and 'CHANGE_ME' not in existing[k] for k in required): return values={ 'PUBLIC_PORT':'8443','POSTGRES_ADMIN_PASSWORD':secrets.token_hex(32), 'POSTGRES_API_PASSWORD':secrets.token_hex(32),'POSTGRES_WORKER_PASSWORD':secrets.token_hex(32), 'S3_API_ACCESS_KEY':secrets.token_hex(12),'S3_API_SECRET_KEY':secrets.token_hex(32), 'S3_WORKER_ACCESS_KEY':secrets.token_hex(12),'S3_WORKER_SECRET_KEY':secrets.token_hex(32), 'S3_ADMIN_ACCESS_KEY':secrets.token_hex(12),'S3_ADMIN_SECRET_KEY':secrets.token_hex(32), 'RABBIT_ADMIN_USER':'lab7_operator','RABBIT_ADMIN_PASSWORD':secrets.token_hex(32), 'RABBIT_API_USER':'lab7_api','RABBIT_API_PASSWORD':secrets.token_hex(32), 'RABBIT_WORKER_USER':'lab7_worker','RABBIT_WORKER_PASSWORD':secrets.token_hex(32), 'GRAFANA_PASSWORD':secrets.token_hex(24),'SESSION_TTL_SECONDS':'3600','JOB_MAX_ATTEMPTS':'5' } write(ENV,'\n'.join(k+'='+v for k,v in values.items())+'\n') def env_values(): result={} for line in ENV.read_text().splitlines(): if line and not line.startswith('#') and '=' in line: k,v=line.split('=',1); result[k]=v return result def openssl(*args): subprocess.run(['openssl',*map(str,args)],cwd=ROOT,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) def create_ca(name): key=PKI/(name+'.key'); cert=PKI/(name+'.crt') if cert.exists() and key.exists(): return cert,key openssl('genpkey','-algorithm','RSA','-pkeyopt','rsa_keygen_bits:3072','-out',key) openssl('req','-x509','-new','-key',key,'-sha256','-days','825','-subj','/CN='+name, '-addext','basicConstraints=critical,CA:TRUE','-addext','keyUsage=critical,keyCertSign,cRLSign','-out',cert) key.chmod(0o600); cert.chmod(0o644) return cert,key def issue(name,ca_name,dns=(),ips=(),uris=()): cert=PKI/(name+'.crt'); key=PKI/(name+'.key') if cert.exists() and key.exists(): return cert,key ca_cert=PKI/(ca_name+'.crt'); ca_key=PKI/(ca_name+'.key') csr=PKI/(name+'.csr'); ext=PKI/(name+'.ext') openssl('genpkey','-algorithm','RSA','-pkeyopt','rsa_keygen_bits:2048','-out',key) openssl('req','-new','-key',key,'-subj','/CN='+name,'-out',csr) sans=[] sans.extend('DNS:'+x for x in dns); sans.extend('IP:'+x for x in ips); sans.extend('URI:'+x for x in uris) lines=['basicConstraints=critical,CA:FALSE','keyUsage=critical,digitalSignature,keyEncipherment','extendedKeyUsage=serverAuth,clientAuth'] if sans: lines.append('subjectAltName='+','.join(sans)) write(ext,'\n'.join(lines)+'\n',0o600) openssl('x509','-req','-in',csr,'-CA',ca_cert,'-CAkey',ca_key,'-CAcreateserial','-out',cert,'-days','90','-sha256','-extfile',ext) key.chmod(0o644); cert.chmod(0o644); csr.unlink(missing_ok=True); ext.unlink(missing_ok=True) return cert,key def create_pki(): PKI.mkdir(parents=True,exist_ok=True); PKI.chmod(0o700) create_ca('external-ca'); create_ca('service-ca'); create_ca('lb-client-ca') create_ca('otel-ingest-ca'); create_ca('backend-client-ca') issue('ingress','external-ca',dns=['localhost'],ips=['127.0.0.1']) issue('api','service-ca',dns=['api1','api2','localhost']) issue('postgres','service-ca',dns=['postgres']) issue('s3','service-ca',dns=['s3']) issue('broker','service-ca',dns=['broker']) issue('openbao','service-ca',dns=['openbao','localhost'],ips=['127.0.0.1']) for name in ('otel-collector','prometheus','loki','tempo','grafana'): names=[name] ips=[] if name in ('prometheus','loki','tempo','grafana'): names.append('localhost'); ips=['127.0.0.1'] issue(name,'service-ca',dns=names,ips=ips) issue('lb-client','lb-client-ca',uris=['spiffe://mtusi2026/lab7/load-balancer']) issue('foreign-client','lb-client-ca',uris=['spiffe://mtusi2026/lab7/unapproved']) issue('untrusted-client','service-ca',uris=['spiffe://mtusi2026/lab7/untrusted']) issue('otel-api-client','otel-ingest-ca',uris=['spiffe://mtusi2026/lab7/api']) issue('otel-worker-client','otel-ingest-ca',uris=['spiffe://mtusi2026/lab7/worker']) issue('backend-collector','backend-client-ca',uris=['spiffe://mtusi2026/lab7/otel-collector']) issue('backend-grafana','backend-client-ca',uris=['spiffe://mtusi2026/lab7/grafana']) for name in ('ingress','lb-client'): cert,key=PKI/(name+'.crt'),PKI/(name+'.key') write(PKI/(name+'.pem'),cert.read_text()+key.read_text(),0o600) def create_s3_config(env): def identity(name,access,secret,actions): return {'name':name,'credentials':[{'accessKey':env[access],'secretKey':env[secret]}],'actions':actions} staging='attachments-staging'; original='attachments-original'; variants='attachments-variants' config={'identities':[ identity('api','S3_API_ACCESS_KEY','S3_API_SECRET_KEY', ['List:'+staging,'Write:'+staging,'List:'+original,'Read:'+original,'List:'+variants,'Read:'+variants]), identity('worker','S3_WORKER_ACCESS_KEY','S3_WORKER_SECRET_KEY', ['Read:'+staging,'Write:'+staging,'Write:'+original,'Write:'+variants]), identity('operator','S3_ADMIN_ACCESS_KEY','S3_ADMIN_SECRET_KEY', ['Admin:'+staging,'Admin:'+original,'Admin:'+variants]) ]} write(LOCAL/'s3.json',json.dumps(config,indent=2)+'\n') def parse_body(error): try: return json.loads(error.read().decode()) except Exception: return {} def bao_request(path,method='GET',body=None,token=None): context=ssl.create_default_context(cafile=str(PKI/'service-ca.crt')) data=None if body is None else json.dumps(body).encode() req=urllib.request.Request('https://localhost:8207/v1/'+path,data=data,method=method) req.add_header('Content-Type','application/json') if token: req.add_header('X-Vault-Token',token) try: with urllib.request.urlopen(req,context=context,timeout=5) as response: data=response.read() return response.status,json.loads(data) if data else {} except urllib.error.HTTPError as exc: return exc.code,parse_body(exc) def wait_openbao(): deadline=time.time()+90 while time.time()