import json import os from pathlib import Path import subprocess import sys import time sys.path.insert(0,str(Path(__file__).resolve().parents[1])) from scripts import provision as p def compose(*args, input=None): result=subprocess.run(['docker','compose','--project-name',p.PROJECT,'--env-file','.env',*args], cwd=p.ROOT,input=input,text=True,capture_output=True,encoding='utf-8') if result.returncode: raise RuntimeError('Operator command failed: ' + ' '.join(args[:3])) return result.stdout def sql(statement): return compose('exec','-T','db','psql','-U','messenger','-d','messenger','-v','ON_ERROR_STOP=1','-At','-f','-',input=statement) def grants(): v=p.values() statement='' for role in ('api','worker','cleanup'): statement+=f"DO $$ BEGIN CREATE ROLE {role} LOGIN; EXCEPTION WHEN duplicate_object THEN NULL; END $$; ALTER ROLE {role} PASSWORD '{v[role+'_db']}';\n" statement+='REVOKE ALL ON SCHEMA public FROM PUBLIC; GRANT USAGE ON SCHEMA public TO api,worker,cleanup;\n' statement+='GRANT SELECT ON ALL TABLES IN SCHEMA public TO api;\n' statement+='GRANT INSERT ON users,chats,chat_members,messages,message_attachments,sessions,idempotency_keys,attachments,attachment_jobs,upload_intents TO api;\n' statement+='GRANT DELETE ON sessions,idempotency_keys,upload_intents TO api; GRANT UPDATE ON upload_intents TO api; GRANT UPDATE(published_at) ON attachment_jobs TO api;\n' statement+='GRANT SELECT ON attachments,attachment_jobs,attachment_variants,schema_migrations TO worker; GRANT INSERT,UPDATE ON attachment_variants TO worker;\n' statement+='GRANT UPDATE(status,error_code,updated_at) ON attachments TO worker; GRANT UPDATE(attempt,next_attempt_at) ON attachment_jobs TO worker;\n' statement+='GRANT SELECT ON attachments,attachment_jobs,upload_intents,schema_migrations TO cleanup; GRANT UPDATE,DELETE ON upload_intents TO cleanup; GRANT UPDATE(status,error_code,updated_at,staging_deleted) ON attachments TO cleanup;\n' sql(statement) print('PASS: separate database roles configured') def main(): action=sys.argv[1] if action=='setup': p.pki();p.configuration() print('Local PKI/configuration ready; operator profile encrypted outside repository') elif action=='bao-bootstrap': deadline=time.monotonic()+90 while True: try: p.bao_request('sys/init');break except Exception: if time.monotonic()>deadline:raise RuntimeError('OpenBao TLS startup timeout') from None time.sleep(1) p.bootstrap_bao();print('PASS: OpenBao initialized/unsealed, cert auth and scoped policies configured') elif action=='pki-renew': p.pki(renew=True);p.configuration();state=p.operator_load();state['renew_roles']=True;p.operator_save(state) print('Leaf certificates reissued; CA and application data preserved') elif action=='grants': grants() elif action=='bao-unseal': p.unseal();print('OpenBao unsealed') elif action=='bao-status': status=p.bao_request('sys/seal-status');print(json.dumps({k:status[k] for k in ('sealed','initialized','type')})) if __name__=='__main__': main()