Complete lab 7 TLS and secret management
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Бахрам
2026-12-01 22:44:28 +03:00
parent 20afc2c790
commit 1df2202403
51 changed files with 3396 additions and 138 deletions
+301
View File
@@ -0,0 +1,301 @@
#!/usr/bin/env python3
"""Create ignored local PKI/secrets, initialize OpenBao, and start the grade-3 stack."""
import json
import os
from pathlib import Path
import secrets
import shutil
import socket
import ssl
import subprocess
import time
import urllib.error
import urllib.request
ROOT=Path(__file__).resolve().parents[1]
LOCAL=ROOT/'.local'
PKI=LOCAL/'pki'
BAO=LOCAL/'openbao'
ROLES=LOCAL/'approles'
ENV=ROOT/'.env'
def run(*args,stdout=None):
return subprocess.run(args,cwd=ROOT,check=True,stdout=stdout)
def write(path,data,mode=0o600):
path.parent.mkdir(parents=True,exist_ok=True)
path.write_text(data,encoding='utf-8')
path.chmod(mode)
def make_env():
required={'POSTGRES_ADMIN_PASSWORD','POSTGRES_API_PASSWORD','POSTGRES_WORKER_PASSWORD',
'S3_API_ACCESS_KEY','S3_API_SECRET_KEY','S3_WORKER_ACCESS_KEY','S3_WORKER_SECRET_KEY',
'S3_ADMIN_ACCESS_KEY','S3_ADMIN_SECRET_KEY','RABBIT_ADMIN_USER','RABBIT_ADMIN_PASSWORD',
'RABBIT_API_USER','RABBIT_API_PASSWORD','RABBIT_WORKER_USER','RABBIT_WORKER_PASSWORD','GRAFANA_PASSWORD'}
if ENV.exists():
existing=env_values()
if required <= set(existing) and all(existing[k] and 'CHANGE_ME' not in existing[k] for k in required):
return
values={
'PUBLIC_PORT':'8443','POSTGRES_ADMIN_PASSWORD':secrets.token_hex(32),
'POSTGRES_API_PASSWORD':secrets.token_hex(32),'POSTGRES_WORKER_PASSWORD':secrets.token_hex(32),
'S3_API_ACCESS_KEY':secrets.token_hex(12),'S3_API_SECRET_KEY':secrets.token_hex(32),
'S3_WORKER_ACCESS_KEY':secrets.token_hex(12),'S3_WORKER_SECRET_KEY':secrets.token_hex(32),
'S3_ADMIN_ACCESS_KEY':secrets.token_hex(12),'S3_ADMIN_SECRET_KEY':secrets.token_hex(32),
'RABBIT_ADMIN_USER':'lab7_operator','RABBIT_ADMIN_PASSWORD':secrets.token_hex(32),
'RABBIT_API_USER':'lab7_api','RABBIT_API_PASSWORD':secrets.token_hex(32),
'RABBIT_WORKER_USER':'lab7_worker','RABBIT_WORKER_PASSWORD':secrets.token_hex(32),
'GRAFANA_PASSWORD':secrets.token_hex(24),'SESSION_TTL_SECONDS':'3600','JOB_MAX_ATTEMPTS':'5'
}
write(ENV,'\n'.join(k+'='+v for k,v in values.items())+'\n')
def env_values():
result={}
for line in ENV.read_text().splitlines():
if line and not line.startswith('#') and '=' in line:
k,v=line.split('=',1); result[k]=v
return result
def openssl(*args):
subprocess.run(['openssl',*map(str,args)],cwd=ROOT,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
def create_ca(name):
key=PKI/(name+'.key'); cert=PKI/(name+'.crt')
if cert.exists() and key.exists(): return cert,key
openssl('genpkey','-algorithm','RSA','-pkeyopt','rsa_keygen_bits:3072','-out',key)
openssl('req','-x509','-new','-key',key,'-sha256','-days','825','-subj','/CN='+name,
'-addext','basicConstraints=critical,CA:TRUE','-addext','keyUsage=critical,keyCertSign,cRLSign','-out',cert)
key.chmod(0o600); cert.chmod(0o644)
return cert,key
def issue(name,ca_name,dns=(),ips=(),uris=()):
cert=PKI/(name+'.crt'); key=PKI/(name+'.key')
if cert.exists() and key.exists(): return cert,key
ca_cert=PKI/(ca_name+'.crt'); ca_key=PKI/(ca_name+'.key')
csr=PKI/(name+'.csr'); ext=PKI/(name+'.ext')
openssl('genpkey','-algorithm','RSA','-pkeyopt','rsa_keygen_bits:2048','-out',key)
openssl('req','-new','-key',key,'-subj','/CN='+name,'-out',csr)
sans=[]
sans.extend('DNS:'+x for x in dns); sans.extend('IP:'+x for x in ips); sans.extend('URI:'+x for x in uris)
lines=['basicConstraints=critical,CA:FALSE','keyUsage=critical,digitalSignature,keyEncipherment','extendedKeyUsage=serverAuth,clientAuth']
if sans: lines.append('subjectAltName='+','.join(sans))
write(ext,'\n'.join(lines)+'\n',0o600)
openssl('x509','-req','-in',csr,'-CA',ca_cert,'-CAkey',ca_key,'-CAcreateserial','-out',cert,'-days','90','-sha256','-extfile',ext)
key.chmod(0o644); cert.chmod(0o644); csr.unlink(missing_ok=True); ext.unlink(missing_ok=True)
return cert,key
def create_pki():
PKI.mkdir(parents=True,exist_ok=True); PKI.chmod(0o700)
create_ca('external-ca'); create_ca('service-ca'); create_ca('lb-client-ca')
create_ca('otel-ingest-ca'); create_ca('backend-client-ca')
issue('ingress','external-ca',dns=['localhost'],ips=['127.0.0.1'])
issue('api','service-ca',dns=['api1','api2','localhost'])
issue('postgres','service-ca',dns=['postgres'])
issue('s3','service-ca',dns=['s3'])
issue('broker','service-ca',dns=['broker'])
issue('openbao','service-ca',dns=['openbao','localhost'],ips=['127.0.0.1'])
for name in ('otel-collector','prometheus','loki','tempo','grafana'):
names=[name]
ips=[]
if name in ('prometheus','loki','tempo','grafana'):
names.append('localhost'); ips=['127.0.0.1']
issue(name,'service-ca',dns=names,ips=ips)
issue('lb-client','lb-client-ca',uris=['spiffe://mtusi2026/lab7/load-balancer'])
issue('foreign-client','lb-client-ca',uris=['spiffe://mtusi2026/lab7/unapproved'])
issue('untrusted-client','service-ca',uris=['spiffe://mtusi2026/lab7/untrusted'])
issue('otel-api-client','otel-ingest-ca',uris=['spiffe://mtusi2026/lab7/api'])
issue('otel-worker-client','otel-ingest-ca',uris=['spiffe://mtusi2026/lab7/worker'])
issue('backend-collector','backend-client-ca',uris=['spiffe://mtusi2026/lab7/otel-collector'])
issue('backend-grafana','backend-client-ca',uris=['spiffe://mtusi2026/lab7/grafana'])
for name in ('ingress','lb-client'):
cert,key=PKI/(name+'.crt'),PKI/(name+'.key')
write(PKI/(name+'.pem'),cert.read_text()+key.read_text(),0o600)
def create_s3_config(env):
def identity(name,access,secret,actions):
return {'name':name,'credentials':[{'accessKey':env[access],'secretKey':env[secret]}],'actions':actions}
staging='attachments-staging'; original='attachments-original'; variants='attachments-variants'
config={'identities':[
identity('api','S3_API_ACCESS_KEY','S3_API_SECRET_KEY',
['List:'+staging,'Write:'+staging,'List:'+original,'Read:'+original,'List:'+variants,'Read:'+variants]),
identity('worker','S3_WORKER_ACCESS_KEY','S3_WORKER_SECRET_KEY',
['Read:'+staging,'Write:'+staging,'Write:'+original,'Write:'+variants]),
identity('operator','S3_ADMIN_ACCESS_KEY','S3_ADMIN_SECRET_KEY',
['Admin:'+staging,'Admin:'+original,'Admin:'+variants])
]}
write(LOCAL/'s3.json',json.dumps(config,indent=2)+'\n')
def parse_body(error):
try: return json.loads(error.read().decode())
except Exception: return {}
def bao_request(path,method='GET',body=None,token=None):
context=ssl.create_default_context(cafile=str(PKI/'service-ca.crt'))
data=None if body is None else json.dumps(body).encode()
req=urllib.request.Request('https://localhost:8207/v1/'+path,data=data,method=method)
req.add_header('Content-Type','application/json')
if token: req.add_header('X-Vault-Token',token)
try:
with urllib.request.urlopen(req,context=context,timeout=5) as response:
data=response.read()
return response.status,json.loads(data) if data else {}
except urllib.error.HTTPError as exc:
return exc.code,parse_body(exc)
def wait_openbao():
deadline=time.time()+90
while time.time()<deadline:
try:
status,doc=bao_request('sys/health')
if doc: return status,doc
except Exception:
time.sleep(1)
raise RuntimeError('OpenBao TLS listener did not start')
def initialize_openbao(env):
BAO.mkdir(parents=True,exist_ok=True); BAO.chmod(0o700)
operator=BAO/'operator.json'
status,health=wait_openbao()
if not health.get('initialized'):
init_status,created=bao_request('sys/init','PUT',{'secret_shares':3,'secret_threshold':2})
if init_status!=200 or created.get('errors'):
raise RuntimeError('OpenBao initialization failed: '+str(created.get('errors',['unexpected response'])[0]))
created['keys']=created.get('keys_base64',created.get('keys',[]))
write(operator,json.dumps(created,indent=2)+'\n')
if not operator.exists():
raise RuntimeError('OpenBao is already initialized, but .local/openbao/operator.json is missing; restore operator recovery material')
data=json.loads(operator.read_text())
keys=data.get('keys') or data.get('keys_base64') or []
root=data.get('root_token')
if not root or len(keys)<2: raise RuntimeError('OpenBao operator recovery material is incomplete')
status,health=bao_request('sys/health')
if health.get('sealed',True):
for key in keys[:2]:
_,health=bao_request('sys/unseal','POST',{'key':key})
if health.get('sealed',True): raise RuntimeError('OpenBao remains sealed after operator unseal')
mounts=bao_request('sys/mounts',token=root)[1]
if 'kv/' not in mounts:
bao_request('sys/mounts/kv','POST',{'type':'kv','options':{'version':'2'}},root)
auth=bao_request('sys/auth',token=root)[1]
if 'approle/' not in auth:
bao_request('sys/auth/approle','POST',{'type':'approle'},root)
policies={
'api-runtime':'path "kv/data/messenger/api" { capabilities = ["read"] }',
'worker-runtime':'path "kv/data/messenger/worker" { capabilities = ["read"] }'
}
for name,policy in policies.items():
bao_request('sys/policies/acl/'+name,'PUT',{'policy':policy},root)
values={
'api':{
'DATABASE_URL':'postgresql://messenger_api:'+env['POSTGRES_API_PASSWORD']+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/certs/service-ca.crt',
'S3_ACCESS_KEY':env['S3_API_ACCESS_KEY'],'S3_SECRET_KEY':env['S3_API_SECRET_KEY'],
'BROKER_URL':'amqps://'+env['RABBIT_API_USER']+':'+env['RABBIT_API_PASSWORD']+'@broker:5671/%2Flab7',
'LOGIN_RATE_HMAC_KEY':secrets.token_hex(32)
},
'worker':{
'DATABASE_URL':'postgresql://messenger_worker:'+env['POSTGRES_WORKER_PASSWORD']+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/certs/service-ca.crt',
'S3_ACCESS_KEY':env['S3_WORKER_ACCESS_KEY'],'S3_SECRET_KEY':env['S3_WORKER_SECRET_KEY'],
'BROKER_URL':'amqps://'+env['RABBIT_WORKER_USER']+':'+env['RABBIT_WORKER_PASSWORD']+'@broker:5671/%2Flab7',
'LOGIN_RATE_HMAC_KEY':secrets.token_hex(32)
}
}
for service,secret in values.items():
bao_request('kv/data/messenger/'+service,'POST',{'data':secret},root)
role=service
bao_request('auth/approle/role/'+role,'POST',{
'token_policies':['api-runtime' if service=='api' else 'worker-runtime'],
'token_ttl':'10m','token_max_ttl':'30m','secret_id_ttl':'720h',
'secret_id_num_uses':0,'bind_secret_id':True
},root)
role_id=bao_request('auth/approle/role/'+role+'/role-id',token=root)[1]['data']['role_id']
secret_id=bao_request('auth/approle/role/'+role+'/secret-id','POST',{},root)[1]['data']['secret_id']
write(ROLES/(role+'-role-id'),role_id+'\n')
write(ROLES/(role+'-secret-id'),secret_id+'\n')
# Prove the runtime identity is read-only and cannot read the other service secret.
for service in ('api','worker'):
role_id=(ROLES/(service+'-role-id')).read_text().strip()
secret_id=(ROLES/(service+'-secret-id')).read_text().strip()
_,login=bao_request('auth/approle/login','POST',{'role_id':role_id,'secret_id':secret_id})
token=login['auth']['client_token']
target='messenger/'+('worker' if service=='api' else 'api')
denied,_=bao_request('kv/data/'+target,token=token)
if denied not in (403,404): raise RuntimeError('OpenBao cross-service policy denial was not enforced')
print('OpenBao initialized/unsealed; scoped API and worker AppRoles verified.')
def init_rabbit(env):
subprocess.run(['docker','compose','exec','-T','broker','su-exec','rabbitmq','rabbitmqctl','add_vhost','/lab7'],cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
queue=r'^attachment\.process\.v1$'
for user_key,pass_key,can_read in [('RABBIT_API_USER','RABBIT_API_PASSWORD',False),('RABBIT_WORKER_USER','RABBIT_WORKER_PASSWORD',True)]:
user=env[user_key]; password=env[pass_key]
added=subprocess.run(['docker','compose','exec','-T','broker','su-exec','rabbitmq','rabbitmqctl','add_user',user,password],cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
if added.returncode:
run('docker','compose','exec','-T','broker','su-exec','rabbitmq','rabbitmqctl','change_password',user,password,stdout=subprocess.DEVNULL)
run('docker','compose','exec','-T','broker','su-exec','rabbitmq','rabbitmqctl','set_permissions','-p','/lab7',user,
queue,r'^amq\.default$',queue if can_read else r'^$',stdout=subprocess.DEVNULL)
run('docker','compose','exec','-T','broker','su-exec','rabbitmq','rabbitmqctl','list_permissions','-p','/lab7',stdout=subprocess.DEVNULL)
def render_grafana():
cert=(PKI/'service-ca.crt').read_text()
client_cert=(PKI/'backend-grafana.crt').read_text()
client_key=(PKI/'backend-grafana.key').read_text()
source=ROOT/'infra/observability/grafana/datasources.json.template'
data=json.loads(source.read_text())
replacements={'@@CA@@':cert,'@@CLIENT_CERT@@':client_cert,'@@CLIENT_KEY@@':client_key}
def walk(v):
if isinstance(v,dict): return {k:walk(x) for k,x in v.items()}
if isinstance(v,list): return [walk(x) for x in v]
if isinstance(v,str) and v in replacements: return replacements[v]
return v
dest=LOCAL/'grafana/provisioning/datasources.json'
write(dest,json.dumps(walk(data),indent=2)+'\n',0o600)
def main():
make_env(); create_pki(); env=env_values(); ROLES.mkdir(parents=True,exist_ok=True); ROLES.chmod(0o700)
create_s3_config(env)
# Create and start only the trust-anchor and stateful dependency services first.
run('docker','compose','--env-file','.env','up','-d','postgres-cert-init','postgres','openbao','broker','master','volume','filer','s3')
deadline=time.time()+120
while time.time()<deadline:
state=subprocess.run(['docker','compose','ps','--format','json','postgres','broker'],cwd=ROOT,stdout=subprocess.PIPE,text=True)
lines=[json.loads(line) for line in state.stdout.splitlines() if line.strip()]
if len(lines)==2 and all(x.get('Health')=='healthy' for x in lines): break
time.sleep(2)
else: raise RuntimeError('PostgreSQL or RabbitMQ did not become healthy')
initialize_openbao(env)
init_rabbit(env)
run('docker','compose','--env-file','.env','run','--rm','s3-init')
run('docker','compose','--env-file','.env','run','--rm','migrate')
render_grafana()
run('docker','compose','--env-file','.env','up','-d','--build')
print('Waiting for HTTPS ingress and internal mTLS health checks...')
context=ssl.create_default_context(cafile=str(PKI/'external-ca.crt'))
url='https://localhost:'+env['PUBLIC_PORT']+'/health/ready'
deadline=time.time()+120
while time.time()<deadline:
try:
with urllib.request.urlopen(url,context=context,timeout=3) as response:
if response.status==200:
print('PASS: HTTPS ingress and required LB-to-API mTLS are ready.')
return
except Exception:
time.sleep(2)
raise RuntimeError('HTTPS ingress did not become ready; inspect docker compose logs')
if __name__=='__main__':
main()
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# Keep OpenBao unsealed; restart application stateful dependencies and services only.
docker compose restart postgres s3 broker api1 api2 worker lb
for _ in $(seq 1 60); do
if docker compose exec -T worker python -c "from app.secrets import load_secrets; load_secrets(); import psycopg,os; c=psycopg.connect(os.environ['DATABASE_URL']); c.execute('SELECT 1'); c.close()" >/dev/null 2>&1; then
exit 0
fi
sleep 1
done
exit 1
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
for service in api1 api2; do
cid=$(docker compose ps -q "$service")
[ -n "$cid" ] || continue
identity=$(docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' "$cid" | sed -n 's/^APP_INSTANCE_ID=//p')
if [ "$identity" = "$TARGET_INSTANCE_ID" ]; then
docker compose stop -t 2 "$service"
exit 0
fi
done
echo 'Target instance not found' >&2
exit 1
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
"""Unseal file-backed OpenBao with operator-held local recovery shares."""
import json
from pathlib import Path
from bootstrap import BAO, bao_request
operator=json.loads((BAO/'operator.json').read_text())
keys=operator.get('keys') or operator.get('keys_base64') or []
if len(keys)<2: raise SystemExit('OpenBao operator recovery material is incomplete')
_,health=bao_request('sys/health')
if not health.get('sealed',True):
print('OpenBao is already unsealed.')
raise SystemExit(0)
for key in keys[:2]:
_,health=bao_request('sys/unseal','POST',{'key':key})
if health.get('sealed',True): raise SystemExit('OpenBao remains sealed; inspect operator recovery shares locally.')
print('OpenBao unsealed; operator shares were not printed.')
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
"""Reproduce public acceptance, TLS-negative and local least-privilege checks."""
import datetime
import json
import os
from pathlib import Path
import ssl
import subprocess
import sys
import time
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
os.chdir(ROOT)
PUBLIC_PORT = os.getenv('PUBLIC_PORT', '8443')
BASE_URL = 'https://localhost:' + PUBLIC_PORT
CA_FILE = str(ROOT / '.local' / 'pki' / 'external-ca.crt')
def command(*args):
print('\n$ ' + ' '.join(map(str, args)), flush=True)
subprocess.run(list(map(str, args)), check=True)
def wait():
context = ssl.create_default_context(cafile=CA_FILE)
for _ in range(120):
try:
with urllib.request.urlopen(BASE_URL + '/health/ready', context=context, timeout=3) as response:
if response.status == 200:
status = subprocess.check_output(['docker', 'compose', 'ps', '--format', 'json', 'api1', 'api2'], text=True)
docs = [json.loads(line) for line in status.splitlines() if line.strip()]
if len(docs) == 2 and all(doc.get('Health') == 'healthy' for doc in docs):
return
except Exception:
pass
time.sleep(1)
raise RuntimeError('HTTPS ingress or API replicas did not become ready')
def state():
ids = subprocess.check_output(['docker', 'compose', 'ps', '-q'], text=True).split()
if ids:
command('docker', 'inspect', '--format', '{{.Name}} {{.Config.Hostname}} {{.State.Status}} {{.State.StartedAt}}', *ids)
print('Verification UTC:', datetime.datetime.now(datetime.timezone.utc).isoformat(), flush=True)
command('docker', 'compose', 'config', '--quiet')
command(sys.executable, 'scripts/check_contract.py')
wait()
command('docker', 'compose', 'ps')
command(sys.executable, 'tests/smoke.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
command(sys.executable, 'tests/security.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
command(sys.executable, 'tests/security_runtime.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
command(sys.executable, 'tests/acceptance_extra.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
command(sys.executable, 'tests/worker_flow.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
command(sys.executable, 'tests/retry_limit.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
print('\nBefore persistence:', flush=True)
state()
command(sys.executable, 'tests/resilience.py', '--mode', 'persistence', '--action-script', 'scripts/restart.sh',
'--base-url', BASE_URL, '--ca-file', CA_FILE)
wait()
print('\nAfter persistence:', flush=True)
state()
command(sys.executable, 'tests/resilience.py', '--mode', 'failover', '--action-script', 'scripts/stop-one.sh',
'--base-url', BASE_URL, '--ca-file', CA_FILE)
state()
command('docker', 'compose', 'ps', '--all')
command('docker', 'compose', 'up', '-d', 'api1', 'api2', 'worker')
wait()
command(sys.executable, 'tests/attachment_failover.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
command(sys.executable, 'tests/storage_failure.py', '--base-url', BASE_URL, '--ca-file', CA_FILE)
wait()
command(sys.executable, 'tests/observability.py')
anonymous_probe = '''import os,ssl,psycopg,urllib.request,urllib.error
from app.secrets import load_secrets
load_secrets()
with psycopg.connect(os.environ['DATABASE_URL']) as db:
ident=str(db.execute("SELECT id FROM attachments WHERE doc->>'status'='ready' LIMIT 1").fetchone()[0])
url=os.environ['S3_ENDPOINT']+'/'+os.environ['S3_ORIGINAL_BUCKET']+'/original/'+ident
ctx=ssl.create_default_context(cafile=os.environ['S3_CA_CERT'])
try:
urllib.request.urlopen(url,context=ctx,timeout=5)
except urllib.error.HTTPError as e:
assert e.code in (401,403), e.code
print('PASS: anonymous GET of existing private S3 object denied:',e.code)
else:
raise AssertionError('Private object publicly accessible')
'''
print('\nChecking private bucket from the application network', flush=True)
subprocess.run(['docker', 'compose', 'exec', '-T', 'api1', 'python', '-c', anonymous_probe], check=True)
command('docker', 'compose', 'ps')
print('\nPASS: all recorded checks', flush=True)