Implement lab7 mTLS, scoped OpenBao secrets and worker compromise experiment
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
"""Explicit operator init/unseal/provision. Shares never enter a service mount."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import time
|
||||
import urllib.request
|
||||
from urllib.error import HTTPError, URLError
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def request(path,body=None,token=None,method=None):
|
||||
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/trust/ca.crt'))
|
||||
ctx.load_cert_chain(ROOT/'secrets/identities/operator/cert.pem',ROOT/'secrets/identities/operator/key.pem')
|
||||
headers={'Content-Type':'application/json'}
|
||||
if token:headers['X-Vault-Token']=token
|
||||
req=urllib.request.Request('https://127.0.0.1:8200/v1/'+path,data=json.dumps(body).encode() if body is not None else None,headers=headers,method=method)
|
||||
with urllib.request.urlopen(req,context=ctx,timeout=15) as r:
|
||||
raw=r.read();return json.loads(raw) if raw else {}
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser();p.add_argument('action',choices=['init','unseal','provision','seal','publish-crl']);args=p.parse_args()
|
||||
file=ROOT/'secrets/operator/bao-init.json'
|
||||
if args.action=='init':
|
||||
if request('sys/init')['initialized']:raise SystemExit('Already initialized; preserve existing operator shares')
|
||||
result=request('sys/init',{'secret_shares':3,'secret_threshold':2})
|
||||
with file.open('x',encoding='utf-8') as f:json.dump(result,f)
|
||||
file.chmod(0o600)
|
||||
print('Initialized; three shares stored in operator-only local file. Unseal explicitly.');return
|
||||
operator=json.loads(file.read_text(encoding='utf-8'));token=operator['root_token']
|
||||
if args.action=='unseal':
|
||||
deadline=time.monotonic()+20
|
||||
while True:
|
||||
try:request('sys/seal-status');break
|
||||
except (URLError,OSError):
|
||||
if time.monotonic()>=deadline:raise
|
||||
time.sleep(.5)
|
||||
for share in operator['keys'][:2]:request('sys/unseal',{'key':share})
|
||||
elif args.action=='seal':request('sys/seal',{},token)
|
||||
elif args.action=='publish-crl':request('auth/cert/crls/operator',{'crl':(ROOT/'secrets/trust/revocations.pem').read_text()},token)
|
||||
elif args.action=='provision':
|
||||
mounts=request('sys/mounts',token=token)
|
||||
if 'secret/' not in mounts:request('sys/mounts/secret',{'type':'kv','options':{'version':'2'}},token)
|
||||
auth=request('sys/auth',token=token)
|
||||
if 'cert/' not in auth:request('sys/auth/cert',{'type':'cert'},token)
|
||||
config=json.loads((ROOT/'secrets/operator/config.json').read_text())
|
||||
for role,data in config['service_credentials'].items():
|
||||
policy=f'path "secret/data/{role}" {{ capabilities = ["read"] }}\n'
|
||||
request('sys/policies/acl/'+role,{'policy':policy},token)
|
||||
request('auth/cert/certs/'+role,{'certificate':(ROOT/'secrets/trust/ca.crt').read_text(),
|
||||
'allowed_dns_sans':[role],'token_policies':[role],'token_ttl':120,'token_max_ttl':120,'token_no_default_policy':False},token)
|
||||
request('secret/data/'+role,{'data':data},token)
|
||||
# Audit is declarative in openbao.hcl; API audit creation remains disabled.
|
||||
assert 'operator/' in request('sys/audit',token=token), 'Audit device missing'
|
||||
print('Operator action completed; no root token/unseal shares printed')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Generate isolated local credentials. Operator files are never app mounts."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import csv
|
||||
import os
|
||||
import subprocess
|
||||
from datetime import datetime,timedelta,timezone
|
||||
import pki
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
ROLES=['api1','api2','worker','dispatcher','reconciler']
|
||||
|
||||
|
||||
def protect_local_files():
|
||||
directory=ROOT/'secrets';directory.mkdir(exist_ok=True)
|
||||
directory.chmod(0o700)
|
||||
if os.name=='nt':
|
||||
sid=next(csv.reader(subprocess.check_output(['whoami','/user','/fo','csv','/nh'],text=True).splitlines()))[1]
|
||||
for path in (directory,ROOT/'.env',ROOT/'.env.storage-admin'):
|
||||
if not path.exists():continue
|
||||
flags='(OI)(CI)' if path.is_dir() else ''
|
||||
result=subprocess.run(['icacls',str(path),'/inheritance:r','/grant:r',
|
||||
'*'+sid+':'+flags+'F','*S-1-5-18:'+flags+'F','*S-1-5-32-544:'+flags+'F'],capture_output=True)
|
||||
if result.returncode:raise RuntimeError('Could not restrict local secret ACLs')
|
||||
|
||||
|
||||
def main():
|
||||
protect_local_files()
|
||||
pki.init()
|
||||
pki.crl()
|
||||
for role in ROLES+['db','s3','broker','cache','otel-collector','prometheus','loki','tempo','grafana','lb','openbao','operator','outsider']:
|
||||
cert_path=ROOT/'secrets/identities'/role/'cert.pem'
|
||||
if (not cert_path.exists() or pki.x509.load_pem_x509_certificate(cert_path.read_bytes()).not_valid_after_utc
|
||||
< datetime.now(timezone.utc)+timedelta(hours=2)):
|
||||
pki.issue(role)
|
||||
target=ROOT/'secrets/operator/config.json'
|
||||
if target.exists():
|
||||
print('Existing local credentials preserved');return
|
||||
password=secrets.token_hex(24)
|
||||
db={role:secrets.token_hex(24) for role in ROLES}
|
||||
broker={role:secrets.token_hex(24) for role in ('worker','dispatcher')}
|
||||
cache={role:secrets.token_hex(24) for role in ('api1','api2')}
|
||||
s3={role:(secrets.token_hex(12),secrets.token_hex(32)) for role in ROLES+['admin'] if role!='dispatcher'}
|
||||
cursor=secrets.token_hex(32)
|
||||
credentials={}
|
||||
for role in ROLES:
|
||||
credentials[role]={'DATABASE_URL':f'postgresql://{role}:{db[role]}@127.0.0.1:5432/messenger',
|
||||
'CURSOR_SECRET':cursor,
|
||||
'OTEL_EXPORTER_OTLP_ENDPOINT':'http://127.0.0.1:4318','TELEMETRY_ENABLED':'1','SESSION_TTL_SECONDS':'3600'}
|
||||
if role in s3:
|
||||
credentials[role].update({'S3_ENDPOINT':'http://127.0.0.1:8333','S3_BUCKET':'messenger',
|
||||
'S3_ACCESS_KEY':s3[role][0],'S3_SECRET_KEY':s3[role][1]})
|
||||
if role in cache: credentials[role]['REDIS_URL']=f'redis://{role}:{cache[role]}@127.0.0.1:6379/0'
|
||||
if role in broker: credentials[role]['BROKER_URL']=f'redis://{role}:{broker[role]}@127.0.0.1:6380/0'
|
||||
identities=[]
|
||||
for role,(key,secret) in s3.items():
|
||||
if role=='admin':actions=['Admin','Read','Write','List','Tagging']
|
||||
elif role.startswith('api'):actions=['Read:messenger/originals/*','Read:messenger/variants/*','Write:messenger/staging/*']
|
||||
else:
|
||||
actions=['Read:messenger/staging/*','Read:messenger/originals/*','Read:messenger/variants/*','Write:messenger/staging/*','Write:messenger/originals/*','Write:messenger/variants/*']
|
||||
if role=='reconciler':actions.append('List:messenger')
|
||||
identities.append({'name':role,'credentials':[{'accessKey':key,'secretKey':secret}],'actions':actions})
|
||||
files={'.env':'POSTGRES_PASSWORD='+password+'\n',
|
||||
'.env.storage-admin':f'S3_ENDPOINT=http://127.0.0.1:8333\nS3_BUCKET=messenger\nS3_ACCESS_KEY={s3["admin"][0]}\nS3_SECRET_KEY={s3["admin"][1]}\n',
|
||||
'secrets/s3.json':json.dumps({'identities':identities},indent=2),
|
||||
'secrets/grafana-password':secrets.token_urlsafe(24)+'\n',
|
||||
'secrets/cache.conf':'bind 127.0.0.1\nprotected-mode yes\nmaxmemory 32mb\nmaxmemory-policy allkeys-lru\nsave ""\nuser default off\n'+''.join(f'user {r} on >{v} ~user:* -@all +get +set +ping +hello +client|setinfo\n' for r,v in cache.items()),
|
||||
'secrets/broker.conf':'bind 127.0.0.1\nprotected-mode yes\nappendonly yes\nappendfsync always\ndir /data\nsave ""\nmaxmemory 64mb\nmaxmemory-policy noeviction\nuser default off\n'+
|
||||
f'user dispatcher on >{broker["dispatcher"]} ~attachment-jobs -@all +xadd +xgroup +ping +hello +client|setinfo\n'+
|
||||
f'user worker on >{broker["worker"]} ~attachment-jobs -@all +xgroup +xautoclaim +xreadgroup +xack +xdel +multi +exec +ping +hello +client|setinfo\n',
|
||||
'secrets/operator/config.json':json.dumps({'database_passwords':db,'service_credentials':credentials},indent=2)}
|
||||
for name,value in files.items():
|
||||
p=ROOT/name;p.parent.mkdir(parents=True,exist_ok=True)
|
||||
with p.open('x',encoding='utf-8',newline='\n') as f:f.write(value)
|
||||
p.chmod(0o600)
|
||||
protect_local_files()
|
||||
print('Generated separate identities and local secrets; values not printed')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Generate the committed, provisioned dashboard from explicit PromQL."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
panels=[]
|
||||
def panel(title,queries,unit='short'):
|
||||
i=len(panels)
|
||||
panels.append({'id':i+1,'type':'timeseries','title':title,'datasource':{'type':'prometheus','uid':'prometheus'},
|
||||
'gridPos':{'x':(i%2)*12,'y':(i//2)*8,'w':12,'h':8},
|
||||
'targets':[{'refId':chr(65+j),'expr':expr,'legendFormat':label} for j,(label,expr) in enumerate(queries)],
|
||||
'fieldConfig':{'defaults':{'unit':unit,'min':0,**({'max':1} if unit=='percentunit' else {})},'overrides':[]},'options':{'legend':{'displayMode':'list','placement':'bottom'}}})
|
||||
|
||||
panel('API requests / second',[('{{method}} {{route}}','sum by(method,route)(rate(http_server_requests_total[1m]))')],'reqps')
|
||||
panel('API 5xx / all business requests',[('5xx fraction','(sum(rate(http_server_requests_total{status_class="5xx"}[1m])) or vector(0)) / clamp_min(sum(rate(http_server_requests_total[1m])),0.001)')],'percentunit')
|
||||
panel('API latency: aggregate buckets across replicas',[(f'p{p}',f'histogram_quantile({p/100},sum by(le)(rate(http_server_duration_seconds_bucket[1m])))') for p in (50,95,99)],'s')
|
||||
panel('Jobs / second by outcome',[('{{outcome}}','sum by(outcome)(rate(jobs_processed_total[1m]))')],'ops')
|
||||
panel('Worker processing latency',[(f'p{p}',f'histogram_quantile({p/100},sum by(le)(rate(job_processing_duration_seconds_bucket[1m])))') for p in (50,95,99)],'s')
|
||||
panel('Acceptance to ready latency',[(f'p{p}',f'histogram_quantile({p/100},sum by(le)(rate(attachment_time_to_ready_seconds_bucket[5m])))') for p in (50,95,99)],'s')
|
||||
panel('Unfinished durable jobs',[('queue depth','sum(queue_depth)')])
|
||||
panel('Oldest unfinished job age',[('oldest','max(queue_oldest_age_seconds)')],'s')
|
||||
panel('DB pool',[('used {{process_instance}}','db_pool_used'),('waiting {{process_instance}}','db_pool_waiting')])
|
||||
panel('Worker saturation',[('busy / capacity','sum(worker_busy) / clamp_min(sum(worker_capacity),1)')],'percentunit')
|
||||
panel('Current process RSS',[('{{service}} {{process_instance}}','process_rss_bytes')],'bytes')
|
||||
panel('Process CPU seconds / wall second',[('{{service}} {{process_instance}}','clamp_min(deriv(process_cpu_time_seconds[1m]),0)')],'short')
|
||||
panel('API availability burn rate; budget 0.5%',[(f'{w}s',f'(sum(rate(http_server_requests_total{{status_class="5xx"}}[{w}s])) or vector(0)) / clamp_min(sum(rate(http_server_requests_total[{w}s])),0.001) / 0.005') for w in (20,60)])
|
||||
panel('Ready <=30s burn rate; budget 1%',[(f'{w}s eligible cohort',f'sum(attachment_slo_bad{{window="{w}"}}) / clamp_min(sum(attachment_slo_eligible{{window="{w}"}}),1) / 0.01') for w in (60,300)])
|
||||
panel('Collector exporter queue / capacity',[('{{exporter}} size','otelcol_exporter_queue_size'),('{{exporter}} capacity','otelcol_exporter_queue_capacity')])
|
||||
panel('Collector failed exports',[('{{exporter}} spans','rate(otelcol_exporter_send_failed_spans_total[1m])'),('{{exporter}} logs','rate(otelcol_exporter_send_failed_log_records_total[1m])')],'ops')
|
||||
panels.append({'id':99,'type':'logs','title':'Structured application logs; TraceID links to Tempo','datasource':{'type':'loki','uid':'loki'},
|
||||
'gridPos':{'x':0,'y':64,'w':24,'h':10},'targets':[{'refId':'A','expr':'{service_name=~"messenger-(api|worker|dispatcher)"}'}],
|
||||
'options':{'showTime':True,'showLabels':False,'wrapLogMessage':True,'sortOrder':'Descending'}})
|
||||
doc={'uid':'mtusi-messenger','title':'MTUSI Messenger - signals and SLO','schemaVersion':39,'version':1,
|
||||
'editable':False,'timezone':'browser','time':{'from':'now-15m','to':'now'},'refresh':'15s','tags':['mtusi','lab6'],
|
||||
'panels':panels,'annotations':{'list':[]},'templating':{'list':[]}}
|
||||
path=Path(__file__).resolve().parents[1]/'infra/grafana/dashboards/messenger.json'
|
||||
path.parent.mkdir(parents=True,exist_ok=True)
|
||||
path.write_text(json.dumps(doc,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Operator migrations/grants over the container-local PostgreSQL Unix socket.
|
||||
|
||||
SQL containing passwords travels on stdin, not argv/logs; no admin DB credential
|
||||
is made available to an application. Existing migration hashes must match.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def sql(query):
|
||||
result=subprocess.run(['docker','compose','exec','-T','db','psql','-X','-qAt',
|
||||
'-v','ON_ERROR_STOP=1','-U','messenger','-d','messenger'],input=query,
|
||||
text=True,encoding='utf-8',capture_output=True,cwd=ROOT)
|
||||
if result.returncode:
|
||||
# Server error text may echo a credential-bearing statement.
|
||||
raise RuntimeError('Operator SQL failed; no query or credentials printed')
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
sql('CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY, sha256 text NOT NULL, applied_at timestamptz NOT NULL DEFAULT clock_timestamp())')
|
||||
for file in sorted((ROOT/'migrations').glob('*.sql')):
|
||||
digest=hashlib.sha256(file.read_bytes()).hexdigest()
|
||||
old=sql(f"SELECT sha256 FROM schema_migrations WHERE name='{file.name}'")
|
||||
if old:
|
||||
assert old==digest, 'Applied migration changed: '+file.name
|
||||
else:
|
||||
sql('BEGIN;\n'+file.read_text()+f"\nINSERT INTO schema_migrations(name,sha256) VALUES ('{file.name}','{digest}'); COMMIT;")
|
||||
print('Migration verified:',file.name)
|
||||
passwords=json.loads((ROOT/'secrets/operator/config.json').read_text())['database_passwords']
|
||||
for role,password in passwords.items():
|
||||
assert role in ('api1','api2','worker','dispatcher','reconciler') and all(c in '0123456789abcdef' for c in password)
|
||||
if not sql(f"SELECT 1 FROM pg_roles WHERE rolname='{role}'"):sql(f'CREATE ROLE {role} LOGIN')
|
||||
sql(f"ALTER ROLE {role} PASSWORD '{password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION; GRANT CONNECT ON DATABASE messenger TO {role}; GRANT USAGE ON SCHEMA public TO {role}; REVOKE ALL ON ALL TABLES IN SCHEMA public FROM {role}; REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM {role};")
|
||||
sql('REVOKE ALL ON DATABASE messenger FROM PUBLIC; REVOKE CREATE ON SCHEMA public FROM PUBLIC;')
|
||||
sql('GRANT SELECT,INSERT,UPDATE,DELETE ON users,sessions,chats,members,messages,idempotency,attachments,message_attachments,jobs,outbox,login_budget TO api1,api2;')
|
||||
sql('GRANT SELECT,UPDATE ON jobs,attachments,outbox,job_faults TO worker; GRANT INSERT ON job_audit TO worker; GRANT USAGE ON SEQUENCE job_audit_id_seq TO worker;')
|
||||
sql('GRANT SELECT,UPDATE ON jobs,attachments,outbox TO dispatcher; GRANT INSERT ON job_audit TO dispatcher; GRANT USAGE ON SEQUENCE job_audit_id_seq TO dispatcher;')
|
||||
sql('GRANT SELECT,UPDATE ON attachments TO reconciler;')
|
||||
print('Scoped database roles applied')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Operator-owned local PKI. CA private material is never mounted into services."""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import ipaddress
|
||||
import json
|
||||
from pathlib import Path
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
PRIVATE=ROOT/'secrets/operator'
|
||||
TRUST=ROOT/'secrets/trust'
|
||||
|
||||
|
||||
def write(path,data):
|
||||
path.parent.mkdir(parents=True,exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
path.chmod(0o600 if 'key' in path.name or path.name == 'combined.pem' or path.parent == PRIVATE else 0o644)
|
||||
|
||||
|
||||
def key_bytes(key):
|
||||
return key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption())
|
||||
|
||||
|
||||
def ca():
|
||||
return (serialization.load_pem_private_key((PRIVATE/'ca.key').read_bytes(),None),
|
||||
x509.load_pem_x509_certificate((TRUST/'ca.crt').read_bytes()))
|
||||
|
||||
|
||||
def init():
|
||||
if (PRIVATE/'ca.key').exists(): return
|
||||
key=ec.generate_private_key(ec.SECP256R1()); now=datetime.now(timezone.utc)
|
||||
name=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'MTUSI local operator CA')])
|
||||
cert=(x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now-timedelta(minutes=1))
|
||||
.not_valid_after(now+timedelta(days=365)).add_extension(x509.BasicConstraints(ca=True,path_length=0),True)
|
||||
.add_extension(x509.KeyUsage(False,False,False,False,False,True,True,None,None),True)
|
||||
.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),False).sign(key,hashes.SHA256()))
|
||||
write(PRIVATE/'ca.key',key_bytes(key));write(TRUST/'ca.crt',cert.public_bytes(serialization.Encoding.PEM))
|
||||
write(PRIVATE/'revoked.json',b'[]'); crl()
|
||||
|
||||
|
||||
def issue(role,hours=24,extra=()):
|
||||
key,issuer=ca(); leaf=ec.generate_private_key(ec.SECP256R1()); now=datetime.now(timezone.utc)
|
||||
sans=[x509.DNSName(role),*[x509.DNSName(n) for n in extra]]
|
||||
if role in ('lb','openbao','grafana'): sans += [x509.DNSName('localhost'),x509.IPAddress(ipaddress.ip_address('127.0.0.1'))]
|
||||
cert=(x509.CertificateBuilder().subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,role)]))
|
||||
.issuer_name(issuer.subject).public_key(leaf.public_key()).serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now-timedelta(minutes=1)).not_valid_after(now+timedelta(hours=hours))
|
||||
.add_extension(x509.BasicConstraints(ca=False,path_length=None),True)
|
||||
.add_extension(x509.SubjectAlternativeName(sans),False)
|
||||
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH,ExtendedKeyUsageOID.CLIENT_AUTH]),False)
|
||||
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False)
|
||||
.sign(key,hashes.SHA256()))
|
||||
folder=ROOT/'secrets/identities'/role
|
||||
write(folder/'key.pem',key_bytes(leaf));write(folder/'cert.pem',cert.public_bytes(serialization.Encoding.PEM))
|
||||
write(folder/'combined.pem',cert.public_bytes(serialization.Encoding.PEM)+key_bytes(leaf))
|
||||
return cert
|
||||
|
||||
|
||||
def crl():
|
||||
key,issuer=ca();now=datetime.now(timezone.utc)
|
||||
doc=x509.CertificateRevocationListBuilder().issuer_name(issuer.subject).last_update(now-timedelta(minutes=1)).next_update(now+timedelta(days=7))
|
||||
for serial in json.loads((PRIVATE/'revoked.json').read_text()):
|
||||
doc=doc.add_revoked_certificate(x509.RevokedCertificateBuilder().serial_number(serial).revocation_date(now).build())
|
||||
pem=doc.sign(key,hashes.SHA256()).public_bytes(serialization.Encoding.PEM)
|
||||
write(TRUST/'revocations.pem',pem);write(TRUST/'bundle.pem',(TRUST/'ca.crt').read_bytes()+pem)
|
||||
|
||||
|
||||
def revoke(role):
|
||||
cert=x509.load_pem_x509_certificate((ROOT/'secrets/identities'/role/'cert.pem').read_bytes())
|
||||
path=PRIVATE/'revoked.json';values=json.loads(path.read_text())
|
||||
if cert.serial_number not in values: values.append(cert.serial_number)
|
||||
write(path,json.dumps(values).encode());crl()
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
import argparse
|
||||
p=argparse.ArgumentParser();p.add_argument('action',choices=['issue','revoke']);p.add_argument('role');p.add_argument('--hours',type=float,default=24)
|
||||
a=p.parse_args();init()
|
||||
if a.action=='issue': issue(a.role,a.hours)
|
||||
else: revoke(a.role)
|
||||
print('PKI operation complete; no key material printed')
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
if not defined LAB7_PYTHON set "LAB7_PYTHON=python"
|
||||
"%LAB7_PYTHON%" "%~dp0restart.py"
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Restart every running replica and dependency, preserving durable volumes."""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from stack import ROOT, docker, state
|
||||
|
||||
before = state()
|
||||
docker('compose', 'stop', '--timeout', '5')
|
||||
docker('compose', 'start')
|
||||
subprocess.run([sys.executable,str(ROOT/'scripts/bao_operator.py'),'unseal'],check=True)
|
||||
after = state()
|
||||
assert set(before) == set(after)
|
||||
assert all(before[c]['state']['StartedAt'] != after[c]['state']['StartedAt'] for c in before)
|
||||
(ROOT / 'evidence').mkdir(exist_ok=True)
|
||||
(ROOT / 'evidence/restart-processes.json').write_text(
|
||||
json.dumps({'before': before, 'after': after, 'volumes_removed': False}, indent=2) + '\n',
|
||||
encoding='utf-8')
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
python3 scripts/restart.py
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Scan exported image archives without mounting the Docker socket or host secrets."""
|
||||
import argparse
|
||||
import collections
|
||||
from datetime import datetime,timezone
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import yaml
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
TRIVY='aquasec/trivy@sha256:790fd66d1697395d8693d1acaa1ea702406a20f109b6fc7bac8db623eca6c06c'
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser();parser.add_argument('services',nargs='*',default=['api1','openbao','s3','lb']);args=parser.parse_args()
|
||||
compose=yaml.safe_load((ROOT/'compose.yaml').read_text())
|
||||
summary={'at_UTC':datetime.now(timezone.utc).isoformat(),'scanner':TRIVY,'scope':args.services,'images':[]}
|
||||
with tempfile.TemporaryDirectory(prefix='lab7-image-scan-') as tmp:
|
||||
for service in args.services:
|
||||
image=compose['services'][service]['image']
|
||||
image_id=subprocess.check_output(['docker','image','inspect',image,'--format','{{.Id}}'],text=True).strip()
|
||||
archive=Path(tmp)/'image.tar';report=Path(tmp)/'report.json'
|
||||
subprocess.run(['docker','save','--output',str(archive),image],check=True)
|
||||
subprocess.run(['docker','run','--rm','--cpus','0.5','--memory','768m','--pids-limit','128',
|
||||
'-v',tmp+':/scan','-v','mtusi-trivy-cache:/root/.cache/trivy',TRIVY,'image','--input','/scan/image.tar',
|
||||
'--parallel','1','--scanners','vuln','--format','json','--output','/scan/report.json'],check=True)
|
||||
data=json.loads(report.read_text());findings=[]
|
||||
for result in data.get('Results',[]):
|
||||
for v in result.get('Vulnerabilities',[]):
|
||||
findings.append({'target':result.get('Target'),**{k:v.get(k) for k in ('VulnerabilityID','PkgName','InstalledVersion','FixedVersion','Severity','Title','PrimaryURL')}})
|
||||
summary['images'].append({'service':service,'image':image,'image_id':image_id,'report_sha256':hashlib.sha256(report.read_bytes()).hexdigest(),
|
||||
'counts':dict(collections.Counter(v['Severity'] for v in findings)),'findings':findings})
|
||||
(ROOT/'evidence/image-audit.json').write_text(json.dumps(summary,indent=2)+'\n')
|
||||
print(service,summary['images'][-1]['counts'],flush=True)
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Shared bounded Docker helpers for reproducible, scoped failure experiments."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
def docker(*args):
|
||||
return subprocess.check_output(['docker',*args],cwd=ROOT,text=True,encoding='utf-8',stderr=subprocess.PIPE).strip()
|
||||
def replicas(): return docker('compose','ps','-q','api1','api2').splitlines()
|
||||
|
||||
def ready_replicas(count=2,timeout=60):
|
||||
deadline=time.monotonic()+timeout
|
||||
while time.monotonic()<deadline:
|
||||
ids=replicas()
|
||||
if len(ids)==count:
|
||||
states=[json.loads(docker('inspect','--format','{{json .State}}',cid)) for cid in ids]
|
||||
if all(s['Running'] and s.get('Health',{}).get('Status')=='healthy' for s in states): return
|
||||
time.sleep(.5)
|
||||
raise AssertionError('Actual replica health did not recover within timeout')
|
||||
def instance(cid):
|
||||
return docker('exec',cid,'python','-c',"import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8080/health/live',timeout=2).headers['X-Instance-Id'])")
|
||||
def state():
|
||||
result={}
|
||||
for service in ('api1','api2','db','cache','lb','s3','reconciler','broker','worker','dispatcher','openbao','otel-collector','prometheus','loki','tempo','grafana'):
|
||||
for cid in docker('compose','ps','-q',service).splitlines():
|
||||
result[cid]={'service':service,'state':json.loads(docker('inspect','--format','{{json .State}}',cid))}
|
||||
return result
|
||||
def ready(client,timeout=60):
|
||||
deadline=time.monotonic()+timeout
|
||||
while time.monotonic()<deadline:
|
||||
try:
|
||||
if client.get('/health/ready').status_code==200: return
|
||||
except Exception: pass
|
||||
time.sleep(.2)
|
||||
raise AssertionError('Readiness timeout')
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
if not defined LAB7_PYTHON set "LAB7_PYTHON=python"
|
||||
"%LAB7_PYTHON%" "%~dp0stop-one.py"
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Stop the real process selected by X-Instance-Id; do not stop any dependency."""
|
||||
import json
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from stack import ROOT, docker, instance, replicas
|
||||
target=os.environ['TARGET_INSTANCE_ID']
|
||||
before=replicas()
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
matches=[cid for cid,alias in zip(before,pool.map(instance,before)) if alias==target]
|
||||
assert len(matches)==1,'Target does not uniquely identify a running API'
|
||||
# Immediate process crash, without adding a graceful-drain delay to the fault.
|
||||
docker('kill','--signal','KILL',matches[0])
|
||||
assert docker('inspect','--format','{{.State.Running}}',matches[0])=='false'
|
||||
(ROOT/'evidence').mkdir(exist_ok=True)
|
||||
(ROOT/'evidence/stop-one.json').write_text(json.dumps({'target_instance':target,'stopped_container':matches[0],'before_containers':before,'after_running_containers':replicas()},indent=2)+'\n',encoding='utf-8')
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/stop-one.py
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Negative-test leaf identities; never used by a runtime service."""
|
||||
from datetime import datetime,timedelta,timezone
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes,serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID
|
||||
import pki
|
||||
|
||||
roles=['lb','api1','api2','worker','dispatcher','reconciler','operator','otel-collector','prometheus','grafana']
|
||||
pki.issue('expired',hours=-.001,extra=roles)
|
||||
pki.issue('revoked',extra=roles);pki.revoke('revoked')
|
||||
key=ec.generate_private_key(ec.SECP256R1());now=datetime.now(timezone.utc)
|
||||
name=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'untrusted-test')])
|
||||
cert=(x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now-timedelta(minutes=1))
|
||||
.not_valid_after(now+timedelta(hours=1)).add_extension(x509.SubjectAlternativeName([x509.DNSName(n) for n in roles]),False).sign(key,hashes.SHA256()))
|
||||
pki.write(pki.ROOT/'secrets/identities/alien/key.pem',pki.key_bytes(key))
|
||||
pki.write(pki.ROOT/'secrets/identities/alien/cert.pem',cert.public_bytes(serialization.Encoding.PEM))
|
||||
print('Negative test identities generated')
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Explicit operator bootstrap/start; preserves credentials and persistent volumes."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
from urllib.error import HTTPError,URLError
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0,str(ROOT/'scripts'))
|
||||
from bao_operator import request
|
||||
|
||||
|
||||
def run(*args):subprocess.run(args,cwd=ROOT,check=True)
|
||||
|
||||
|
||||
def main():
|
||||
run(sys.executable,'scripts/bootstrap.py')
|
||||
run('docker','compose','config','--quiet')
|
||||
run('docker','compose','build','api1')
|
||||
# Coordinated cold start also reloads native TLS and copied secret files.
|
||||
# A parent and its shared-network sidecar must restart in dependency order.
|
||||
run('docker','compose','stop','--timeout','5')
|
||||
run('docker','compose','up','-d','db','openbao','s3','cache','broker')
|
||||
for _ in range(40):
|
||||
try:initialized=request('sys/init')['initialized'];break
|
||||
except (URLError,OSError):time.sleep(.5)
|
||||
else:raise RuntimeError('OpenBao did not become reachable')
|
||||
if not initialized:run(sys.executable,'scripts/bao_operator.py','init')
|
||||
run(sys.executable,'scripts/bao_operator.py','unseal')
|
||||
run(sys.executable,'scripts/database_operator.py')
|
||||
run(sys.executable,'scripts/bao_operator.py','provision')
|
||||
run('docker','compose','run','--rm','storage-init')
|
||||
run('docker','compose','up','-d')
|
||||
# Compose may recreate Bao when its dependency image changed.
|
||||
run(sys.executable,'scripts/bao_operator.py','unseal')
|
||||
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/trust/ca.crt'))
|
||||
for _ in range(90):
|
||||
try:
|
||||
with urllib.request.urlopen('https://127.0.0.1:8443/health/ready',context=ctx,timeout=3) as r:
|
||||
if r.status==200:break
|
||||
except (URLError,OSError):pass
|
||||
time.sleep(1)
|
||||
else:raise RuntimeError('Verified HTTPS readiness failed')
|
||||
print('Stack ready on verified HTTPS; local operator shares remain outside containers/Git')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Unchanged public checks + real restart/failover hooks; evidence kept verbatim."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import ssl
|
||||
import urllib.request
|
||||
from stack import docker,ready_replicas,replicas
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
ENV={**os.environ,'LAB7_PYTHON':sys.executable}
|
||||
|
||||
|
||||
def check(script,*args,name=None):
|
||||
result=subprocess.run([sys.executable,'-X','utf8',script,*args],cwd=ROOT,env=ENV,text=True,encoding='utf-8',capture_output=True)
|
||||
(ROOT/'evidence'/((name or Path(script).stem)+'.txt')).write_text(result.stdout+result.stderr,encoding='utf-8')
|
||||
print((name or script)+': '+('PASS' if result.returncode==0 else 'FAIL'),flush=True)
|
||||
if result.returncode:raise RuntimeError('Public check failed; inspect its evidence transcript')
|
||||
|
||||
|
||||
def main():
|
||||
ready_replicas(timeout=90)
|
||||
time.sleep(3) # HAProxy healthy rise after native replica readiness.
|
||||
opts=['--base-url','https://127.0.0.1:8443','--ca-file',str(ROOT/'secrets/trust/ca.crt')]
|
||||
check('scripts/check_contract.py')
|
||||
check('scripts/validate_openapi.py')
|
||||
check('tests/smoke.py',*opts)
|
||||
check('tests/security.py',*opts)
|
||||
ext='cmd' if os.name=='nt' else 'sh'
|
||||
time.sleep(10)
|
||||
check('tests/resilience.py','--mode','persistence','--action-script','scripts/restart.'+ext,*opts,name='persistence')
|
||||
stopped=[]
|
||||
for i in range(6):
|
||||
docker('compose','stop','--timeout','2','api1-tls','api2-tls')
|
||||
docker('compose','start','api1','api2','api1-tls','api2-tls')
|
||||
ready_replicas(timeout=90)
|
||||
# The LB chooses the actual target; continue until both containers have
|
||||
# really been stopped. Never override the public test's selected target.
|
||||
time.sleep(10)
|
||||
for _ in range(i):
|
||||
with urllib.request.urlopen('https://127.0.0.1:8443/health/live',context=ssl.create_default_context(cafile=str(ROOT/'secrets/trust/ca.crt')),timeout=3):pass
|
||||
check('tests/resilience.py','--mode','failover','--action-script','scripts/stop-one.'+ext,*opts,name='failover-'+str(i+1))
|
||||
proof=json.loads((ROOT/'evidence/stop-one.json').read_text())
|
||||
stopped.append(proof)
|
||||
(ROOT/'evidence'/('failover-'+str(i+1)+'-process.json')).write_text(json.dumps(proof,indent=2))
|
||||
if len({p['stopped_container'] for p in stopped})==2:break
|
||||
docker('compose','stop','--timeout','2','api1-tls','api2-tls')
|
||||
docker('compose','start','api1','api2','api1-tls','api2-tls');ready_replicas(timeout=90)
|
||||
assert len({p['stopped_container'] for p in stopped})==2,'Both tests selected same container; repeat second target explicitly'
|
||||
print('PASS: both distinct API containers failed over; all replicas restored',flush=True)
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Sequential security experiments; do not run alongside other fault injection."""
|
||||
from datetime import datetime,timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def run(args,name,input=None,json_output=False):
|
||||
r=subprocess.run(args,cwd=ROOT,text=True,encoding='utf-8',capture_output=True,input=input)
|
||||
if json_output and r.returncode==0:
|
||||
data=json.loads(r.stdout);assert data['passed']
|
||||
(ROOT/'evidence'/(name+'.json')).write_text(json.dumps(data,indent=2)+'\n')
|
||||
(ROOT/'evidence'/(name+'.txt')).unlink(missing_ok=True)
|
||||
else:(ROOT/'evidence'/(name+'.txt')).write_text(r.stdout+r.stderr,encoding='utf-8')
|
||||
print(name+': '+('PASS' if r.returncode==0 else 'FAIL'),flush=True)
|
||||
if r.returncode:raise RuntimeError('Failed security scenario: '+name)
|
||||
|
||||
|
||||
def main():
|
||||
py=[sys.executable,'-X','utf8'];compose=['docker','compose']
|
||||
run(py+['scripts/test_identities.py'],'generate-test-identities')
|
||||
run(py+['scripts/bao_operator.py','publish-crl'],'publish-crl')
|
||||
# >=1s context cache expiration, no weakening of certificate verification.
|
||||
time.sleep(2)
|
||||
run(compose+['run','--rm','--no-deps','security-check'],'tls-matrix',json_output=True)
|
||||
run(compose+['run','--rm','--no-deps','security-check','python','/checks/bao_policy.py'],'bao-policy',json_output=True)
|
||||
run(compose+['exec','-T','worker','python','-'],'worker-rights',input=(ROOT/'checks/worker_rights.py').read_text(),json_output=True)
|
||||
run(py+['checks/security_api.py'],'security-api-run')
|
||||
time.sleep(10)
|
||||
run(py+['checks/compromised_worker.py'],'compromised-worker-run')
|
||||
run(py+['checks/sealed_bao.py'],'sealed-bao-run')
|
||||
run(py+['checks/telemetry_security.py'],'telemetry-security-run')
|
||||
run(py+['checks/hardening.py'],'hardening-run')
|
||||
run(compose+['run','--rm','--no-deps','-v',str(ROOT/'checks')+':/checks:ro','api1','python','-m','unittest','discover','-s','/checks','-p','test_render.py'],'render-unit')
|
||||
(ROOT/'evidence/security-suite.json').write_text(json.dumps({'passed':True,'completed_at_UTC':datetime.now(timezone.utc).isoformat()},indent=2)+'\n')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
Reference in New Issue
Block a user