Files
mtusi2026lab7/src/secret_agent.py
T

75 lines
2.8 KiB
Python

"""Cert-authenticated, finite-lease child supervisor; no stored Bao token.
An unavailable/sealed Bao is tolerated only until the last authenticated lease
expires. Secret changes restart the child, dropping old pooled connections.
"""
import json
import os
import signal
import ssl
import subprocess
import sys
import time
import urllib.request
def fetch():
ctx=ssl.create_default_context(cafile='/trust/bundle.pem')
ctx.minimum_version=ssl.TLSVersion.TLSv1_2
ctx.load_cert_chain('/identity/cert.pem','/identity/key.pem')
ctx.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF
def request(path,body=None,token=None):
headers={'Content-Type':'application/json'}
if token: headers['X-Vault-Token']=token
r=urllib.request.Request('https://openbao:8200/v1/'+path,
data=json.dumps(body).encode() if body is not None else None,headers=headers)
with urllib.request.urlopen(r,context=ctx,timeout=4) as response: return json.load(response)
role=os.environ['SERVICE_ROLE']
auth=request('auth/cert/login',{'name':role})['auth']
try:
data=request('secret/data/'+role,token=auth['client_token'])['data']['data']
return data,min(120,int(auth['lease_duration']))
finally:
# The secret validity budget is local and bounded; no orphaned tokens.
try: request('auth/token/revoke-self',{},auth['client_token'])
except Exception: pass
def main():
child=None; stopping=False; expires=0; current=None
def stop(*_):
nonlocal stopping
stopping=True
for sig in (signal.SIGTERM,signal.SIGINT): signal.signal(sig,stop)
def terminate():
nonlocal child
if child and child.poll() is None:
child.terminate()
try: child.wait(timeout=8)
except subprocess.TimeoutExpired: child.kill(); child.wait()
child=None
try:
while not stopping:
try:
data,ttl=fetch()
if data!=current: terminate(); current=data
expires=time.monotonic()+ttl
if child is None:
child=subprocess.Popen(sys.argv[1:],env={**os.environ,**{k:str(v) for k,v in data.items()}})
elif child.poll() is not None:
# Restart the child, not its container/network namespace:
# the paired TLS sidecar shares that namespace.
print('{"event":"supervised_child_exited"}',flush=True)
child=None
except Exception:
print('{"event":"secret_refresh_unavailable"}',flush=True)
if time.monotonic()>=expires: terminate(); current=None
for _ in range(20):
if stopping: break
time.sleep(1)
finally: terminate()
return 0
if __name__=='__main__': sys.exit(main())