This commit is contained in:
2026-11-26 23:34:55 +03:00
parent 20afc2c790
commit a25f357314
167 changed files with 33202 additions and 89 deletions
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
umask 077
exec python3 scripts/bootstrap_openbao.py "$@"
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
umask 077
export PKI_DIR="${PKI_DIR:-$PWD/certs}"
export CA_DIR="${CA_DIR:-$PWD/secrets/operator/ca}"
mkdir -p "$PKI_DIR" "$CA_DIR/newcerts"
exec 8> "$CA_DIR/ca.lock"
flock 8
if [[ ! -f "$CA_DIR/ca.key" ]]; then
if [[ -e "$CA_DIR/active" || -L "$CA_DIR/active" || -e "$PKI_DIR/ca.crt" || -L "$PKI_DIR/ca.crt" ]]; then
echo 'CA state exists but its signing key is missing; restore it explicitly, never silently regenerate trust.' >&2
exit 1
fi
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out "$CA_DIR/ca.key" 2>/dev/null
openssl req -new -x509 -sha256 -days 3650 -key "$CA_DIR/ca.key" -out "$PKI_DIR/ca.crt" -subj /CN=Lab7-Root-CA -addext basicConstraints=critical,CA:true -addext keyUsage=critical,keyCertSign,cRLSign
touch "$CA_DIR/index.txt"
echo 1000 > "$CA_DIR/serial"
echo 1000 > "$CA_DIR/crlnumber"
fi
python3 scripts/pki_state.py init
issue() {
local name="$1" san="$2" usage="$3"
local dir="$PKI_DIR/$name"
mkdir -p "$dir"
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out "$dir/$name.key.next" 2>/dev/null
openssl req -new -key "$dir/$name.key.next" -out "$dir/request.csr" -subj "/CN=$name"
cat > "$dir/extensions.cnf" <<EOF
basicConstraints=critical,CA:false
keyUsage=critical,digitalSignature,keyEncipherment
extendedKeyUsage=$usage
subjectAltName=$san
EOF
openssl ca -batch -notext -config "$CA_DIR/openssl.cnf" -extfile "$dir/extensions.cnf" -in "$dir/request.csr" -out "$dir/$name.crt.next" >/dev/null 2>&1
if [[ -f "$dir/$name.crt" ]]; then
cp "$dir/$name.crt" "$CA_DIR/$name.previous.crt"
# During CA overlap an old-generation leaf stays valid until explicit retirement.
# Never import its serial into another issuer's revocation database.
if openssl verify -no_check_time -no-CApath -no-CAstore -CAfile "$CA_DIR/issuer.crt" "$dir/$name.crt" >/dev/null 2>&1; then
serial=$(openssl x509 -in "$dir/$name.crt" -noout -serial | cut -d= -f2)
status=$(openssl ca -config "$CA_DIR/openssl.cnf" -status "$serial" 2>&1 || true)
if [[ "$status" != *Revoked* ]]; then
openssl ca -config "$CA_DIR/openssl.cnf" -revoke "$dir/$name.crt" >/dev/null 2>&1
fi
fi
fi
mv "$dir/$name.key.next" "$dir/$name.key"
mv "$dir/$name.crt.next" "$dir/$name.crt"
chmod 700 "$dir"; chmod 600 "$dir/$name.key"; chmod 644 "$dir/$name.crt"
rm "$dir/request.csr" "$dir/extensions.cnf"
}
if [[ $# -gt 0 ]]; then
name="$1"
case "$name" in
client-api) issue "$name" DNS:client-api clientAuth ;;
lb) issue lb DNS:lb,DNS:localhost,IP:127.0.0.1 serverAuth ;;
openbao|grafana) issue "$name" "DNS:$name,DNS:localhost,IP:127.0.0.1" serverAuth,clientAuth ;;
api|worker|redis|db|minio|otel-collector|prometheus|tempo|loki|collector|operator)
issue "$name" "DNS:$name" serverAuth,clientAuth ;;
*) echo 'Unknown identity' >&2; exit 2 ;;
esac
else
for name in lb api worker db minio redis client-api openbao otel-collector collector prometheus tempo loki grafana operator; do
[[ -f "$PKI_DIR/$name/$name.crt" ]] && continue
case "$name" in
lb) issue lb DNS:lb,DNS:localhost,IP:127.0.0.1 serverAuth ;;
client-api) issue client-api DNS:client-api clientAuth ;;
openbao|grafana) issue "$name" "DNS:$name,DNS:localhost,IP:127.0.0.1" serverAuth,clientAuth ;;
*) issue "$name" "DNS:$name" serverAuth,clientAuth ;;
esac
done
fi
if [[ -f "$PKI_DIR/minio/minio.crt" ]]; then
cp "$PKI_DIR/minio/minio.crt" "$PKI_DIR/minio/public.crt"
cp "$PKI_DIR/minio/minio.key" "$PKI_DIR/minio/private.key"
fi
openssl ca -gencrl -config "$CA_DIR/openssl.cnf" -out "$CA_DIR/active.crl" >/dev/null 2>&1
python3 scripts/pki_state.py publish
chmod 755 "$PKI_DIR"; chmod 644 "$PKI_DIR/ca.crt" "$PKI_DIR/ca.crl"
echo 'PKI ready: private CA stays in secrets/operator/ca; leaf lifetime 7 days.'
+157
View File
@@ -0,0 +1,157 @@
#!/usr/bin/env python3
"""Operator-only provisioning. Never emits secret values or passes them in argv."""
import fcntl, json, os, secrets, ssl, subprocess, sys, time, urllib.request, urllib.error
from pathlib import Path
ROOT=Path(__file__).resolve().parent.parent
os.chdir(ROOT)
os.umask(0o077)
DC=[str(ROOT/'scripts/dc.sh')]
OP=ROOT/'secrets/operator'
def run(*args, data=None):
p=subprocess.run(DC+list(args),input=data,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if p.returncode:
raise RuntimeError('Compose operation failed: '+' '.join(args[:3])+' (details withheld to protect secrets)')
return p.stdout
def save(path,value):
path.parent.mkdir(parents=True,exist_ok=True)
path.write_text(value);path.chmod(0o600)
def secret(name):
path=OP/name
if not path.exists():save(path,secrets.token_hex(24))
return path.read_text().strip()
def prepare():
OP.mkdir(parents=True,exist_ok=True)
for name in ['db-password','minio-user','minio-password','grafana-password','redis-api','redis-worker','s3-api','s3-worker']:secret(name)
for name in ['postgres','redis','minio','openbao','grafana','prometheus','loki','tempo']:
(ROOT/'secrets/state'/name).mkdir(parents=True,exist_ok=True)
# Grafana datasource provisioning embeds public CA and this service's own private key
# in an ignored runtime file; provider expansion is not supported in datasource YAML.
source=next((ROOT/'infra/grafana/provisioning/datasources').glob('*'))
provisioning=json.loads(source.read_text())
for ds in provisioning['datasources']:
ds['secureJsonData']={'tlsCACert':(ROOT/'certs/ca.crt').read_text(),
'tlsClientCert':(ROOT/'certs/grafana/grafana.crt').read_text(),
'tlsClientKey':(ROOT/'certs/grafana/grafana.key').read_text()}
save(ROOT/'secrets/grafana-datasources/datasources.yaml',json.dumps(provisioning))
# Use current operator UID consistently; leaf keys remain 0600, not world-readable.
if not (ROOT/'.env').exists():
save(ROOT/'.env',f'LOCAL_UID={os.getuid()}\nLOCAL_GID={os.getgid()}\nHTTPS_PORT=8443\nBAO_PORT=8200\nGRAFANA_PORT=3000\n')
import hashlib
acl='user default off\n'
for role,commands,keys in [
('api','+ping +get +set +del +eval +incr +expire +xadd','~session:* ~ratelimit:login:* ~jobs:attachments'),
('worker','+ping (+xgroup +xreadgroup +xautoclaim +xack ~jobs:attachments) (+xadd ~jobs:attachments:dlq)','')]:
digest=hashlib.sha256(secret('redis-'+role).encode()).hexdigest()
acl+=f'user {role} on #{digest} {keys} -@all {commands}\n'
save(ROOT/'secrets/redis/users.acl',acl)
for role in ['api','worker']:(ROOT/'secrets/approle'/role).mkdir(parents=True,exist_ok=True)
OP.mkdir(parents=True,exist_ok=True)
bootstrap_lock=(OP/"bootstrap.lock").open("a")
fcntl.flock(bootstrap_lock,fcntl.LOCK_EX)
prepare()
if '--prepare' in sys.argv:
print('Local secret files prepared; .env contains only ports/UID/GID.');sys.exit(0)
run('up','-d','--wait','--wait-timeout','90','db','cache','minio','openbao')
# ACL file changes must become active even when the container already exists.
run('restart','cache')
ctx=ssl.create_default_context(cafile=str(ROOT/'certs/ca.crt'))
local_settings=dict(line.split('=',1) for line in (ROOT/'.env').read_text().splitlines() if '=' in line and not line.startswith('#'))
addr='https://localhost:'+os.environ.get('BAO_PORT',local_settings.get('BAO_PORT','8200'))
token=None
def req(path,body=None):
headers={'Content-Type':'application/json'}
if token:headers['X-Vault-Token']=token
request=urllib.request.Request(addr+'/v1/'+path,data=None if body is None else json.dumps(body).encode(),headers=headers)
with urllib.request.urlopen(request,context=ctx,timeout=10) as r:
b=r.read();return json.loads(b) if b else {}
for _ in range(90):
try:
state=req('sys/seal-status');break
except (OSError,urllib.error.URLError):time.sleep(1)
else:raise RuntimeError('OpenBao TLS listener did not start')
initfile=OP/'bao-init.json'
if not state['initialized']:
# init output is captured only in the operator's private file.
save(initfile,run('exec','-T','openbao','bao','operator','init','-key-shares=1','-key-threshold=1','-format=json'))
init=json.loads(initfile.read_text())
if state['sealed']:req('sys/unseal',{'key':init['unseal_keys_b64'][0]})
token=init['root_token']
# Audit record payloads are HMACed by default; no raw secrets.
if 'file/' not in req('sys/audit'):
req('sys/audit/file',{'type':'file','options':{'file_path':'/bao/data/audit.json'}})
# Migrations run over operator-local Unix socket, never with application credentials.
sql="CREATE TABLE IF NOT EXISTS schema_migrations(version int PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now());"
run('exec','-T','db','psql','-U','postgres','-d','messenger','-v','ON_ERROR_STOP=1',data=sql)
applied=set(run('exec','-T','db','psql','-U','postgres','-d','messenger','-Atc','SELECT version FROM schema_migrations').split())
for p in sorted((ROOT/'migrations').glob('*.sql')):
version=int(p.name.split('_')[0])
if str(version) not in applied:
run('exec','-T','db','psql','-U','postgres','-d','messenger','-v','ON_ERROR_STOP=1',data='BEGIN;\n'+p.read_text()+f'\nINSERT INTO schema_migrations(version) VALUES({version});COMMIT;')
roles_sql="""
DO $$ BEGIN
IF NOT EXISTS(SELECT FROM pg_roles WHERE rolname='api_access') THEN CREATE ROLE api_access NOLOGIN; END IF;
IF NOT EXISTS(SELECT FROM pg_roles WHERE rolname='worker_access') THEN CREATE ROLE worker_access NOLOGIN; END IF;
END $$;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO api_access,worker_access;
GRANT SELECT,INSERT,UPDATE,DELETE ON ALL TABLES IN SCHEMA public TO api_access;
GRANT USAGE,SELECT ON ALL SEQUENCES IN SCHEMA public TO api_access;
REVOKE ALL ON schema_migrations FROM api_access;
GRANT SELECT,UPDATE ON attachments,jobs TO worker_access;
GRANT SELECT,INSERT,UPDATE ON attachment_results TO worker_access;
GRANT SELECT ON direct_uploads,outbox TO worker_access;
"""
run('exec','-T','db','psql','-U','postgres','-d','messenger','-v','ON_ERROR_STOP=1',data=roles_sql)
mounts=req('sys/mounts')
for name,typ in [('database','database'),('secret','kv')]:
if name+'/' not in mounts:req('sys/mounts/'+name,{'type':typ,**({'options':{'version':'2'}} if typ=='kv' else {})})
# OpenBao DB manager bootstraps using postgres; its secret is held only by the operator/Bao.
req('database/config/messenger',{'plugin_name':'postgresql-database-plugin','allowed_roles':['api-role','worker-role'],
'connection_url':'postgresql://{{username}}:{{password}}@db:5432/messenger?sslmode=verify-full&sslrootcert=/pki/ca.crt&sslcert=/identity/openbao.crt&sslkey=/identity/openbao.key',
'username':'postgres','password':secret('db-password')})
if 'approle/' not in req('sys/auth'):req('sys/auth/approle',{'type':'approle'})
for role in ['api','worker']:
creation=f'''CREATE ROLE "{{{{name}}}}" WITH LOGIN PASSWORD '{{{{password}}}}' VALID UNTIL '{{{{expiration}}}}' IN ROLE {role}_access;'''
req('database/roles/'+role+'-role',{'db_name':'messenger','creation_statements':[creation],
'revocation_statements':['''SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='{{name}}'; DROP ROLE IF EXISTS "{{name}}";'''],
'default_ttl':'15m','max_ttl':'1h'})
policy=f'''path "database/creds/{role}-role" {{ capabilities=["read"] }}
path "secret/data/{role}" {{ capabilities=["read"] }}
path "sys/leases/renew" {{ capabilities=["update"] }}
path "auth/token/renew-self" {{ capabilities=["update"] }}
path "auth/token/revoke-self" {{ capabilities=["update"] }}
'''
(ROOT/'infra/openbao'/f'{role}.hcl').write_text(policy)
req('sys/policies/acl/'+role,{'policy':policy})
req('auth/approle/role/'+role,{'token_policies':[role],'token_no_default_policy':True,
'token_ttl':'15m','token_max_ttl':'1h','secret_id_ttl':'24h','secret_id_num_uses':0})
previous=ROOT/'secrets/approle'/role/'secret-id'
if previous.exists():
try:req('auth/approle/role/'+role+'/secret-id/destroy',{'secret_id':previous.read_text()})
except urllib.error.HTTPError as e:
if e.code != 404:raise
save(ROOT/'secrets/approle'/role/'role-id',req('auth/approle/role/'+role+'/role-id')['data']['role_id'])
save(ROOT/'secrets/approle'/role/'secret-id',req('auth/approle/role/'+role+'/secret-id',{})['data']['secret_id'])
req('secret/data/'+role,{'data':{'redis_url':f'rediss://{role}:{secret("redis-"+role)}@redis:6379/0',
's3_access_key':'messenger-'+role,'s3_secret_key':secret('s3-'+role)}})
# mc configuration and credentials live exclusively in its ephemeral /tmp.
script='''set -eu
mc alias set local https://minio:9000 "$(cat /operator/minio-user)" "$(cat /operator/minio-password)" >/dev/null
mc mb --ignore-existing local/attachments >/dev/null
mc anonymous set none local/attachments >/dev/null
'''
for role in ['api','worker']:
# Track 2 chosen: worker needs all staging objects for lab6 processing and cleanup.
actions=['s3:GetObject','s3:PutObject','s3:DeleteObject','s3:AbortMultipartUpload','s3:ListMultipartUploadParts']
policy={'Version':'2012-10-17','Statement':[{'Effect':'Allow','Action':['s3:GetBucketLocation','s3:ListBucket'],'Resource':['arn:aws:s3:::attachments']},{'Effect':'Allow','Action':actions,'Resource':['arn:aws:s3:::attachments/staging/*','arn:aws:s3:::attachments/attachments/*']}]}
script+=f"cat > /tmp/{role}.json <<'POLICY'\n{json.dumps(policy)}\nPOLICY\n"
script+=f'mc admin user add local messenger-{role} "$(cat /operator/s3-{role})" >/dev/null\n'
script+=f'mc admin policy create local {role} /tmp/{role}.json >/dev/null\n'
script+=f'mc admin policy attach local {role} --user messenger-{role} >/dev/null\n'
run('run','--rm','-T','mc','-s',data=script)
print('OpenBao initialized/unsealed, database roles, scoped AppRoles, S3 policies provisioned. No secret values printed.')
print('Protect secrets/operator/bao-init.json: lab auto-unseal uses it; production requires offline custody/external unseal.')
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
exec python3 scripts/ca_rollover.py "$@"
+183
View File
@@ -0,0 +1,183 @@
#!/usr/bin/env python3
"""Three-phase root rollover. Offline mode is restricted to an isolated test PKI."""
import argparse,contextlib,fcntl,json,os,secrets,shutil,subprocess,time
from pathlib import Path
import pki_state as pki
from resilience_hooks import command,DC,ROOT
CANARIES=('client-api','api','grafana','prometheus','otel-collector')
ENDPOINTS=[
('lb',443,'lb','api','/health/ready'),
('api-tls',8443,'api','client-api','/health/ready'),('api2-tls',8443,'api','client-api','/health/ready'),
('minio',9000,'minio','api','/minio/health/live'),('openbao',8200,'openbao','api','/v1/sys/seal-status'),
('otel-collector',4318,'otel-collector','api','/v1/traces'),('otel-collector-tls',9464,'otel-collector','prometheus','/metrics'),
('loki-tls',3100,'loki','grafana','/ready'),('tempo-tls',4318,'tempo','otel-collector','/v1/traces'),
('tempo-tls',3200,'tempo','grafana','/ready'),('prometheus-tls',9090,'prometheus','grafana','/-/ready'),
('grafana-tls',3000,'grafana','api','/api/health')]
@contextlib.contextmanager
def ca_lock():
with (pki.CA/'ca.lock').open('a') as f:
fcntl.flock(f,fcntl.LOCK_EX);yield
def record(s,phase,details):
s.setdefault('events',[]).append({'phase':phase,'unix_time':time.time(),**details})
pki.save_state(s)
if not OFFLINE:
public={k:v for k,v in s.items() if k not in ('events',)}
public['events']=s['events']
pki.atomic(ROOT/'evidence/ca-rollover.json',json.dumps(public,indent=2)+'\n',0o644)
def verify_leaf(cert,root):
p=pki.openssl('verify','-no_check_time','-no-CApath','-no-CAstore','-CAfile',root,cert)
return p
def new_authority():
directory=pki.CA/'generations'/('.pending-'+secrets.token_hex(6));directory.mkdir(mode=0o700)
pki.openssl('genpkey','-algorithm','RSA','-pkeyopt','rsa_keygen_bits:3072','-out',directory/'ca.key')
pki.openssl('req','-new','-x509','-sha256','-days','3650','-key',directory/'ca.key','-out',directory/'issuer.crt',
'-subj','/CN=Lab7-Root-CA-'+time.strftime('%Y%m%d%H%M%S',time.gmtime())+'-'+secrets.token_hex(3),
'-addext','basicConstraints=critical,CA:true','-addext','keyUsage=critical,keyCertSign,cRLSign')
fp=pki.fingerprint(directory/'issuer.crt');target=pki.authority(fp);os.replace(directory,target)
(target/'newcerts').mkdir();pki.atomic(target/'index.txt',b'')
pki.atomic(target/'serial',secrets.token_hex(8)+'\n');pki.atomic(target/'crlnumber','1000\n')
pki.atomic(target/'openssl.cnf',pki.config(target));pki.generate_crl(target)
return target
def canaries(directory):
for role in CANARIES:
out=directory/'canaries'/role;out.mkdir(parents=True,mode=0o700,exist_ok=True)
if (out/(role+'.crt')).exists():continue
pki.openssl('genpkey','-algorithm','RSA','-pkeyopt','rsa_keygen_bits:2048','-out',out/(role+'.key'))
pki.openssl('req','-new','-key',out/(role+'.key'),'-subj','/CN=rollover-canary-'+role,'-out',out/'request.csr')
pki.atomic(out/'extensions.cnf',f'basicConstraints=critical,CA:false\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=clientAuth\nsubjectAltName=DNS:{role}\n')
pki.openssl('ca','-batch','-notext','-config',directory/'openssl.cnf','-extfile',out/'extensions.cnf','-in',out/'request.csr','-out',out/(role+'.crt'))
pki.generate_crl(directory)
def reload_stack(phase):
if OFFLINE:return
env=dict(os.environ,HOOK_EVIDENCE_FILE='evidence/ca-'+phase+'-restart.json')
p=subprocess.run([str(ROOT/'scripts/restart.sh')],cwd=ROOT,env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=110)
if p.returncode:raise RuntimeError('Rollover restart hook failed; dual trust is retained until recovery')
def client_directory(s,role,canary=False):
return pki.authority(s['new'])/'canaries'/role if canary else pki.PKI/role
def probe_args(ca,client,role):
return ['run','--rm','-T','--no-deps','-v',str(ca)+':/verify/ca.crt:ro','-v',str(client)+':/probe-client:ro','--entrypoint']
def http_probe(host,port,name,role,ca,client,path):
args=probe_args(ca,client,role)+['curl','api','--silent','--show-error','--connect-timeout','3','--max-time','8',
'--cacert','/verify/ca.crt','--cert','/probe-client/'+role+'.crt','--key','/probe-client/'+role+'.key',
'--connect-to',f'{name}:{port}:{host}:{port}','--output','/dev/null','--write-out','%{http_code}',f'https://{name}:{port}/'+path.lstrip('/')]
p=subprocess.run(DC+args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20)
if p.returncode or not p.stdout.strip().isdigit() or int(p.stdout.strip())==0:
raise RuntimeError('TLS endpoint verification failed: '+host+':'+str(port))
return {'endpoint':host+':'+str(port),'server_name':name,'http_status':int(p.stdout.strip())}
def protocol_probe(host,port,name,ca,client,postgres=False):
args=probe_args(ca,client,'api')+['/usr/bin/timeout','api','--kill-after=1s','4s','openssl','s_client','-quiet','-ign_eof',
'-connect',f'{host}:{port}','-servername',name,'-verify_hostname',name,'-verify_return_error','-CAfile','/verify/ca.crt',
'-cert','/probe-client/api.crt','-key','/probe-client/api.key']
if postgres:
import struct
args+=['-starttls','postgres'];body=b'user\0pki_probe\0database\0messenger\0\0'
payload=struct.pack('!II',len(body)+8,196608)+body
else:payload=b'PING\r\n'
p=subprocess.run(DC+args,input=payload,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=15)
accepted=(p.stdout.startswith(b'R') if postgres else b'NOAUTH' in p.stdout)
if p.returncode not in (0,124) or not accepted:
raise RuntimeError('TLS protocol/application response failed: '+host)
return {'endpoint':host+':'+str(port),'server_name':name,'application_response':'PostgreSQL Authentication' if postgres else 'Redis NOAUTH'}
def probes(s,new_only=False,canary=False):
if OFFLINE:return []
ca=pki.authority(s['new'])/'issuer.crt' if new_only else pki.PKI/'ca.crt'
result=[]
for host,port,name,role,path in ENDPOINTS:
result.append(http_probe(host,port,name,role,ca,client_directory(s,role,canary),path))
result.append(protocol_probe('db',5432,'db',ca,client_directory(s,'api',canary),True))
result.append(protocol_probe('redis',6379,'redis',ca,client_directory(s,'api',canary)))
return result
def old_client_probe(s,deny):
if OFFLINE:return
directory=pki.authority(s['old'])/'old-client-api'
for host in ('api-tls','api2-tls'):
args=probe_args(pki.PKI/'ca.crt',directory,'client-api')+['curl','api','--silent','--show-error','--fail','--connect-timeout','3','--max-time','8',
'--cacert','/verify/ca.crt','--cert','/probe-client/client-api.crt','--key','/probe-client/client-api.key',
'--connect-to',f'api:8443:{host}:8443','https://api:8443/health/ready']
p=subprocess.run(DC+args,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20)
assert (p.returncode in (35,52,55,56)) if deny else p.returncode==0,host+' old-root identity verification'
def prepare():
with ca_lock():
pki.ensure_layout();s=pki.state()
if not s or s['phase']=='retired':
old=pki.active();new=new_authority();canaries(new)
saved=old/'old-client-api';saved.mkdir(mode=0o700,exist_ok=True)
for ext in ('crt','key'):shutil.copy2(pki.PKI/'client-api'/('client-api.'+ext),saved/('client-api.'+ext))
s={'old':old.name,'new':new.name,'phase':'overlap','trust_distributed':False,'offline_test':OFFLINE,'events':[]}
pki.save_state(s)
if s['phase']!='overlap':raise RuntimeError('prepare is only valid before leaf reissue')
pki.publish()
reload_stack('overlap')
checks=probes(s,canary=True);old_client_probe(s,False)
with ca_lock():
s['trust_distributed']=True;record(s,'overlap',{'trusted_roots':2,'new_root_client_checks':checks,'old_root_client':'accepted'})
print(('OFFLINE model' if OFFLINE else 'PASS')+': old and new roots trusted; old leaves retained; new-root client identities accepted',flush=True)
def reissue():
with ca_lock():
s=pki.state();assert s and s['phase'] in ('overlap','reissued') and s['trust_distributed'],'Distribute/verify dual trust first'
if pki.active().name!=s['new']:
assert pki.active().name==s['old'];pki.link(pki.CA/'active',Path('generations')/s['new'])
pki.publish()
for role in pki.ROLES:
cert=pki.PKI/role/(role+'.crt')
try:verify_leaf(cert,pki.authority(s['new'])/'issuer.crt')
except RuntimeError:
env=dict(os.environ,PKI_DIR=str(pki.PKI),CA_DIR=str(pki.CA))
p=subprocess.run([str(ROOT/'scripts/bootstrap-pki.sh'),role],env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if p.returncode:raise RuntimeError('Leaf reissue failed: '+role)
verify_leaf(cert,pki.authority(s['new'])/'issuer.crt')
with ca_lock():s['phase']='reissued';pki.save_state(s);pki.publish()
reload_stack('reissued');checks=probes(s,new_only=True);old_client_probe(s,False)
with ca_lock():record(s,'reissued',{'trusted_roots':2,'new_root_server_checks':checks,'old_root_client':'accepted during overlap','leaf_roles':list(pki.ROLES)})
print(('OFFLINE model' if OFFLINE else 'PASS')+': all leaf/server identities switched to the new CA; overlap still accepts old clients',flush=True)
def revoke(directory,certificate):
serial=pki.openssl('x509','-in',certificate,'-noout','-serial').decode().strip().split('=')[1]
rows=[r.split('\t') for r in (directory/'index.txt').read_text().splitlines()]
if not any(r[0]=='R' and r[3].upper()==serial.upper() for r in rows):
pki.openssl('ca','-config',directory/'openssl.cnf','-revoke',certificate)
def retire():
s=pki.state();assert s and s['phase'] in ('reissued','retired'),'Reissue every leaf before retirement'
for role in pki.ROLES:verify_leaf(pki.PKI/role/(role+'.crt'),pki.authority(s['new'])/'issuer.crt')
# Never remove old trust until every actual TLS endpoint proves its new chain.
checks=probes(s,new_only=True)
with ca_lock():
old=pki.authority(s['old']);new=pki.authority(s['new'])
for row in (old/'index.txt').read_text().splitlines():
parts=row.split('\t')
cert=old/'newcerts'/(parts[3]+'.pem')
if parts[0]=='V' and cert.exists():revoke(old,cert)
revoke(old,old/'issuer.crt');pki.generate_crl(old)
for role in CANARIES:revoke(new,new/'canaries'/role/(role+'.crt'))
pki.generate_crl(new)
s['phase']='retired';pki.save_state(s);pki.publish()
reload_stack('retired');checks=probes(s,new_only=True);old_client_probe(s,True)
with ca_lock():record(s,'retired',{'trusted_roots':1,'old_ca_revocation_recorded':True,'old_root_client':'rejected on both API replicas','new_root_server_checks':checks})
print(('OFFLINE model' if OFFLINE else 'PASS')+': old CA/leaf revocations recorded; old trust anchor removed; old identities rejected',flush=True)
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('phase',choices=['prepare','reissue','retire','all']);parser.add_argument('--offline',action='store_true');args=parser.parse_args()
OFFLINE=args.offline
assert not OFFLINE or (pki.PKI!=ROOT/'certs' and pki.CA!=ROOT/'secrets/operator/ca'),'Offline mode requires isolated test paths'
os.umask(0o077);pki.CA.mkdir(parents=True,exist_ok=True)
# Same operator lock as cron; each CA mutation also takes the signing DB lock.
with (pki.CA.parent/'pki.lock').open('a') as operator_lock:
fcntl.flock(operator_lock,fcntl.LOCK_EX)
if args.phase=='all':prepare();reissue();retire()
else:{'prepare':prepare,'reissue':reissue,'retire':retire}[args.phase]()
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
image="${1:-postgres:16.15-alpine}"
scripts/docker.sh run --rm --network none --user "${PROBE_UID:-$(id -u)}:${PROBE_GID:-$(id -g)}" \
--read-only --cap-drop ALL --security-opt no-new-privileges:true \
--entrypoint /bin/sh "$image" -ec '
test "$(id -u)" -ne 0
grep -Eq "^NoNewPrivs:[[:space:]]+1$" /proc/self/status
grep -Eq "^CapEff:[[:space:]]+0+$" /proc/self/status
echo "PASS: non-root, read_only, cap_drop=ALL, NoNewPrivs=1"
'
Executable
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
if scripts/docker.sh compose version >/dev/null 2>&1; then
exec scripts/docker.sh compose --project-directory "$PWD" "$@"
fi
if [[ -x /snap/docker/current/usr/libexec/docker/cli-plugins/docker-compose ]]; then
exec /snap/docker/current/usr/libexec/docker/cli-plugins/docker-compose --project-directory "$PWD" "$@"
fi
echo 'Docker Compose v2 plugin is required.' >&2
exit 1
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ -n "${DOCKER_BIN:-}" ]]; then exec "$DOCKER_BIN" "$@"; fi
if [[ -x /usr/bin/docker ]]; then exec /usr/bin/docker "$@"; fi
if [[ -x /snap/docker/current/bin/docker ]]; then exec /snap/docker/current/bin/docker "$@"; fi
exec docker "$@"
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env bash
# Review before running: sudo bash scripts/install-native-docker.sh --install
# Does not remove Snap, its image/volume storage, or lab7 bind data.
set -euo pipefail
cd "$(dirname "$0")/.."
root="$PWD"
case "${1:---check}" in
--check) exec scripts/check-docker-hardening.sh ;;
--install) ;;
*) echo 'Usage: install-native-docker.sh [--check|--install]' >&2; exit 2 ;;
esac
[[ "$EUID" -eq 0 ]] || { echo 'Run from your terminal: sudo bash scripts/install-native-docker.sh --install' >&2; exit 1; }
command -v apt-get >/dev/null
command -v snap >/dev/null
command -v systemctl >/dev/null
# Global daemon switching is permitted only while no existing container is running.
snap_cli=/snap/docker/current/bin/docker
if systemctl is-active --quiet docker.service && ! systemctl is-active --quiet snap.docker.dockerd.service; then
operator="${SUDO_USER:?Invoke via sudo as the repository owner}"
exec env DOCKER_BIN=/usr/bin/docker PROBE_UID="$(id -u "$operator")" PROBE_GID="$(id -g "$operator")" scripts/check-docker-hardening.sh
fi
[[ -x "$snap_cli" ]]
[[ -z "$("$snap_cli" ps -q)" ]] || { echo 'Stop existing containers safely before switching Docker daemons. Nothing changed.' >&2; exit 1; }
mkdir -p build/docker-migration
chmod 700 build/docker-migration
# Export only the images used by this repository; no volume or secrets export.
mapfile -t images < <(scripts/dc.sh --profile operator config --images | sort -u)
[[ "${#images[@]}" -gt 0 ]]
for image in "${images[@]}"; do "$snap_cli" image inspect "$image" >/dev/null; done
"$snap_cli" image save -o "$root/build/docker-migration/lab7-images.tar" "${images[@]}"
chmod 600 build/docker-migration/lab7-images.tar
[[ -z "$("$snap_cli" ps -q)" ]] || { echo 'A container started during image export; aborting without stopping it.' >&2; exit 1; }
restore_snap() {
echo 'Native Docker installation failed; restoring the Snap daemon without deleting either storage.' >&2
systemctl disable --now docker.service docker.socket 2>/dev/null || true
snap enable docker >/dev/null 2>&1 || true
snap start docker >/dev/null 2>&1 || true
}
trap restore_snap ERR
# Reversible: Snap package and /var/snap/docker data are preserved.
snap stop docker
snap disable docker
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y docker.io docker-compose-v2
systemctl enable --now docker.service
/usr/bin/docker image load -i "$root/build/docker-migration/lab7-images.tar"
# Materialize platform-specific public image blobs after a cross-version import.
scripts/dc.sh --profile operator pull --ignore-buildable
# Use the operator UID for the actual non-root probe, not root's UID.
operator="${SUDO_USER:?Invoke via sudo as the repository owner}"
uid=$(id -u "$operator")
gid=$(id -g "$operator")
/usr/bin/docker run --rm --network none --user "$uid:$gid" --read-only --cap-drop ALL \
--security-opt no-new-privileges:true --entrypoint /bin/sh postgres:16.15-alpine -ec '
test "$(id -u)" -ne 0
grep -Eq "^NoNewPrivs:[[:space:]]+1$" /proc/self/status
grep -Eq "^CapEff:[[:space:]]+0+$" /proc/self/status
echo "PASS: native Docker starts non-root with NoNewPrivs=1 and no capabilities"
'
trap - ERR
if ! id -nG "$operator" | tr ' ' '\n' | grep -qx docker; then
usermod -aG docker "$operator"
echo 'Docker group added. Start a new login session before non-sudo Docker commands.'
fi
printf 'Native Docker ready. Snap storage and all lab7 data preserved.\n'
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
root="$PWD"
command -v crontab >/dev/null || { echo 'Install cron before enabling host certificate renewal.' >&2; exit 1; }
(crontab -l 2>/dev/null | sed '\|# lab7-pki-renew$|d' || true
printf '0 */12 * * * cd %q && scripts/renew-pki.sh >> secrets/operator/renewal.log 2>&1 # lab7-pki-renew\n' "$root") | crontab -
echo 'Installed operator certificate renewal every 12 hours.'
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Private per-generation CA database; public atomic trust/CRL bundles only."""
import json,os,re,secrets,shutil,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parent.parent
PKI=Path(os.environ.get('PKI_DIR',ROOT/'certs')).resolve()
CA=Path(os.environ.get('CA_DIR',ROOT/'secrets/operator/ca')).resolve()
ROLES=('lb','api','worker','db','minio','redis','client-api','openbao','otel-collector','collector','prometheus','tempo','loki','grafana','operator')
def openssl(*args,data=None):
p=subprocess.run(['openssl',*map(str,args)],input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if p.returncode:raise RuntimeError('OpenSSL operation failed: '+str(args[0])+' (private command output withheld)')
return p.stdout
def atomic(path,data,mode=0o600):
path=Path(path);path.parent.mkdir(parents=True,exist_ok=True)
temp=path.with_name(path.name+'.tmp-'+secrets.token_hex(4))
fd=os.open(temp,os.O_WRONLY|os.O_CREAT|os.O_EXCL,mode)
try:
with os.fdopen(fd,'wb') as f:f.write(data if isinstance(data,bytes) else data.encode());f.flush();os.fsync(f.fileno())
os.chmod(temp,mode);os.replace(temp,path)
finally:
if temp.exists():temp.unlink()
def link(path,target):
path=Path(path);temp=path.with_name(path.name+'.link-'+secrets.token_hex(4))
temp.symlink_to(target);os.replace(temp,path)
def fingerprint(cert):
return openssl('x509','-in',cert,'-noout','-fingerprint','-sha256').decode().strip().split('=')[1].replace(':','').lower()
def config(directory):
directory=Path(directory)
return f'''[ca]
default_ca=local
[local]
dir={directory}
database=$dir/index.txt
new_certs_dir=$dir/newcerts
certificate=$dir/issuer.crt
private_key=$dir/ca.key
serial=$dir/serial
crlnumber=$dir/crlnumber
default_md=sha256
default_days=7
default_crl_days=7
policy=policy
unique_subject=no
[policy]
commonName=supplied
'''
def state():
path=CA/'rollover.json'
return json.loads(path.read_text()) if path.exists() else None
def save_state(s):atomic(CA/'rollover.json',json.dumps(s,indent=2)+'\n')
def authority(identifier):
assert re.fullmatch('[0-9a-f]{64}',identifier),'Invalid CA generation'
return CA/'generations'/identifier
def active():return (CA/'active').resolve(strict=True)
def generate_crl(directory):
directory=Path(directory)
raw=openssl('ca','-gencrl','-config',directory/'openssl.cnf')
atomic(directory/'ca.crl',raw,0o644)
def ensure_layout():
"""Called under the CA lock, after initial root creation in bootstrap-pki."""
CA.mkdir(parents=True,exist_ok=True);(CA/'generations').mkdir(exist_ok=True)
(PKI/'trust').mkdir(parents=True,exist_ok=True);os.chmod(PKI/'trust',0o755)
if not (CA/'active').exists():
root_cert=PKI/'ca.crt'
certs=re.findall(rb'-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----\s*',root_cert.read_bytes(),re.S)
assert len(certs)==1,'Initial migration needs exactly one root certificate'
fp=fingerprint(root_cert);directory=authority(fp)
directory.mkdir(mode=0o700,exist_ok=True)
# Copy first; until the active pointer exists, the legacy CA remains intact.
for pattern in ('ca.key','index.txt*','serial*','crlnumber*'):
for src in CA.glob(pattern):
if src.is_file() and not (directory/src.name).exists():shutil.copy2(src,directory/src.name)
if not (directory/'newcerts').exists():shutil.copytree(CA/'newcerts',directory/'newcerts')
atomic(directory/'issuer.crt',certs[0],0o644)
atomic(directory/'openssl.cnf',config(directory))
crl=PKI/'ca.crl'
if crl.exists():atomic(directory/'ca.crl',crl.read_bytes(),0o644)
else:generate_crl(directory)
link(CA/'active',Path('generations')/fp)
# All signing paths resolve through one atomic generation pointer.
for name,target in [('ca.key','ca.key'),('issuer.crt','issuer.crt'),('index.txt','index.txt'),('serial','serial'),('crlnumber','crlnumber'),('active.crl','ca.crl')]:
link(CA/name,Path('active')/target)
atomic(CA/'openssl.cnf',config(CA/'active'))
for name in ('ca.crt','ca.crl'):
path=PKI/name
if path.exists() and not path.is_symlink() and not (PKI/'trust'/name).exists():atomic(PKI/'trust'/name,path.read_bytes(),0o644)
link(path,Path('trust')/name)
publish()
def publish():
s=state()
directories=[active()]
if s and s['phase']=='retired':
assert active().name==s['new'],'Refusing to restore a retired trust anchor'
if s and s['phase'] in ('overlap','reissued'):
directories=[authority(s['old']),authority(s['new'])]
for directory in directories:
if not (directory/'ca.crl').exists():generate_crl(directory)
atomic(PKI/'trust/ca.crt',b''.join((d/'issuer.crt').read_bytes() for d in directories),0o644)
atomic(PKI/'trust/ca.crl',b''.join((d/'ca.crl').read_bytes() for d in directories),0o644)
if __name__=='__main__':
import sys
{'init':ensure_layout,'publish':publish}[sys.argv[1]]()
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
# Operator cron: 0 */12 * * * cd /path/to/lab7 && scripts/renew-pki.sh
set -euo pipefail
cd "$(dirname "$0")/.."
exec 9> secrets/operator/pki.lock
flock -n 9 || exit 0
for identity in lb api worker db minio redis client-api openbao otel-collector prometheus tempo loki grafana operator; do
if ! openssl x509 -checkend 172800 -noout -in "certs/$identity/$identity.crt" >/dev/null; then
scripts/bootstrap-pki.sh "$identity"
fi
done
# Refresh CRL even when no leaf is due; invalidate cached TLS state by restarting proxies.
scripts/bootstrap-pki.sh
scripts/dc.sh restart lb api-tls api2-tls otel-collector-tls prometheus-tls tempo-tls loki-tls grafana-tls cache minio openbao
scripts/dc.sh exec -T db psql -U postgres -d messenger -c 'SELECT pg_reload_conf()' >/dev/null
# OpenBao restarts sealed with file storage. Operator script unseals using protected material.
scripts/bootstrap-openbao.sh
scripts/dc.sh restart api api2 worker otel-collector prometheus grafana loki tempo
+84
View File
@@ -0,0 +1,84 @@
#!/usr/bin/env python3
"""Operator hooks for unmodified public resilience tests. Never remove volumes/data."""
import json,os,ssl,subprocess,sys,time,urllib.request
from pathlib import Path
ROOT=Path(__file__).resolve().parent.parent
os.chdir(ROOT)
DC=[str(ROOT/'scripts/dc.sh')]
DOCKER=[str(ROOT/'scripts/docker.sh')]
DATA={'db':'/var/lib/postgresql/data','cache':'/data','minio':'/data','openbao':'/bao/data','grafana':'/var/lib/grafana','prometheus':'/prometheus','loki':'/loki','tempo':'/var/tempo'}
def command(argv,timeout=80):
result=subprocess.run(argv,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=timeout)
log=ROOT/'secrets/operator/resilience-hook.log';log.parent.mkdir(parents=True,exist_ok=True)
fd=os.open(log,os.O_WRONLY|os.O_CREAT|os.O_APPEND,0o600)
with os.fdopen(fd,'w') as stream:stream.write(result.stdout+result.stderr)
if result.returncode:raise RuntimeError('Operator command failed; inspect private resilience-hook.log')
return result.stdout
def snapshot():
ids=command(DC+['ps','--all','--quiet']).split()
if not ids:return {}
result={}
for c in json.loads(command(DOCKER+['inspect',*ids])):
service=c['Config']['Labels']['com.docker.compose.service']
instance=next((v.partition('=')[2] for v in c['Config'].get('Env',[]) if v.startswith('INSTANCE_ID=')),c['Config']['Hostname'])
result[service]={'id':c['Id'],'instance_id':instance,'running':c['State']['Running'],'started_at':c['State']['StartedAt'],
'data_mounts':[{'source':m['Source'],'destination':m['Destination'],'rw':m['RW']} for m in c.get('Mounts',[]) if m['Destination']==DATA.get(service)]}
return result
def wait_ready(timeout=60):
values={}
envfile=ROOT/'.env'
if envfile.exists():values=dict(x.split('=',1) for x in envfile.read_text().splitlines() if '=' in x and not x.startswith('#'))
url=os.environ.get('BASE_URL','https://localhost:'+values.get('HTTPS_PORT','8443'))+'/health/ready'
ctx=ssl.create_default_context(cafile=str(ROOT/'certs/ca.crt'))
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
end=time.monotonic()+timeout
while time.monotonic()<end:
try:
with opener.open(url,timeout=2) as r:
if r.status==200:return
except OSError:pass
time.sleep(.25)
raise RuntimeError('Verified HTTPS readiness did not recover before timeout')
def main():
mode=sys.argv[1]
assert mode in ('persistence','failover')
started=time.monotonic();before=snapshot()
evidence={'status':'RUNNING','mode':mode,'before':before,'volumes_removed':False}
out=ROOT/os.environ.get('HOOK_EVIDENCE_FILE','evidence/resilience-'+mode+'-hook.json')
assert out.resolve().is_relative_to((ROOT/'evidence').resolve())
try:
if mode=='persistence':
assert all(before.get(s,{}).get('running') for s in ('api','api2','worker','db','cache','minio','openbao','lb')),'Start the full stack before the persistence hook'
# Full process replacement includes DB, sessions, broker and S3.
command(DC+['down'],timeout=30)
command([str(ROOT/'scripts/bootstrap-openbao.sh')],timeout=45)
command(DC+['up','-d','--no-build','--wait','--wait-timeout','50'],timeout=55)
wait_ready(10)
after=snapshot()
for service in ('api','api2','worker','db','cache','minio','openbao','lb'):
assert after[service]['running'] and after[service]['id']!=before[service]['id'],service
for service in DATA:
mounts=before[service]['data_mounts']
assert len(mounts)==1 and mounts==after[service]['data_mounts'],service
evidence['recreated_services']=sorted(s for s in before if s in after and before[s]['id']!=after[s]['id'])
else:
target=os.environ.get('TARGET_INSTANCE_ID','')
candidates=[s for s in ('api','api2') if before.get(s,{}).get('running') and before[s]['instance_id']==target]
assert target and len(candidates)==1,'TARGET_INSTANCE_ID must identify exactly one API process'
service=candidates[0]
command(DC+['stop','--timeout','5',service],timeout=8)
after=snapshot()
assert not after[service]['running'],'Target API is still running'
other='api2' if service=='api' else 'api'
assert after[other]['running'],'Surviving replica is not running'
for untouched in ('db','cache','minio','openbao','lb','api-tls','api2-tls',other):
assert before[untouched]['id']==after[untouched]['id'] and before[untouched]['started_at']==after[untouched]['started_at'],untouched
evidence['stopped_service']=service
evidence.update(status='PASS',after=after,elapsed_seconds=round(time.monotonic()-started,3))
except Exception as e:
evidence.update(status='FAIL',error=str(e),elapsed_seconds=round(time.monotonic()-started,3));raise
finally:out.write_text(json.dumps(evidence,indent=2)+'\n')
if __name__=='__main__':main()
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
exec python3 scripts/resilience_hooks.py persistence
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
identity="${1:?Usage: revoke-cert.sh identity}"
[[ "$identity" =~ ^[a-z-]+$ ]] || exit 2
exec 9> secrets/operator/pki.lock
flock 9
exec 8> secrets/operator/ca/ca.lock
flock 8
# A stale leaf must never be imported into a different issuer's CRL database.
openssl verify -no_check_time -no-CApath -no-CAstore -CAfile secrets/operator/ca/issuer.crt "certs/$identity/$identity.crt" >/dev/null
openssl ca -config secrets/operator/ca/openssl.cnf -revoke "certs/$identity/$identity.crt"
openssl ca -config secrets/operator/ca/openssl.cnf -gencrl -out secrets/operator/ca/active.crl
python3 scripts/pki_state.py publish
scripts/dc.sh exec -T db psql -U postgres -d messenger -c 'SELECT pg_reload_conf()' >/dev/null
# New handshakes must use the new CRL. Existing TCP sessions close on restart.
scripts/dc.sh restart lb api-tls api2-tls otel-collector-tls tempo-tls loki-tls prometheus-tls grafana-tls
scripts/dc.sh restart api api2 worker otel-collector tempo loki prometheus grafana
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
role="${1:?Usage: rotate-service-secret.sh api|worker}"
[[ "$role" == api || "$role" == worker ]] || exit 2
python3 - "$role" <<'PY'
import secrets,sys
from pathlib import Path
for name in ['redis-'+sys.argv[1],'s3-'+sys.argv[1]]:
p=Path('secrets/operator')/name
p.write_text(secrets.token_hex(24));p.chmod(0o600)
PY
scripts/bootstrap-openbao.sh
scripts/dc.sh restart cache
if [[ "$role" == api ]]; then scripts/dc.sh restart api api2; else scripts/dc.sh restart worker; fi
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
image="${1:-lab7-api:local}"
docker_bin="${DOCKER_BIN:-docker}"
mkdir -p build/security-scan/cache build/security-scan/reports
# Export only an image, never mount the Docker socket or any secret directory.
"$docker_bin" save -o build/security-scan/image.tar "$image"
"$docker_bin" run --rm --user "$(id -u):$(id -g)" --read-only --cap-drop ALL \
--security-opt no-new-privileges:true --memory 2g --cpus 2 --tmpfs /tmp:rw,nosuid,size=1g \
-v "$PWD/build/security-scan/image.tar:/image.tar:ro" \
-v "$PWD/build/security-scan/cache:/cache" \
-v "$PWD/build/security-scan/reports:/reports" aquasec/trivy:0.60.0 \
image --input /image.tar --cache-dir /cache --scanners vuln --format json \
--output /reports/image-scan.json --timeout 5m
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
exec python3 scripts/resilience_hooks.py failover
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
import json,ssl,subprocess,urllib.request
from pathlib import Path
root=Path(__file__).resolve().parent.parent
init=json.loads((root/'secrets/operator/bao-init.json').read_text())
ctx=ssl.create_default_context(cafile=str(root/'certs/ca.crt'))
def write(path,body,token=None):
headers={'Content-Type':'application/json'}
if token:headers['X-Vault-Token']=token
request=urllib.request.Request('https://localhost:8200/v1/'+path,data=json.dumps(body).encode(),headers=headers)
with urllib.request.urlopen(request,context=ctx,timeout=10) as response:response.read()
try:
write('sys/seal',{},init['root_token'])
p=subprocess.run([str(root/'scripts/dc.sh'),'run','--rm','-T','--no-deps','--entrypoint','/app/worker','worker'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20)
assert p.returncode==1,'Worker must fail closed when OpenBao is sealed'
finally:write('sys/unseal',{'key':init['unseal_keys_b64'][0]})
print('PASS: fresh Worker refuses startup with sealed OpenBao; operator unseal restores access')
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
temp=$(mktemp -d)
trap 'rm -rf "$temp"' EXIT
export PKI_DIR="$temp/certs" CA_DIR="$temp/ca"
scripts/bootstrap-pki.sh >/dev/null
cp "$PKI_DIR/client-api/client-api.crt" "$temp/old-client.crt"
cp "$PKI_DIR/ca.crt" "$temp/old-root.crt"
scripts/ca-rollover.sh prepare --offline
# During overlap both old production leaves and candidate-root canaries verify.
openssl verify -CAfile "$PKI_DIR/ca.crt" -CRLfile "$PKI_DIR/ca.crl" -crl_check "$temp/old-client.crt" >/dev/null
scripts/ca-rollover.sh reissue --offline
openssl verify -CAfile "$PKI_DIR/ca.crt" -CRLfile "$PKI_DIR/ca.crl" -crl_check "$temp/old-client.crt" >/dev/null
openssl verify -CAfile "$PKI_DIR/ca.crt" -CRLfile "$PKI_DIR/ca.crl" -crl_check "$PKI_DIR/client-api/client-api.crt" >/dev/null
scripts/ca-rollover.sh retire --offline
if openssl verify -CAfile "$PKI_DIR/ca.crt" "$temp/old-client.crt" >"$temp/error" 2>&1; then echo 'FAIL: retired root still trusted'; exit 1; fi
grep -Eq 'unable to get local issuer certificate|unable to verify' "$temp/error"
for cert in "$PKI_DIR"/*/*.crt; do
[[ "$cert" == "$PKI_DIR/trust/"* ]] && continue
openssl verify -CAfile "$PKI_DIR/ca.crt" -CRLfile "$PKI_DIR/ca.crl" -crl_check "$cert" >/dev/null
done
python3 - <<'PY'
import json,os,subprocess
from pathlib import Path
ca=Path(os.environ['CA_DIR']);pki=Path(os.environ['PKI_DIR']);s=json.loads((ca/'rollover.json').read_text())
assert s['phase']=='retired' and s['old']!=s['new']
assert (pki/'ca.crt').read_text().count('BEGIN CERTIFICATE')==1
assert (ca/'active').resolve().name==s['new']
assert (ca/'generations'/s['old']/'ca.key').stat().st_mode & 0o077 == 0
old = ca/'generations'/s['old']
serial = subprocess.check_output(['openssl','x509','-in',old/'issuer.crt','-noout','-serial'],text=True).strip().split('=')[1]
rows = [row.split('\t') for row in (old/'index.txt').read_text().splitlines()]
assert any(row[0]=='R' and int(row[3],16)==int(serial,16) for row in rows), 'Old root serial was not revoked'
print('PASS: isolated dual trust, cross-issuer leaf reissue, current CRL, old anchor removal, protected CA generations')
PY
# Existing renewal/revocation remains usable after a completed rollover.
scripts/bootstrap-pki.sh client-api >/dev/null
openssl verify -CAfile "$PKI_DIR/ca.crt" -CRLfile "$PKI_DIR/ca.crl" -crl_check "$PKI_DIR/client-api/client-api.crt" >/dev/null
+108
View File
@@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""Live root rollover: TLS overlap, data/session retention, latency/resource samples."""
import argparse,hashlib,json,math,os,ssl,subprocess,sys,threading,time,urllib.error,urllib.request
from pathlib import Path
ROOT=Path(__file__).resolve().parent.parent
sys.path.insert(0,str(ROOT/'tests'))
from client import Client,check
sys.path.insert(0,str(ROOT/'scripts'))
import pki_state as pki
def percentile(values,p):
if not values:return None
return round(sorted(values)[max(0,math.ceil(len(values)*p)-1)],3)
def memory_bytes(text):
import re
match=re.fullmatch(r'([0-9.]+)\s*([A-Za-z]+)',text.strip())
if not match:raise ValueError('Unavailable memory sample')
value,unit=match.groups()
factor={'B':1,'kB':1000,'KB':1000,'MB':1000**2,'GB':1000**3,'KiB':1024,'MiB':1024**2,'GiB':1024**3}[unit]
return float(value)*factor
def main():
parser=argparse.ArgumentParser();parser.add_argument('--base-url',default=os.environ.get('BASE_URL','https://localhost:8443'));args=parser.parse_args()
os.environ['BASE_URL']=args.base_url
before=pki.fingerprint(ROOT/'certs/ca.crt')
client=Client(args.base_url,str(ROOT/'certs/ca.crt'))
alice,bob,eve,chat=client.bootstrap()
original=client.message(alice,chat,'CA rollover confirmed data')['json']
attachment,content=client.attachment(alice,chat);client.wait_ready(alice,attachment)
checks=[]
def retained(phase):
# Explicitly reload the distributed trust bundle; keep the same bearer tokens.
c=Client(args.base_url,str(ROOT/'certs/ca.crt'))
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
history=c.call('GET','/api/v1/chats/'+chat['id']+'/messages?limit=100',actor=bob,schema='MessagePage')['json']['items']
check(any(m==original for m in history),'Confirmed message changed during rollover')
data=c.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=bob)['bytes']
check(data==content,'Attachment changed during rollover')
checks.append({'phase':phase,'existing_session':'PASS','message':'PASS','attachment_sha256':hashlib.sha256(data).hexdigest(),'trusted_roots':(ROOT/'certs/ca.crt').read_text().count('BEGIN CERTIFICATE')})
retained('before')
stopping=threading.Event();samples=[];resources={};resource_failures=[];started=time.monotonic()
def load():
while not stopping.is_set():
now=time.monotonic();status='200'
try:
ctx=ssl.create_default_context(cafile=str(ROOT/'certs/ca.crt'))
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
with opener.open(args.base_url+'/health/ready',timeout=2) as r:assert r.status==200
except urllib.error.HTTPError as e:status=str(e.code)
except (OSError,ValueError) as e:
cause=e.reason if isinstance(e,urllib.error.URLError) else e
status=type(cause).__name__
samples.append({'seconds':round(time.monotonic()-started,3),'latency_ms':round((time.monotonic()-now)*1000,3),'status':status})
stopping.wait(.25)
def stats():
while not stopping.is_set():
try:
r=subprocess.run([str(ROOT/'scripts/docker.sh'),'stats','--no-stream','--format','{{json .}}'],text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=8)
for line in r.stdout.splitlines():
row=json.loads(line);name=row['Name']
if not name.startswith('lab7-') or not name.endswith('-1'):continue
cpu=float(row['CPUPerc'].rstrip('%'));memory=memory_bytes(row['MemUsage'].split('/')[0])
entry=resources.setdefault(name,{'max_sampled_cpu_percent':0.,'max_sampled_memory_bytes':0.,'samples':0})
entry['max_sampled_cpu_percent']=max(entry['max_sampled_cpu_percent'],cpu)
entry['max_sampled_memory_bytes']=max(entry['max_sampled_memory_bytes'],memory);entry['samples']+=1
except (OSError,ValueError,KeyError,subprocess.TimeoutExpired):resource_failures.append(time.monotonic()-started)
stopping.wait(3)
threads=[threading.Thread(target=load),threading.Thread(target=stats)]
for thread in threads:thread.start()
result={'status':'RUNNING','old_root':before,'profile':'one sequential HTTPS readiness client, 250ms pause, 2s request timeout; nearest-rank percentiles','warmup':'fixture creation before sampling','hardware':{'logical_cpus':os.cpu_count(),'mem_total':next((s.strip() for s in Path('/proc/meminfo').read_text().splitlines() if s.startswith('MemTotal:')),None)},'data_checks':checks}
try:
for phase in ('prepare','reissue','retire'):
print('Running CA phase: '+phase,flush=True)
log=ROOT/'secrets/operator'/('ca-'+phase+'.log')
fd=os.open(log,os.O_WRONLY|os.O_CREAT|os.O_TRUNC,0o600)
with os.fdopen(fd,'wb') as f:
r=subprocess.run([str(ROOT/'scripts/ca-rollover.sh'),phase],cwd=ROOT,stdout=f,stderr=f,timeout=240)
check(r.returncode==0,'CA '+phase+' failed; inspect private operator log')
retained(phase)
if phase=='reissue':
old=pki.authority(pki.state()['old'])/'issuer.crt'
try:
urllib.request.urlopen(args.base_url+'/health/ready',context=ssl.create_default_context(cafile=str(old)),timeout=3)
raise AssertionError('Old-root-only client still trusts the new server')
except urllib.error.URLError as e:
check(isinstance(e.reason,ssl.SSLCertVerificationError),'Old-only client failed for a non-certificate reason')
result['old_root_only_client']='rejected with certificate verification error'
result['new_root']=pki.fingerprint(ROOT/'certs/ca.crt')
check(result['old_root']!=result['new_root'],'Root fingerprint did not change')
stopping.wait(2)
stopping.set()
for thread in threads:
thread.join()
check(resources,'No resource samples collected')
check(any(s['status']=='200' for s in samples),'No successful HTTPS readiness samples')
check(not any(s['status']=='SSLCertVerificationError' for s in samples),'Unexpected certificate verification error under dual trust')
result['status']='PASS'
finally:
stopping.set()
for thread in threads:thread.join(timeout=10)
elapsed=time.monotonic()-started;good=[s['latency_ms'] for s in samples if s['status']=='200'];all_times=[s['latency_ms'] for s in samples]
result.update(elapsed_seconds=round(elapsed,3),requests=len(samples),successes=len(good),errors=len(samples)-len(good),successful_rps=round(len(good)/elapsed,3),latency_ms={'all':{f'p{int(p*100)}':percentile(all_times,p) for p in (.5,.95,.99)},'successful':{f'p{int(p*100)}':percentile(good,p) for p in (.5,.95,.99)}},resource_samples=resources,resource_sampler_failures=len(resource_failures),raw_requests=samples)
if result['status']=='RUNNING':result['status']='FAIL'
(ROOT/'evidence/ca-rollover-load.json').write_text(json.dumps(result,indent=2,ensure_ascii=False)+'\n')
print('PASS: three CA phases, old-root rejection, same session/message/attachment preserved; metrics saved',flush=True)
if __name__=='__main__':main()
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
exec python3 scripts/test-ca-rollover.py "$@"
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
# Allowed API cert; a valid empty OTLP envelope succeeds.
scripts/dc.sh run --rm -T --no-deps --entrypoint curl api \
-fsS --cacert /pki/ca.crt --cert /identity/api.crt --key /identity/api.key \
-H 'Content-Type: application/json' -d '{}' https://otel-collector:4318/v1/traces >/dev/null
set +e
scripts/dc.sh run --rm -T --no-deps -v "$PWD/certs/client-api:/wrong:ro" --entrypoint curl api \
-fsS --connect-timeout 3 --max-time 10 --cacert /pki/ca.crt --cert /wrong/client-api.crt --key /wrong/client-api.key \
-H 'Content-Type: application/json' -d '{}' https://otel-collector:4318/v1/traces >/dev/null 2>&1
rc=$?
set -e
case "$rc" in 35|52|55|56) echo 'PASS: Collector accepts api SAN and rejects client-api SAN' ;; *) echo "FAIL: unexpected result $rc"; exit 1 ;; esac
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""Operator test: rotates worker secrets; never prints old or new values."""
import json,ssl,subprocess,urllib.request,urllib.error,shlex
from pathlib import Path
root=Path(__file__).resolve().parent.parent
op=root/'secrets/operator'
old_redis=(op/'redis-worker').read_text().strip()
old_s3=(op/'s3-worker').read_text().strip()
role=(root/'secrets/approle/worker/role-id').read_text()
old_sid=(root/'secrets/approle/worker/secret-id').read_text()
dc=[str(root/'scripts/dc.sh')]
subprocess.run([str(root/'scripts/rotate-service-secret.sh'),'worker'],cwd=root,check=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=120)
ctx=ssl.create_default_context(cafile=str(root/'certs/ca.crt'))
r=urllib.request.Request('https://localhost:8200/v1/auth/approle/login',data=json.dumps({'role_id':role,'secret_id':old_sid}).encode(),headers={'Content-Type':'application/json'})
try:
urllib.request.urlopen(r,context=ctx,timeout=10)
raise AssertionError('old SecretID still accepted')
except urllib.error.HTTPError as e:assert e.code in (400,403)
script=f'valkey-cli --tls --cacert /pki/ca.crt --cert /identity/redis.crt --key /identity/redis.key --sni redis -h redis --user worker --pass {shlex.quote(old_redis)} PING\n'
p=subprocess.run(dc+['run','--rm','-T','--no-deps','--entrypoint','/bin/sh','cache','-s'],cwd=root,input=script,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20)
assert 'WRONGPASS' in p.stdout+p.stderr,'old Redis password did not fail authentication'
script=f'mc alias set old https://minio:9000 messenger-worker {shlex.quote(old_s3)} >/dev/null && mc ls old/attachments/staging\n'
p=subprocess.run(dc+['run','--rm','-T','mc','-s'],cwd=root,input=script,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20)
assert p.returncode!=0 and any(x in (p.stdout+p.stderr).lower() for x in ['signature','access denied','access key']),'old S3 secret did not fail authentication'
p=subprocess.run(dc+['run','--rm','-T','--no-deps','--entrypoint','/app/dependency_security_test','worker'],cwd=root,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=30)
assert p.returncode==0,'fresh worker credentials failed validation'
print('PASS: worker SecretID, Redis password and S3 secret rotated; old credentials denied; fresh worker credentials succeed')
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
"""Inspect delivered flags and real PID 1 kernel state without target shell/tools."""
import json,os,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parent.parent
DOCKER=[str(ROOT/'scripts/docker.sh')]
def run(*args):return subprocess.check_output(DOCKER+list(args),text=True,stderr=subprocess.PIPE)
ids=run('ps','--quiet','--filter','label=com.docker.compose.project=lab7','--filter','label=com.docker.compose.oneoff=False').split()
assert ids,'No running lab7 services'
containers=json.loads(run('inspect',*ids));result=[]
for c in containers:
service=c['Config']['Labels']['com.docker.compose.service'];h=c['HostConfig'];user=c['Config']['User']
assert user.split(':')[0] not in ('','0','root'),service
assert h['ReadonlyRootfs'] and 'ALL' in h['CapDrop'] and h['Memory']>0,service
assert any(x in ('no-new-privileges','no-new-privileges:true') for x in h['SecurityOpt']),service
assert h['NetworkMode']!='host' and not h['Privileged'],service
assert not any(m['Destination']=='/var/run/docker.sock' for m in c['Mounts']),service
bindings={k:v for k,v in (h.get('PortBindings') or {}).items() if v}
if bindings:
assert service in ('lb','grafana-tls','openbao'),service
if service!='lb':assert all(x['HostIp']=='127.0.0.1' for v in bindings.values() for x in v),service
# A trusted helper shares only the target PID namespace, no network or mounts.
# PID 1 remains the target service; inspect its kernel status, not the helper's.
status=run('run','--rm','--network','none','--pid','container:'+c['Id'],'--user',user,'--read-only','--cap-drop','ALL','--security-opt','no-new-privileges:true','--entrypoint','/bin/cat','lab7-api:local','/proc/1/status')
fields=dict(line.split(':',1) for line in status.splitlines() if ':' in line)
assert fields['NoNewPrivs'].strip()=='1',service
assert int(fields['CapEff'].strip(),16)==0,service
assert int(fields['Uid'].split()[0])!=0,service
result.append({'service':service,'container_id':c['Id'],'user':user,'read_only':True,'cap_drop':['ALL'],'no_new_privs':1,'effective_capabilities':0,'seccomp':fields['Seccomp'].strip(),'apparmor':c.get('AppArmorProfile'),'memory_limit_bytes':h['Memory'],'nano_cpus':h['NanoCpus'],'published_ports':bindings})
expected={'api','api2','worker','api-tls','api2-tls','db','cache','minio','openbao','lb','otel-collector','otel-collector-tls','loki','loki-tls','tempo','tempo-tls','prometheus','prometheus-tls','grafana','grafana-tls'}
assert {x['service'] for x in result}==expected,'The complete stack must be running'
server=json.loads(run('version','--format','{{json .Server}}'))
output={'status':'PASS','docker_version':server['Version'],'docker_root_dir':run('info','--format','{{.DockerRootDir}}').strip(),'context':'main compose.yaml, no diagnostic override','services':result}
(ROOT/'evidence/hardening-native.json').write_text(json.dumps(output,indent=2)+'\n')
print('PASS: all 20 real service PID 1 processes are non-root, NoNewPrivs=1, CapEff=0; read_only/resources/ports verified')
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
mode="${1:?no-cert or wrong-identity}"
args=()
if [[ "$mode" == wrong-identity ]]; then args=(--cert /identity/worker.crt --key /identity/worker.key); fi
for target in api-tls api2-tls; do
# Positive control proves each listener/application and permitted LB identity.
scripts/dc.sh run --rm -T --no-deps -v "$PWD/certs/client-api:/test-client:ro" --entrypoint curl api \
--silent --show-error --fail --connect-timeout 3 --max-time 10 --cacert /pki/ca.crt \
--cert /test-client/client-api.crt --key /test-client/client-api.key \
--connect-to "api:8443:$target:8443" https://api:8443/health/ready >/dev/null
set +e
scripts/dc.sh run --rm -T --no-deps --entrypoint curl worker \
--silent --show-error --fail --connect-timeout 3 --max-time 10 --cacert /pki/ca.crt \
"${args[@]}" --connect-to "api:8443:$target:8443" https://api:8443/health/ready >/dev/null 2>&1
rc=$?
set -e
case "$rc" in 35|52|55|56) echo "PASS: $target rejects $mode (curl $rc)" ;; *) echo "FAIL: unexpected result $rc"; exit 1 ;; esac
done
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
work=secrets/operator/foreign-test
mkdir -p "$work"
trap 'rm -rf "$work"' EXIT
openssl req -new -x509 -newkey rsa:2048 -nodes -days 1 -subj /CN=client-api \
-addext subjectAltName=DNS:client-api -addext extendedKeyUsage=clientAuth \
-keyout "$work/client.key" -out "$work/client.crt" >/dev/null 2>&1
for target in api-tls api2-tls; do
set +e
scripts/dc.sh run --rm -T --no-deps -v "$PWD/$work:/foreign:ro" --entrypoint curl api \
-fsS --connect-timeout 3 --max-time 10 --cacert /pki/ca.crt --cert /foreign/client.crt --key /foreign/client.key \
--connect-to "api:8443:$target:8443" https://api:8443/health/ready >/dev/null 2>&1
rc=$?
set -e
case "$rc" in 35|52|55|56) echo "PASS: $target rejects untrusted client CA with otherwise correct SAN" ;; *) echo "FAIL: unexpected result $rc"; exit 1 ;; esac
done
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
set -euo pipefail
exec "$(dirname "$0")/test-mtls-common.sh" no-cert
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
set -euo pipefail
exec "$(dirname "$0")/test-mtls-common.sh" wrong-identity
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
import json,ssl,urllib.request,urllib.error
from pathlib import Path
root=Path(__file__).resolve().parent.parent
ctx=ssl.create_default_context(cafile=str(root/'certs/ca.crt'))
def call(path,body=None,token=None,expected=200):
h={'Content-Type':'application/json'}
if token:h['X-Vault-Token']=token
r=urllib.request.Request('https://localhost:8200/v1/'+path,headers=h,data=None if body is None else json.dumps(body).encode())
try:
with urllib.request.urlopen(r,context=ctx,timeout=10) as response:
assert response.status==expected,(path,response.status)
raw=response.read();return json.loads(raw) if raw else {}
except urllib.error.HTTPError as e:
assert e.code==expected,(path,e.code)
for role,other in [('api','worker'),('worker','api')]:
creds=root/'secrets/approle'/role
token=call('auth/approle/login',{'role_id':(creds/'role-id').read_text(),'secret_id':(creds/'secret-id').read_text()})['auth']['client_token']
try:
call('secret/data/'+role,token=token)
call('database/creds/'+role+'-role',token=token)
call('secret/data/'+other,token=token,expected=403)
call('database/creds/'+other+'-role',token=token,expected=403)
call('sys/policies/acl/root',token=token,expected=403)
call('sys/policies/acl/'+role,{'policy':''},token,403)
finally:call('auth/token/revoke-self',{},token,204)
print('PASS: both AppRoles read own KV/DB path; cross-role and policy read/write denied; test tokens revoked')
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
# Destructive only to the current LB leaf: rotates it, then verifies old/expired cert denial.
set -euo pipefail
cd "$(dirname "$0")/.."
old=secrets/operator/lifecycle
mkdir -p "$old"
chmod 700 "$old"
cp certs/client-api/client-api.crt "$old/old.crt"
cp certs/client-api/client-api.key "$old/old.key"
python3 - <<'PY' &
import json,time,ssl,urllib.request,urllib.error
from pathlib import Path
ctx=ssl.create_default_context(cafile='certs/ca.crt')
counts={'ok':0,'errors':0,'first_failure_seconds':None,'recovered_seconds':None}
start=time.monotonic()
for _ in range(80):
try:
with urllib.request.urlopen('https://localhost:8443/health/ready',context=ctx,timeout=2) as r:
assert r.status==200
counts['ok']+=1
if counts['first_failure_seconds'] is not None and counts['recovered_seconds'] is None:counts['recovered_seconds']=round(time.monotonic()-start,3)
except (OSError,urllib.error.URLError,AssertionError):
counts['errors']+=1
if counts['first_failure_seconds'] is None:counts['first_failure_seconds']=round(time.monotonic()-start,3)
time.sleep(.25)
counts['elapsed_seconds']=round(time.monotonic()-start,3)
Path('evidence/pki-load.json').write_text(json.dumps(counts,indent=2)+'\n')
PY
load_pid=$!
scripts/bootstrap-pki.sh client-api
scripts/dc.sh restart api-tls api2-tls
scripts/dc.sh restart api api2
scripts/dc.sh restart lb
# Wait for fresh TLS listeners; this also checks the new LB client leaf succeeds.
for i in {1..30}; do
if curl --silent --fail --cacert certs/ca.crt https://localhost:8443/health/ready >/dev/null; then break; fi
sleep 1
done
curl --silent --show-error --fail --cacert certs/ca.crt https://localhost:8443/health/ready >/dev/null
reject() {
set +e
scripts/dc.sh run --rm -T --no-deps -v "$PWD/$old:/old-client:ro" --entrypoint curl api \
--silent --show-error --fail --connect-timeout 3 --max-time 10 --cacert /pki/ca.crt \
--cert "/old-client/$1.crt" --key "/old-client/$1.key" \
--resolve api:8443:127.0.0.1 https://api:8443/health/ready >/dev/null 2>&1
rc=$?
set -e
case "$rc" in 35|52|55|56) ;; *) echo "FAIL: expected TLS rejection for $1; got $rc"; exit 1 ;; esac
}
reject old
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out "$old/expired.key" 2>/dev/null
openssl req -new -key "$old/expired.key" -out "$old/expired.csr" -subj /CN=expired-client-api
cat > "$old/ext.cnf" <<'EOF'
basicConstraints=critical,CA:false
keyUsage=critical,digitalSignature
extendedKeyUsage=clientAuth
subjectAltName=DNS:client-api
EOF
flock secrets/operator/ca/ca.lock openssl ca -batch -notext -config secrets/operator/ca/openssl.cnf -extfile "$old/ext.cnf" \
-startdate 200101000000Z -enddate 210101000000Z -in "$old/expired.csr" -out "$old/expired.crt" >/dev/null 2>&1
reject expired
wait "$load_pid"
echo 'PASS: renewed leaf succeeds; old leaf revoked; expired leaf rejected; load results: evidence/pki-load.json'
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
temp=$(mktemp -d)
trap 'rm -rf "$temp"' EXIT
export PKI_DIR="$temp/certs" CA_DIR="$temp/ca"
scripts/bootstrap-pki.sh >/dev/null
openssl verify -CAfile "$PKI_DIR/ca.crt" -verify_hostname api "$PKI_DIR/api/api.crt"
if openssl verify -CAfile "$PKI_DIR/ca.crt" -verify_hostname worker "$PKI_DIR/api/api.crt" >/dev/null 2>&1; then echo 'FAIL hostname accepted'; exit 1; fi
cp "$PKI_DIR/client-api/client-api.crt" "$temp/old.crt"
scripts/bootstrap-pki.sh client-api >/dev/null
openssl verify -CAfile "$PKI_DIR/ca.crt" -CRLfile "$PKI_DIR/ca.crl" -crl_check "$PKI_DIR/client-api/client-api.crt"
if openssl verify -CAfile "$PKI_DIR/ca.crt" -CRLfile "$PKI_DIR/ca.crl" -crl_check "$temp/old.crt" >"$temp/revoked.out" 2>&1; then echo 'FAIL revoked cert accepted'; exit 1; fi
grep -q 'certificate revoked' "$temp/revoked.out"
echo 'PASS: SAN verification; leaf renewal; previous leaf revoked by CRL'
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
# Dedicated caller IP on the private network; exercise both replicas through one ingress.
headers=$(mktemp)
trap 'rm -f "$headers"' EXIT
instances=""
for i in 1 2 3 4 5 6; do
code=$(scripts/dc.sh run --rm -T --no-deps --entrypoint curl api \
-sS --cacert /pki/ca.crt --connect-to localhost:8443:lb:443 \
-X POST -H 'Authorization: Basic bm9uZXhpc3RlbnQ6d3Jvbmc=' \
-D - -o - https://localhost:8443/api/v1/auth/sessions)
printf '%s\n' "$code" > "$headers"
instances+="$(tr -d '\r' < "$headers" | sed -n 's/^X-Instance-Id: //Ip') "
if [[ "$i" -le 5 ]]; then
[[ "$code" == *'401 Unauthorized'* ]] || { echo "FAIL: request $i expected 401"; exit 1; }
else
[[ "$code" == *'429 Too Many Requests'* ]]
tr -d '\r' < "$headers" | grep -qi '^Retry-After: 60$'
python3 - "$headers" <<'PYCODE'
import json,sys
raw=open(sys.argv[1]).read().split('\n\n',1)[1]
j=json.loads(raw)['error']
assert j['code']=='rate_limited' and j['request_id'] and j['message']
PYCODE
fi
done
[[ $(printf '%s\n' "$instances" | tr ' ' '\n' | sed '/^$/d' | sort -u | wc -l) -eq 2 ]] || { echo 'FAIL: both replicas must participate'; exit 1; }
echo 'PASS: first 5 invalid logins return 401; sixth returns 429 with Retry-After: 60'
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""Runs public tests unchanged, checks hook scope and restores stopped replicas."""
import argparse,json,os,subprocess,time
from pathlib import Path
from resilience_hooks import ROOT,DC,command,wait_ready
def main():
p=argparse.ArgumentParser();p.add_argument('--mode',choices=['persistence','failover','all'],default='all');p.add_argument('--base-url',default=os.environ.get('BASE_URL','https://localhost:8443'));args=p.parse_args()
os.environ['BASE_URL']=args.base_url
# Fail before changing the stack if the host cannot run the delivered hardening.
command([str(ROOT/'scripts/check-docker-hardening.sh')],timeout=15)
command([str(ROOT/'scripts/bootstrap-openbao.sh')],timeout=100)
up = DC+['up','-d','--no-build','--wait','--wait-timeout','90']
try:
command(up,timeout=100)
except RuntimeError:
# After unseal, previously failing workloads can still be in restart backoff.
container_ids = command(DC+['ps','--all','--quiet','api','api2','worker']).split()
if not container_ids:
raise
fmt = '{{index .Config.Labels "com.docker.compose.service"}} {{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}'
states = command([str(ROOT/'scripts/docker.sh'),'inspect','--format',fmt,*container_ids])
stale = []
for line in states.splitlines():
service, status, health = line.split()
if status in ('restarting','exited') or health=='unhealthy':
stale.append(service)
if not stale:
raise
command(DC+['up','-d','--no-build','--no-deps','--force-recreate',*stale],timeout=90)
command(up,timeout=100)
wait_ready()
modes=['persistence','failover'] if args.mode=='all' else [args.mode]
summary={'base_url':args.base_url,'hardening':'main compose, NoNewPrivs=1 probe passed','tests':[]}
try:
for index,mode in enumerate(modes):
if index:
print('Waiting 61s for a fresh shared login limiter window.',flush=True)
for _ in range(61):time.sleep(1)
hook=ROOT/'evidence'/('resilience-'+mode+'-hook.json')
previous_hook_mtime=hook.stat().st_mtime_ns if hook.exists() else None
started=time.monotonic()
result=subprocess.run(['python3',str(ROOT/'tests/resilience.py'),'--mode',mode,'--action-script',str(ROOT/'scripts'/('restart.sh' if mode=='persistence' else 'stop-one.sh')),'--base-url',args.base_url,'--ca-file',str(ROOT/'certs/ca.crt')],cwd=ROOT,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=220)
# Public tests keep bearer tokens in memory and print only aggregate results.
print(result.stdout,flush=True)
entry={'mode':mode,'status':'PASS' if result.returncode==0 else 'FAIL','elapsed_seconds':round(time.monotonic()-started,3)}
for line in result.stdout.splitlines():
if line.startswith('{'):
values=json.loads(line)
entry['public_metrics']={k:values[k] for k in ['observed_instances_before','successful_writes','failed_attempts','first_recovery_seconds'] if k in values}
if hook.exists() and hook.stat().st_mtime_ns!=previous_hook_mtime:
entry['hook']=json.loads(hook.read_text())
if entry.get('hook',{}).get('status')!='PASS':
entry['status']='FAIL'
summary['tests'].append(entry)
if result.returncode:
raise RuntimeError(f'Public {mode} test failed (exit {result.returncode})')
if entry['status']!='PASS':
raise RuntimeError(f'Missing or failed hook evidence for {mode}')
print('PASS: '+mode+' data/session check AND real process/mount scope',flush=True)
finally:
# Restore even when failover assertions fail; never remove volumes.
command(DC+['up','-d','--no-deps','--wait','--wait-timeout','60','api','api2'],timeout=70)
(ROOT/'evidence/resilience-results.json').write_text(json.dumps(summary,indent=2,ensure_ascii=False)+'\n')
if __name__=='__main__':main()
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
exec python3 scripts/test-resilience.py "$@"
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env python3
import base64,json,ssl,time,urllib.request,urllib.parse,urllib.error
from pathlib import Path
ctx=ssl.create_default_context(cafile='certs/ca.crt')
password=Path('secrets/operator/grafana-password').read_text().strip()
headers={'Authorization':'Basic '+base64.b64encode(('admin:'+password).encode()).decode()}
def get(path):
r=urllib.request.Request('https://localhost:3000'+path,headers=headers)
with urllib.request.urlopen(r,context=ctx,timeout=20) as response:return json.load(response)
for uid in ['prometheus','loki']:
for attempt in range(30):
try:
result=get('/api/datasources/uid/'+uid+'/health')
assert result.get('status')=='OK',(uid,result.get('status'))
break
except urllib.error.HTTPError as e:
if e.code not in (400,502,503) or attempt==29:raise
time.sleep(1)
up=get('/api/datasources/proxy/uid/prometheus/api/v1/query?query=up')
assert any(x['value'][1]=='1' for x in up['data']['result'])
traces=get('/api/datasources/proxy/uid/tempo/api/search?limit=1')
assert traces.get('traces'),'No traces found'
logs=get('/api/datasources/proxy/uid/loki/loki/api/v1/query_range?'+urllib.parse.urlencode({'query':'{service_name="messenger-api"}','limit':10,'start':str(time.time_ns()-120_000_000_000)}))
assert logs['data']['result'],'No API logs found'
print('PASS: Grafana mTLS datasource health; Prometheus TLS scrape up; traces and logs reach Tempo/Loki')
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
url="${BASE_URL:-https://localhost:8443}/health/ready"
curl --noproxy '*' --silent --show-error --fail --cacert certs/ca.crt "$url" >/dev/null
set +e
curl --noproxy '*' --silent --output /dev/null "$url"
rc=$?
set -e
[[ "$rc" == 60 ]] || { echo "FAIL: expected CA verification error 60, got $rc"; exit 1; }
echo 'PASS: trusted CA succeeds; untrusted CA fails verification (60)'