Files
mtusi2026lab7-fork/student-tests/lifecycle.py

101 lines
5.8 KiB
Python

"""Operator lifecycle checks: rotation, revocation, sealed Bao and token expiry."""
import json,ssl,subprocess,sys,time,urllib.request,urllib.error
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
sys.path[:0]=[str(ROOT/'scripts'),str(ROOT/'tests')]
import bao
from client import Client,check
c=Client('https://localhost:8443',str(ROOT/'secrets/ca/ca.crt'))
a,b,_,chat=c.bootstrap();results={}
def images():
names=['mtusi-lab7-'+x+'-1' for x in ('api-a','api-b','worker')]
rows=json.loads(subprocess.check_output(['docker','inspect',*names],text=True))
return {r['Name']:r['Image'] for r in rows}
def ready():
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca/ca.crt'))
try:
with urllib.request.urlopen('https://localhost:8443/health/ready',context=ctx,timeout=2) as response:return response.status==200
except (OSError,urllib.error.URLError):return False
def wait(function,seconds=80):
deadline=time.monotonic()+seconds
while time.monotonic()<deadline:
if function():return
time.sleep(1)
raise AssertionError('lifecycle deadline')
before=images()
subprocess.run([sys.executable,'scripts/rotate.py','worker-secret'],cwd=ROOT,check=True)
# Verify fresh connections with retired and replacement credentials inside the operator namespace.
code="""
import json,sys,psycopg2
v=json.load(sys.stdin)
try:psycopg2.connect(v['old'])
except psycopg2.OperationalError:pass
else:raise AssertionError('retired DB credential accepted')
conn=psycopg2.connect(v['new']);conn.close();print('PASS')
"""
old=(ROOT/'secrets/operator/previous-worker-dsn').read_text()
new=json.loads((ROOT/'secrets/operator/roles.json').read_text())['worker']['database_url']
subprocess.run(['docker','compose','--profile','operator','run','--rm','--no-deps','migrate','python','-c',code],cwd=ROOT,input=json.dumps({'old':old,'new':new}),text=True,check=True,stdout=subprocess.DEVNULL)
time.sleep(5)
att,_=c.attachment(a,chat);c.wait_ready(b,att)
results['worker_secret_rotation']={'retired_password_denied_new_connection':True,'new_password_works':True,'attachment_ready':True}
subprocess.run([sys.executable,'scripts/rotate.py','api-leaf'],cwd=ROOT,check=True)
time.sleep(5)
wait(ready)
# The old API client certificate was allowed at Collector before revocation.
code="""
from pathlib import Path
import grpc
from opentelemetry.proto.collector.trace.v1.trace_service_pb2_grpc import TraceServiceStub
from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
root=Path('/workspace/secrets')
def probe(folder):
creds=grpc.ssl_channel_credentials((root/'ca/ca.crt').read_bytes(),(folder/'server.key').read_bytes(),(folder/'server.crt').read_bytes())
with grpc.secure_channel('otel-collector:4317',creds) as channel:TraceServiceStub(channel).Export(ExportTraceServiceRequest(),timeout=4)
try:probe(root/'operator/previous-api-a')
except grpc.RpcError:pass
else:raise AssertionError('revoked leaf accepted')
probe(root/'tls/api-a')
print('PASS')
"""
subprocess.run(['docker','compose','--profile','operator','run','--rm','--no-deps','-v',str(ROOT)+':/workspace:ro','migrate','python','-c',code],cwd=ROOT,check=True,stdout=subprocess.DEVNULL)
check(images()==before,'rotation rebuilt/replaced images')
results['leaf_rotation']={'revoked_old_leaf_denied_new_connection':True,'replacement_accepted':True,'images_unchanged':True,'existing_collector_connection_max_age_seconds':60}
# A real service token with 60s TTL is deliberately left without renewal.
def login_api():
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca/ca.crt'))
ctx.load_cert_chain(str(ROOT/'secrets/tls/api-a/server.crt'),str(ROOT/'secrets/tls/api-a/server.key'))
request=urllib.request.Request('https://localhost:18200/v1/auth/cert/login',data=b'{"name":"api"}',headers={'Content-Type':'application/json'})
with urllib.request.urlopen(request,context=ctx,timeout=5) as response:return json.load(response)['auth'],ctx
probe_token,context=login_api();started=time.monotonic()
try:
bao.call('sys/seal',{},bao.root_token())
wait(lambda:not ready(),seconds=75)
unavailable_after=round(time.monotonic()-started,2)
subprocess.run(['docker','compose','restart','api-a'],cwd=ROOT,check=True,stdout=subprocess.DEVNULL)
time.sleep(5)
data=json.loads(subprocess.check_output(['docker','inspect','mtusi-lab7-api-a-1'],text=True))[0]
# A newly restarted API has no usable Bao token and must not open its listener.
probe="import socket; s=socket.socket(); s.settimeout(1); raise SystemExit(0 if s.connect_ex(('127.0.0.1',8080)) else 1)"
subprocess.run(['docker','compose','exec','-T','api-a','python','-c',probe],cwd=ROOT,check=True)
subprocess.run(['docker','compose','restart','openbao'],cwd=ROOT,check=True,stdout=subprocess.DEVNULL)
time.sleep(3)
check(bao.call('sys/seal-status')['sealed'],'OpenBao restart must require operator unseal')
while time.monotonic()-started<65:time.sleep(1)
finally:
bao.unseal()
wait(ready)
request=urllib.request.Request('https://localhost:18200/v1/secret/data/api',headers={'X-Vault-Token':probe_token['client_token']})
try:urllib.request.urlopen(request,context=context,timeout=5)
except urllib.error.HTTPError as error:check(error.code==403,'unexpected expiry result')
else:raise AssertionError('expired service token accepted')
c.call('GET','/api/v1/users/me',actor=a,schema='User')
results['sealed_expiry']={'api_failed_closed_after_seconds':unavailable_after,'restart_while_sealed_opened_no_listener':True,'unrenewed_service_token_expired':True,'recovered_after_operator_unseal':True,'existing_bearer_session_preserved':True,'openbao_restart_preserved_scoped_configuration':True}
(ROOT/'secrets/operator/previous-worker-dsn').unlink(missing_ok=True)
(ROOT/'evidence/lifecycle.json').write_text(json.dumps(results,indent=2)+'\n')
print('PASS secret/leaf rotation, revocation, expiry, sealed/restart/recovery')