103 lines
4.8 KiB
Python
103 lines
4.8 KiB
Python
"""Bounded credential agent + local TLS transport boundary; no secret logging."""
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import signal
|
|
import ssl
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
ROLE=os.getenv('SERVICE_ROLE','api')
|
|
IDENTITY=Path('/run/identity')
|
|
STOP=threading.Event()
|
|
|
|
|
|
class BaoClient:
|
|
def __init__(self):self.token=None;self.until=0;self.renewals=0;self.logins=0;self.created=0;self.context=None;self.identity=None
|
|
def call(self,path,data=None,token=False):
|
|
fingerprint=cert_fingerprint()
|
|
if self.context is None or self.identity!=fingerprint:
|
|
self.context=ssl.create_default_context(cafile='/run/trust/ca.crt');self.context.load_cert_chain(str(IDENTITY/'service.pem'));self.identity=fingerprint
|
|
context=self.context
|
|
headers={'Content-Type':'application/json'}
|
|
if token:headers['X-Vault-Token']=self.token
|
|
req=urllib.request.Request(os.getenv('BAO_ADDR','https://openbao:8200')+'/v1/'+path,
|
|
data=json.dumps(data).encode() if data is not None else None,headers=headers)
|
|
with urllib.request.urlopen(req,context=context,timeout=5) as r:
|
|
raw=r.read();return json.loads(raw) if raw else {}
|
|
def get(self):
|
|
now=time.monotonic()
|
|
if not self.token or now-self.created>=50:
|
|
auth=self.call('auth/cert/login',{'name':ROLE})['auth']
|
|
self.token=auth['client_token'];self.until=now+auth['lease_duration'];self.created=now;self.logins+=1
|
|
elif self.until-now<12:
|
|
auth=self.call('auth/token/renew-self',{'increment':30},token=True)['auth']
|
|
self.until=now+auth['lease_duration'];self.renewals+=1
|
|
try:return self.call('secret/data/'+ROLE,token=True)['data']['data']
|
|
except Exception:
|
|
self.token=None;raise
|
|
|
|
|
|
def cert_fingerprint():return hashlib.sha256((IDENTITY/'service.pem').read_bytes()).hexdigest()
|
|
|
|
def valid_leaf():
|
|
p=subprocess.run(['openssl','x509','-in',str(IDENTITY/'service.crt'),'-checkend','0','-noout'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
|
return p.returncode==0
|
|
|
|
def stop_child(child):
|
|
if child and child.poll() is None:
|
|
child.terminate()
|
|
try:child.wait(timeout=5)
|
|
except subprocess.TimeoutExpired:child.kill();child.wait()
|
|
|
|
|
|
def main():
|
|
for sig in (signal.SIGTERM,signal.SIGINT):signal.signal(sig,lambda *_:STOP.set())
|
|
proxy=subprocess.Popen(['haproxy','-W','-db','-f','/run/mesh.cfg'],stdout=subprocess.DEVNULL)
|
|
def reload_proxy(*_):
|
|
if proxy.poll() is None:proxy.send_signal(signal.SIGUSR2)
|
|
signal.signal(signal.SIGUSR2,reload_proxy)
|
|
child=None;client=BaoClient();last=None;failures=0;blocked=0;last_error=None
|
|
try:
|
|
if ROLE=='operator':
|
|
time.sleep(.5)
|
|
values=json.loads(Path('/run/operator-env.json').read_text())
|
|
os.environ.update({k:v if isinstance(v,str) else json.dumps(v) for k,v in values.items()})
|
|
args=sys.argv[2:] or ['python','scripts/provision.py']
|
|
return subprocess.call(args)
|
|
while not STOP.is_set():
|
|
try:
|
|
if proxy.poll() is not None:
|
|
stop_child(child);child=None;last=None
|
|
proxy=subprocess.Popen(['haproxy','-W','-db','-f','/run/mesh.cfg'],stdout=subprocess.DEVNULL)
|
|
STOP.wait(.5)
|
|
if proxy.poll() is not None:raise RuntimeError('transport stopped')
|
|
if not valid_leaf():raise RuntimeError('identity expired')
|
|
values=client.get();fingerprint=(values,cert_fingerprint())
|
|
if fingerprint!=last or child is None or child.poll() is not None:
|
|
stop_child(child)
|
|
if last is not None:reload_proxy()
|
|
env=os.environ.copy();env.update(values)
|
|
command=['uvicorn','app:app','--host','127.0.0.1','--port','8080','--no-access-log','--timeout-graceful-shutdown','3'] if ROLE=='api' else ['python',sys.argv[1]]
|
|
child=subprocess.Popen(command,env=env);last=fingerprint
|
|
failures=0;last_error=None
|
|
except Exception as exc:
|
|
last_error=type(exc).__name__
|
|
client.token=None
|
|
failures+=1
|
|
if failures>=3:
|
|
stop_child(child);child=None;blocked+=1
|
|
Path('/tmp/agent-status.json').write_text(json.dumps({'role':ROLE,'renewals':client.renewals,'logins':client.logins,
|
|
'last_error_type':last_error,'consecutive_failures':failures,'blocked_events':blocked,'child_running':child is not None and child.poll() is None}))
|
|
STOP.wait(5)
|
|
return 0
|
|
finally:stop_child(child);stop_child(proxy)
|
|
|
|
|
|
if __name__=='__main__':raise SystemExit(main())
|