Files
mtusi2026lab7/scripts/bootstrap.py
T

82 lines
4.8 KiB
Python

"""Generate isolated local credentials. Operator files are never app mounts."""
import json
from pathlib import Path
import secrets
import csv
import os
import subprocess
from datetime import datetime,timedelta,timezone
import pki
ROOT=Path(__file__).resolve().parents[1]
ROLES=['api1','api2','worker','dispatcher','reconciler']
def protect_local_files():
directory=ROOT/'secrets';directory.mkdir(exist_ok=True)
directory.chmod(0o700)
if os.name=='nt':
sid=next(csv.reader(subprocess.check_output(['whoami','/user','/fo','csv','/nh'],text=True).splitlines()))[1]
for path in (directory,ROOT/'.env',ROOT/'.env.storage-admin'):
if not path.exists():continue
flags='(OI)(CI)' if path.is_dir() else ''
result=subprocess.run(['icacls',str(path),'/inheritance:r','/grant:r',
'*'+sid+':'+flags+'F','*S-1-5-18:'+flags+'F','*S-1-5-32-544:'+flags+'F'],capture_output=True)
if result.returncode:raise RuntimeError('Could not restrict local secret ACLs')
def main():
protect_local_files()
pki.init()
pki.crl()
for role in ROLES+['db','s3','broker','cache','otel-collector','prometheus','loki','tempo','grafana','lb','openbao','operator','outsider']:
cert_path=ROOT/'secrets/identities'/role/'cert.pem'
if (not cert_path.exists() or pki.x509.load_pem_x509_certificate(cert_path.read_bytes()).not_valid_after_utc
< datetime.now(timezone.utc)+timedelta(hours=2)):
pki.issue(role)
target=ROOT/'secrets/operator/config.json'
if target.exists():
print('Existing local credentials preserved');return
password=secrets.token_hex(24)
db={role:secrets.token_hex(24) for role in ROLES}
broker={role:secrets.token_hex(24) for role in ('worker','dispatcher')}
cache={role:secrets.token_hex(24) for role in ('api1','api2')}
s3={role:(secrets.token_hex(12),secrets.token_hex(32)) for role in ROLES+['admin'] if role!='dispatcher'}
cursor=secrets.token_hex(32)
credentials={}
for role in ROLES:
credentials[role]={'DATABASE_URL':f'postgresql://{role}:{db[role]}@127.0.0.1:5432/messenger',
'CURSOR_SECRET':cursor,
'OTEL_EXPORTER_OTLP_ENDPOINT':'http://127.0.0.1:4318','TELEMETRY_ENABLED':'1','SESSION_TTL_SECONDS':'3600'}
if role in s3:
credentials[role].update({'S3_ENDPOINT':'http://127.0.0.1:8333','S3_BUCKET':'messenger',
'S3_ACCESS_KEY':s3[role][0],'S3_SECRET_KEY':s3[role][1]})
if role in cache: credentials[role]['REDIS_URL']=f'redis://{role}:{cache[role]}@127.0.0.1:6379/0'
if role in broker: credentials[role]['BROKER_URL']=f'redis://{role}:{broker[role]}@127.0.0.1:6380/0'
identities=[]
for role,(key,secret) in s3.items():
if role=='admin':actions=['Admin','Read','Write','List','Tagging']
elif role.startswith('api'):actions=['Read:messenger/originals/*','Read:messenger/variants/*','Write:messenger/staging/*']
else:
actions=['Read:messenger/staging/*','Read:messenger/originals/*','Read:messenger/variants/*','Write:messenger/staging/*','Write:messenger/originals/*','Write:messenger/variants/*']
if role=='reconciler':actions.append('List:messenger')
identities.append({'name':role,'credentials':[{'accessKey':key,'secretKey':secret}],'actions':actions})
files={'.env':'POSTGRES_PASSWORD='+password+'\n',
'.env.storage-admin':f'S3_ENDPOINT=http://127.0.0.1:8333\nS3_BUCKET=messenger\nS3_ACCESS_KEY={s3["admin"][0]}\nS3_SECRET_KEY={s3["admin"][1]}\n',
'secrets/s3.json':json.dumps({'identities':identities},indent=2),
'secrets/grafana-password':secrets.token_urlsafe(24)+'\n',
'secrets/cache.conf':'bind 127.0.0.1\nprotected-mode yes\nmaxmemory 32mb\nmaxmemory-policy allkeys-lru\nsave ""\nuser default off\n'+''.join(f'user {r} on >{v} ~user:* -@all +get +set +ping +hello +client|setinfo\n' for r,v in cache.items()),
'secrets/broker.conf':'bind 127.0.0.1\nprotected-mode yes\nappendonly yes\nappendfsync always\ndir /data\nsave ""\nmaxmemory 64mb\nmaxmemory-policy noeviction\nuser default off\n'+
f'user dispatcher on >{broker["dispatcher"]} ~attachment-jobs -@all +xadd +xgroup +ping +hello +client|setinfo\n'+
f'user worker on >{broker["worker"]} ~attachment-jobs -@all +xgroup +xautoclaim +xreadgroup +xack +xdel +multi +exec +ping +hello +client|setinfo\n',
'secrets/operator/config.json':json.dumps({'database_passwords':db,'service_credentials':credentials},indent=2)}
for name,value in files.items():
p=ROOT/name;p.parent.mkdir(parents=True,exist_ok=True)
with p.open('x',encoding='utf-8',newline='\n') as f:f.write(value)
p.chmod(0o600)
protect_local_files()
print('Generated separate identities and local secrets; values not printed')
if __name__=='__main__':main()