"""Explicit operator revocation/rollover; no image rebuild and no root credential in apps.""" import json from pathlib import Path import secrets import shutil import subprocess import time import ssl import urllib.request import urllib.error from pki import ROOT,issue from bootstrap import main as bootstrap from bao_operator import URL,call,unseal,configure def dc(*a,**kw):return subprocess.run(['docker','compose',*a],cwd=ROOT,check=True,**kw) def run(): started=time.monotonic() dc('stop','worker') old=ROOT/'pki/revoked-worker';old.mkdir(exist_ok=True) for file in (ROOT/'pki/worker').iterdir(): if file.is_file():shutil.copyfile(file,old/file.name) # Exact cert serial is public correlation data; keys and passwords remain local. serial=subprocess.check_output(['openssl','x509','-in',str(old/'tls.crt'),'-serial','-noout'],text=True).strip().split('=')[1] settings=json.loads((ROOT/'operator/settings.json').read_text()) oldfile=ROOT/'operator/revoked-worker-settings.json';oldfile.write_text(json.dumps(settings));oldfile.chmod(0o600) root=unseal() def old_service(path,data=None,token=None): ctx=ssl.create_default_context(cafile=str(ROOT/'pki/worker/ca.crt')) ctx.load_cert_chain(str(ROOT/'pki/worker/tls.crt'),str(ROOT/'pki/worker/tls.key')) headers={'Content-Type':'application/json'} if token:headers['X-Vault-Token']=token req=urllib.request.Request(URL+'/v1/'+path, data=None if data is None else json.dumps(data).encode(),headers=headers) op=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx)) with op.open(req,timeout=5) as response:return json.load(response) auth=old_service('auth/cert/login',{'name':'worker'})['auth'] old_token=auth['client_token'] assert old_service('secret/data/worker',token=old_token)['data']['data'] token_created=time.monotonic() call('auth/cert/certs/worker',token=root,method='DELETE') # Revoke all outstanding worker tokens instead of assuming deleting a role revokes tokens. revoked_tokens=0 try:accessors=call('auth/token/accessors',token=root,method='LIST')['data']['keys'] except Exception:accessors=[] for accessor in accessors: try: info=call('auth/token/lookup-accessor',{'accessor':accessor},root) if 'worker' in info['data']['policies']: call('auth/token/revoke-accessor',{'accessor':accessor},root);revoked_tokens+=1 except Exception:pass # An already-expired token is not still usable. try:old_service('secret/data/worker',token=old_token) except urllib.error.HTTPError as error:assert error.code==403 else:raise AssertionError('Outstanding worker token still reads secrets after revocation') revoke_latency=time.monotonic()-token_created assert revoke_latency < auth['lease_duration']-1, 'Prove revocation before natural token expiry' for folder in (ROOT/'pki').iterdir(): listing=folder/'revoked.list' if listing.exists() and folder.name!='revoked-worker': rows=set(listing.read_text().splitlines());rows.add(serial.lower());listing.write_text('\n'.join(sorted(rows))+'\n') for proxy in ['broker','s3','otel-collector']: dc('kill','-s','SIGUSR2',proxy) settings['worker']=secrets.token_hex(24) settings['broker_worker']=secrets.token_hex(24) settings['s3_worker']=secrets.token_hex(24) settings['s3_worker_key']=secrets.token_hex(12) file=ROOT/'operator/settings.json';file.write_text(json.dumps(settings));file.chmod(0o600) issue('worker') bootstrap() dc('--profile','tools','run','--rm','--no-deps','audit','/app/student-tests/rotation_db.py') # Raw process restart keeps the stable TLS/network boundary and persistent broker/S3 data. dc('restart','broker-raw','s3-raw') configure() dc('up','-d','--no-deps','worker') result={'revoked_certificate_serial':serial,'worker_tokens_revoked':revoked_tokens,'old_valid_token_denied_before_natural_expiry':True,'token_revoke_latency_seconds':round(revoke_latency,3), 'passwords_rotated':['PostgreSQL worker','Redis worker','S3 worker'], 'new_leaf_certificate':True,'proxy_hard_stop_seconds':5,'images_rebuilt':False, 'seconds':round(time.monotonic()-started,3)} (ROOT/'evidence/worker-rotation.json').write_text(json.dumps(result,indent=2)+'\n') print('Worker identity revoked, fresh secrets/certificate installed; no secrets printed.') return result if __name__=='__main__':run()