#!/usr/bin/env python3 """Idempotent local lab7 bootstrap. Never prints secrets or modifies lab6.""" import json, os, secrets, shutil, subprocess from pathlib import Path ROOT=Path(__file__).resolve().parents[1]; S=ROOT/'secrets/lab7'; O=S/'operator' def run(*args): subprocess.run(args,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE) def secret(name): p=O/name if not p.exists(): p.write_text(secrets.token_hex(24)) p.chmod(0o600);return p.read_text().strip() def issue(role,days=1,cn=None): d=S/role;d.mkdir(exist_ok=True) if not (d/'tls.crt').exists() or (d/'tls.crt').stat().st_size==0: run('openssl','req','-new','-newkey','rsa:2048','-nodes','-keyout',str(d/'tls.key'),'-out',str(O/'request.csr'),'-subj','/CN='+(cn or role)) ext=O/'leaf.ext';ext.write_text('[leaf]\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName=DNS:'+role+(',DNS:localhost,IP:127.0.0.1' if role in ('lb','openbao','grafana') else '')+'\n') run('openssl','ca','-batch','-config',str(O/'ca.cnf'),'-extensions','leaf','-extfile',str(ext),'-days',str(days),'-in',str(O/'request.csr'),'-out',str(d/'tls.crt'),'-notext') for f in ['ca.crt','ca.crl']: temporary=d/(f+'.tmp');shutil.copyfile(O/f,temporary);temporary.replace(d/f) # The directory is the security boundary; only this identity directory is mounted in its container. d.chmod(0o755) return d def main(): os.umask(0o077);S.mkdir(parents=True,exist_ok=True);O.mkdir(exist_ok=True);O.chmod(0o700) for p in S.rglob('*'): if p.is_file():p.chmod(0o600) for f,value in [('index.txt',''),('serial','1000\n'),('crlnumber','1000\n')]: if not (O/f).exists():(O/f).write_text(value) (O/'newcerts').mkdir(exist_ok=True) (O/'ca.cnf').write_text(f'''[ca] default_ca=local [local] dir={O} database=$dir/index.txt new_certs_dir=$dir/newcerts certificate=$dir/ca.crt private_key=$dir/ca.key serial=$dir/serial crlnumber=$dir/crlnumber default_md=sha256 default_days=1 default_crl_days=1 unique_subject=no policy=policy [policy] commonName=supplied [leaf] ''') if not (O/'ca.key').exists():run('openssl','req','-x509','-newkey','rsa:3072','-nodes','-days','365','-keyout',str(O/'ca.key'),'-out',str(O/'ca.crt'),'-subj','/CN=lab7-local-ca','-addext','basicConstraints=critical,CA:TRUE','-addext','keyUsage=critical,keyCertSign,cRLSign') run('openssl','ca','-config',str(O/'ca.cnf'),'-gencrl','-out',str(O/'ca.crl')) roles=['lb','api','worker','dispatcher','postgres','redis','broker','s3','otel-collector','prometheus','loki','tempo','grafana','openbao','operator-client','stranger'] for role in roles:issue(role) if not (S/'api/jwt.key').exists(): run('openssl','genrsa','-out',str(S/'api/jwt.key'),'2048');run('openssl','rsa','-in',str(S/'api/jwt.key'),'-pubout','-out',str(S/'api/jwt.pub')) for p in (S/'api').glob('jwt.*'):p.chmod(0o444) for name in ['db_password','bao_db_password','redis_password','grafana_password','s3_admin_access','s3_admin_secret','s3_api_access','s3_api_secret','s3_worker_access','s3_worker_secret','s3_baseline_access','s3_baseline_secret']:secret(name) bucket='messenger-attachments' identities=[] for role,actions in [('baseline',[f'Read:{bucket}',f'Write:{bucket}',f'List:{bucket}']),('admin',['Admin']),('api',[f'Read:{bucket}/results/*',f'Read:{bucket}/originals/*',f'Write:{bucket}/staging/*',f'Read:{bucket}']),('worker',[f'Read:{bucket}/staging/*',f'Write:{bucket}/staging/*',f'Read:{bucket}/results/*',f'Write:{bucket}/results/*',f'Read:{bucket}'])]: # Bucket-scoped Read also permits arbitrary object reads; do not grant it. HeadBucket is handled by health prefix probes instead. if role not in ['admin','baseline']:actions=[a for a in actions if a!=f'Read:{bucket}'] identities.append({'name':role,'credentials':[{'accessKey':secret('s3_'+role+'_access'),'secretKey':secret('s3_'+role+'_secret')}],'actions':actions}) (S/'s3/s3.json').write_text(json.dumps({'identities':identities}));(S/'s3/s3.json').chmod(0o444) (S/'postgres/password').write_text(secret('db_password'));(S/'postgres/password').chmod(0o444) (S/'postgres/init.sql').write_text("CREATE ROLE bao_manager WITH LOGIN CREATEROLE PASSWORD '"+secret('bao_db_password')+"';\nCREATE ROLE api_role NOLOGIN; CREATE ROLE worker_role NOLOGIN; CREATE ROLE dispatcher_role NOLOGIN;\nGRANT api_role,worker_role,dispatcher_role TO bao_manager WITH ADMIN OPTION;\nGRANT pg_signal_backend TO bao_manager;\n") (S/'postgres/init.sql').chmod(0o444) (S/'redis/users.acl').write_text('user default off\nuser api on >'+secret('redis_password')+' ~ratelimit:* ~chat:* ~chats:* +@read +@write +ping +evalsha +eval +script|load +script|exists -flushall -flushdb -config -acl\n');(S/'redis/users.acl').chmod(0o444) (S/'grafana/password').write_text(secret('grafana_password'));(S/'grafana/password').chmod(0o444) for role in ('api','worker','dispatcher','operator-client'): (S/role/'broker_url').write_text('amqps://broker:5671/attachments');(S/role/'broker_url').chmod(0o444) (S/'lb/bundle.pem').write_text((S/'lb/tls.crt').read_text()+(S/'lb/tls.key').read_text());(S/'lb/bundle.pem').chmod(0o444) for name in ['s3_admin_access','s3_admin_secret','s3_baseline_access','s3_baseline_secret']: (S/'operator-client'/name).write_text(secret(name));(S/'operator-client'/name).chmod(0o444) # Provisioning contains the Grafana client private key, so it is generated outside Git. sources=[] for name in ['prometheus','loki','tempo']: sources.append({'name':name.title(),'uid':name,'type':name,'url':'https://'+name+':9443','access':'proxy','isDefault':name=='prometheus','jsonData':{'tlsAuth':True,'tlsAuthWithCACert':True,'serverName':name,'timeInterval':'5s'},'secureJsonData':{'tlsCACert':(O/'ca.crt').read_text(),'tlsClientCert':(S/'grafana/tls.crt').read_text(),'tlsClientKey':(S/'grafana/tls.key').read_text()}}) (S/'grafana/datasources.yaml').write_text(json.dumps({'apiVersion':1,'datasources':sources},indent=2)) for role in roles: for p in (S/role).iterdir():p.chmod(0o444) definitions=json.loads((ROOT/'infra/rabbitmq/definitions.json').read_text()) cn=subprocess.check_output(['openssl','x509','-in',str(S/'worker/tls.crt'),'-noout','-subject','-nameopt','RFC2253'],text=True).strip().split('CN=')[-1] for user in definitions['users']: if user['name']=='worker':user['name']=cn for permission in definitions['permissions']: if permission['user']=='worker':permission['user']=cn (S/'broker/definitions.json').chmod(0o600) if (S/'broker/definitions.json').exists() else None (S/'broker/definitions.json').write_text(json.dumps(definitions));(S/'broker/definitions.json').chmod(0o444) foreign=S/'foreign';foreign.mkdir(exist_ok=True);foreign.chmod(0o755) if not (foreign/'tls.crt').exists(): run('openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','1','-keyout',str(foreign/'tls.key'),'-out',str(foreign/'tls.crt'),'-subj','/CN=foreign','-addext','subjectAltName=DNS:foreign') (foreign/'ca.crt').chmod(0o600) if (foreign/'ca.crt').exists() else None shutil.copyfile(O/'ca.crt',foreign/'ca.crt') for p in foreign.iterdir():p.chmod(0o444) print('Local lab7 CA, identities and synthetic secrets prepared. No credentials printed.') if __name__=='__main__':main()