ЛР 7 — БВТ2303 — Брезгунова — на 5
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
"""Explicit operator init/unseal/configure. Operator material is NOT mounted in Bao/app."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import psycopg
|
||||
from psycopg import sql
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SECRETS = ROOT/'secrets'
|
||||
|
||||
|
||||
def value(name):
|
||||
return (SECRETS/name).read_text().strip()
|
||||
|
||||
|
||||
def bao(path,body=None,token=None,method=None):
|
||||
ctx = ssl.create_default_context(cafile=str(ROOT/'pki/ca.crt'))
|
||||
ctx.load_cert_chain(str(SECRETS/'tls/operator/cert.crt'),str(SECRETS/'tls/operator/key.key'))
|
||||
headers = {'Content-Type':'application/json'}
|
||||
if token:
|
||||
headers['X-Vault-Token'] = token
|
||||
request = urllib.request.Request('https://openbao:8200/v1/'+path,
|
||||
data=json.dumps(body).encode() if body is not None else None,headers=headers,method=method)
|
||||
with urllib.request.urlopen(request,context=ctx,timeout=10) as response:
|
||||
return json.load(response) if response.status!=204 else {}
|
||||
|
||||
|
||||
def root_token():
|
||||
return json.loads((SECRETS/'operator/bao-init.json').read_text())['root_token']
|
||||
|
||||
|
||||
def configure():
|
||||
folder = SECRETS/'operator'
|
||||
folder.mkdir(exist_ok=True)
|
||||
if not bao('sys/init')['initialized']:
|
||||
init = bao('sys/init',{'secret_shares':3,'secret_threshold':2})
|
||||
(folder/'bao-init.json').write_text(json.dumps(init))
|
||||
init = json.loads((folder/'bao-init.json').read_text())
|
||||
if bao('sys/seal-status')['sealed']:
|
||||
for key in init['keys'][:2]:
|
||||
bao('sys/unseal',{'key':key})
|
||||
token = init['root_token']
|
||||
mounts = bao('sys/mounts',token=token)
|
||||
if 'secret/' not in mounts:
|
||||
bao('sys/mounts/secret',{'type':'kv','options':{'version':'2'}},token)
|
||||
if 'cert/' not in bao('sys/auth',token=token):
|
||||
bao('sys/auth/cert',{'type':'cert'},token)
|
||||
if 'file/' not in bao('sys/audit',token=token):
|
||||
bao('sys/audit/file',{'type':'file','options':{'file_path':'/bao/data/audit.json'}},token)
|
||||
for role in ('api1','api2','worker','publisher','janitor'):
|
||||
policy = 'path "secret/data/'+role+'" { capabilities = ["read"] }'
|
||||
(ROOT/'infra/openbao'/('policy-'+role+'.hcl')).write_text(policy+'\n')
|
||||
bao('sys/policies/acl/'+role,{'policy':policy},token)
|
||||
bao('auth/cert/certs/'+role,{'certificate':(SECRETS/'tls'/role/'cert.crt').read_text(),
|
||||
'allowed_dns_sans':[role],'token_policies':[role],'token_ttl':30,'token_max_ttl':60,'token_no_default_policy':True},token)
|
||||
dbrole = 'api' if role.startswith('api') else role
|
||||
s3role = 'operator' if role=='janitor' else 'api' if role.startswith('api') or role=='publisher' else role
|
||||
brokerrole = 'api' if role.startswith('api') else 'operator' if role=='janitor' else role
|
||||
values = {'DATABASE_URL':'postgresql://'+dbrole+':'+value(dbrole+'_db_password')+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/pki/ca.crt',
|
||||
'CURSOR_SECRET':value('cursor_secret'), 'S3_ACCESS_KEY_ID':value(s3role+'_s3_key'),
|
||||
'S3_SECRET_ACCESS_KEY':value(s3role+'_s3_secret'),
|
||||
'BROKER_URL':'rediss://'+brokerrole+':'+value(brokerrole+'_broker_password')+'@broker:6380/0'}
|
||||
if not role.startswith('api'):
|
||||
values.pop('CURSOR_SECRET')
|
||||
if role=='publisher':
|
||||
values.pop('S3_ACCESS_KEY_ID')
|
||||
values.pop('S3_SECRET_ACCESS_KEY')
|
||||
if role=='janitor':
|
||||
values.pop('BROKER_URL')
|
||||
bao('secret/data/'+role,{'data':values},token)
|
||||
print('OpenBao initialized/unsealed with persistent storage; pinned cert roles and scoped KV paths ready.')
|
||||
|
||||
|
||||
def database():
|
||||
with psycopg.connect('host=postgres dbname=messenger user=messenger password='+value('postgres_password')+' sslmode=verify-full sslrootcert='+str(ROOT/'pki/ca.crt')) as conn:
|
||||
for path in sorted((ROOT/'migrations').glob('*.sql')):
|
||||
conn.execute(path.read_text())
|
||||
conn.execute('REVOKE CREATE ON SCHEMA public FROM PUBLIC')
|
||||
for role in ('api','worker','publisher','janitor'):
|
||||
if not conn.execute('SELECT 1 FROM pg_roles WHERE rolname=%s',(role,)).fetchone():
|
||||
conn.execute(sql.SQL('CREATE ROLE {} LOGIN').format(sql.Identifier(role)))
|
||||
conn.execute(sql.SQL('ALTER ROLE {} PASSWORD {}').format(sql.Identifier(role),sql.Literal(value(role+'_db_password'))))
|
||||
conn.execute(sql.SQL('GRANT CONNECT ON DATABASE messenger TO {}').format(sql.Identifier(role)))
|
||||
conn.execute(sql.SQL('GRANT USAGE ON SCHEMA public TO {}').format(sql.Identifier(role)))
|
||||
permissions = {
|
||||
'api':{'SELECT,INSERT,UPDATE,DELETE':['users','sessions','chats','members','messages','message_attachments','idempotency','attachments','login_limits'], 'SELECT,INSERT':['jobs','outbox','job_audit']},
|
||||
'worker':{'SELECT,UPDATE':['jobs','attachments','outbox'],'INSERT':['job_audit']},
|
||||
'publisher':{'SELECT,UPDATE':['jobs','attachments','outbox'],'INSERT':['job_audit']},
|
||||
'janitor':{'SELECT':['attachments']}}
|
||||
for role,rights in permissions.items():
|
||||
for verbs,tables in rights.items():
|
||||
for table in tables:
|
||||
conn.execute(sql.SQL('GRANT '+verbs+' ON {} TO {}').format(sql.Identifier(table),sql.Identifier(role)))
|
||||
if role!='janitor':
|
||||
conn.execute(sql.SQL('GRANT USAGE,SELECT ON SEQUENCE job_audit_id_seq TO {}').format(sql.Identifier(role)))
|
||||
print('Schema and least-privilege DB roles ready over verify-full TLS.')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
if len(sys.argv)>1 and sys.argv[1]=='unseal':
|
||||
init = json.loads((SECRETS/'operator/bao-init.json').read_text())
|
||||
for key in init['keys'][:2]:
|
||||
bao('sys/unseal',{'key':key})
|
||||
print('Operator unseal completed.')
|
||||
else:
|
||||
configure()
|
||||
database()
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Read-only Git/public contract and secret scan. Never print secret values."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
def git(*args):return subprocess.check_output(['git',*args],cwd=ROOT,text=True,encoding='utf-8').strip()
|
||||
public=git('ls-files','--','README.md','COURSE.md','CONTRIBUTING.md','tests','contracts').splitlines()
|
||||
public=[name for name in public if name!='contracts/trust-matrix.md']
|
||||
changed=[name for name in public if git('hash-object','--path',name,name)!=git('rev-parse','HEAD:'+name)]
|
||||
assert not changed,'Mandatory files changed: '+', '.join(changed)
|
||||
private=[]
|
||||
for path in (ROOT/'secrets').rglob('*'):
|
||||
if path.is_file() and path.suffix not in ('.crt',):
|
||||
raw=path.read_bytes()
|
||||
if path.suffix not in ('.json','.yaml','.pem','.key') and len(raw.strip())>=16:
|
||||
private.append(raw.strip())
|
||||
scan=[]
|
||||
for path in ROOT.rglob('*'):
|
||||
if path.is_file() and path.suffix in ('.md','.py','.json','.txt','.yaml','.yml','.hcl','.cfg','.conf','.lock') and not set(path.relative_to(ROOT).parts)&{'.git','secrets','pki','.venv','__pycache__'}:
|
||||
scan.append(path)
|
||||
marker=b'-----BEGIN PRIVATE KEY-----'
|
||||
leaks=[str(p.relative_to(ROOT)) for p in scan if any(v in p.read_bytes() for v in private) or
|
||||
p.read_bytes().startswith(marker) or b'\n'+marker+b'\n' in p.read_bytes()]
|
||||
assert not leaks,'Private material found in '+', '.join(leaks)
|
||||
result={'result':'PASS','unchanged_mandatory_files':len(public),'trust_matrix_filled_as_required':True,
|
||||
'scanned_files':len(scan),'private_value_leaks':0,'scope':'mtusi2026lab7 only',
|
||||
'secrets_ignored':bool(git('check-ignore','secrets/postgres_password','pki/ca.crt','.env'))}
|
||||
(ROOT/'evidence/integrity.json').write_text(json.dumps(result,indent=2),encoding='utf-8')
|
||||
print(json.dumps(result))
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Public load workload plus actual process/cgroup snapshots on the same stand."""
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from verify import ROOT,BASE,CA,command,compose,save
|
||||
|
||||
|
||||
def stats(role):
|
||||
tag='src.app:app' if role.startswith('api') else 'src.worker'
|
||||
code="import psutil,json; p=next(p for p in psutil.process_iter() if p.name().startswith('python') and "+repr(tag)+" in p.cmdline()); procs=[p]+p.children(recursive=True); print(json.dumps({'cpu_seconds':sum(sum(x.cpu_times()[:2]) for x in procs),'rss_bytes':sum(x.memory_info().rss for x in procs)}))"
|
||||
return json.loads(compose('exec','-T',role,'python','-c',code))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
before={r:stats(r) for r in ('api1','api2','worker')}
|
||||
started=time.monotonic()
|
||||
command([sys.executable,'-X','utf8','tests/load.py','--base-url',BASE,'--ca-file',CA,'--duration','30','--concurrency','4','--output','evidence/load.json'],'load.txt')
|
||||
elapsed=time.monotonic()-started
|
||||
after={r:stats(r) for r in before}
|
||||
ids=compose('ps','-q').split()
|
||||
containers=command(['docker','stats','--no-stream','--format','{{json .}}',*ids])
|
||||
save('load-resources.json',{'before':before,'after':after,'wall_seconds':elapsed,
|
||||
'CPU_cores':{r:(after[r]['cpu_seconds']-before[r]['cpu_seconds'])/elapsed for r in before},
|
||||
'cgroup_snapshots':[json.loads(line) for line in containers.splitlines()],
|
||||
'clock_resolution_seconds':time.get_clock_info('monotonic').resolution,
|
||||
'limitation':'Process snapshots include child workers, exclude client, DB, TLS sidecars and Collector from API CPU; container snapshots cover those separately. RSS is end snapshot, not worst-case peak.'})
|
||||
print('PASS: public HTTPS load and process/container resource snapshots')
|
||||
@@ -0,0 +1,8 @@
|
||||
from pathlib import Path
|
||||
from src.storage import db
|
||||
|
||||
with db() as conn:
|
||||
conn.execute('SELECT pg_advisory_xact_lock(440001)')
|
||||
for path in sorted(Path('migrations').glob('*.sql')):
|
||||
conn.execute(path.read_text())
|
||||
print('Schema ready (idempotent migration).')
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Operator-only local PKI. Never mount this directory into applications."""
|
||||
import datetime as dt
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PRIVATE = ROOT/'secrets'
|
||||
PUBLIC = ROOT/'pki'
|
||||
|
||||
|
||||
def key_bytes(key):
|
||||
return key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption())
|
||||
|
||||
|
||||
def authority(name):
|
||||
path = PRIVATE/'operator'/name
|
||||
path.mkdir(parents=True,exist_ok=True)
|
||||
if not (path/'key.key').exists():
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,name)])
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
cert = x509.CertificateBuilder().subject_name(subject).issuer_name(subject).public_key(key.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-dt.timedelta(minutes=1)).not_valid_after(now+dt.timedelta(days=365)).add_extension(x509.BasicConstraints(ca=True,path_length=0),True).add_extension(x509.KeyUsage(True,False,False,False,False,True,True,False,False),True).sign(key,hashes.SHA256())
|
||||
(path/'key.key').write_bytes(key_bytes(key))
|
||||
(path/'cert.crt').write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||
key=serialization.load_pem_private_key((path/'key.key').read_bytes(),None)
|
||||
cert=x509.load_pem_x509_certificate((path/'cert.crt').read_bytes())
|
||||
try:
|
||||
cert.extensions.get_extension_for_class(x509.SubjectKeyIdentifier)
|
||||
except x509.ExtensionNotFound:
|
||||
cert=x509.CertificateBuilder().subject_name(cert.subject).issuer_name(cert.issuer).public_key(key.public_key()).serial_number(cert.serial_number).not_valid_before(cert.not_valid_before_utc).not_valid_after(cert.not_valid_after_utc).add_extension(x509.BasicConstraints(ca=True,path_length=0),True).add_extension(x509.KeyUsage(True,False,False,False,False,True,True,False,False),True).add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),False).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).sign(key,hashes.SHA256())
|
||||
(path/'cert.crt').write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||
return key,cert
|
||||
|
||||
|
||||
def issue(role,hours=24,foreign=False,force=False):
|
||||
folder = PRIVATE/'tls'/role
|
||||
folder.mkdir(parents=True,exist_ok=True)
|
||||
if (folder/'cert.crt').exists() and not force:
|
||||
old=x509.load_pem_x509_certificate((folder/'cert.crt').read_bytes())
|
||||
try:
|
||||
old.extensions.get_extension_for_class(x509.AuthorityKeyIdentifier)
|
||||
return
|
||||
except x509.ExtensionNotFound:
|
||||
pass
|
||||
key,ca = authority('foreign-ca' if foreign else 'lab7-ca')
|
||||
leaf_key = ec.generate_private_key(ec.SECP256R1())
|
||||
now = dt.datetime.now(dt.timezone.utc)
|
||||
if hours<0:
|
||||
now -= dt.timedelta(days=2)
|
||||
hours = 1
|
||||
san = [x509.DNSName(role)]
|
||||
if role in ('lb','openbao','grafana'):
|
||||
san += [x509.DNSName('localhost'),x509.IPAddress(ipaddress.ip_address('127.0.0.1'))]
|
||||
leaf = x509.CertificateBuilder().subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,role)])).issuer_name(ca.subject).public_key(leaf_key.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-dt.timedelta(minutes=2)).not_valid_after(now+dt.timedelta(hours=hours)).add_extension(x509.BasicConstraints(ca=False,path_length=None),True).add_extension(x509.SubjectAlternativeName(san),False).add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH,ExtendedKeyUsageOID.CLIENT_AUTH]),False).add_extension(x509.KeyUsage(True,False,False,False,False,False,False,False,False),True).add_extension(x509.SubjectKeyIdentifier.from_public_key(leaf_key.public_key()),False).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).sign(key,hashes.SHA256())
|
||||
(folder/'cert.crt').write_bytes(leaf.public_bytes(serialization.Encoding.PEM))
|
||||
(folder/'key.key').write_bytes(key_bytes(leaf_key))
|
||||
(folder/'bundle.pem').write_bytes((folder/'cert.crt').read_bytes()+(folder/'key.key').read_bytes())
|
||||
# Native PostgreSQL rejects group/world-readable private keys on Linux.
|
||||
(folder/'key.key').chmod(0o600)
|
||||
if os.name!='nt':
|
||||
for path in folder.iterdir():
|
||||
os.chown(path,10001,10001)
|
||||
|
||||
|
||||
def main():
|
||||
PUBLIC.mkdir(exist_ok=True)
|
||||
_,ca = authority('lab7-ca')
|
||||
(PUBLIC/'ca.crt').write_bytes(ca.public_bytes(serialization.Encoding.PEM))
|
||||
if not (PUBLIC/'revoked.json').exists():
|
||||
(PUBLIC/'revoked.json').write_text('[]')
|
||||
roles = ['lb','api1','api2','worker','publisher','janitor','postgres','s3','broker','otel-collector','prometheus','loki','tempo','grafana','openbao','operator','probe','intruder']
|
||||
if len(sys.argv)>1:
|
||||
issue(sys.argv[1],force=True)
|
||||
else:
|
||||
for role in roles:
|
||||
issue(role)
|
||||
issue('foreign',foreign=True)
|
||||
issue('expired',hours=-1)
|
||||
print('Local PKI prepared; no private material displayed.')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
python scripts/restart.py
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Persistence hook: restart all actual services and explicit operator unseal."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
DC=['docker','compose','--env-file','.env']
|
||||
def call(*args):subprocess.run(DC+list(args),cwd=ROOT,check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
sidecars=['api1-tls','api2-tls','broker-tls','otel-collector-tls','prometheus-tls','loki-tls','tempo-tls','grafana-tls']
|
||||
# Stop shared-network sidecars before replacing the parent's namespace.
|
||||
call('stop',*sidecars)
|
||||
call('restart','postgres','s3','broker','openbao','otel-collector','prometheus','loki','tempo','grafana','api1','api2','publisher','worker','janitor','lb')
|
||||
for _ in range(20):
|
||||
try:
|
||||
call('run','--rm','--no-deps','operator','python','scripts/bootstrap.py','unseal')
|
||||
break
|
||||
except subprocess.CalledProcessError:time.sleep(1)
|
||||
else:raise RuntimeError('operator unseal failed')
|
||||
call('up','-d','--no-deps','--force-recreate',*sidecars)
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/restart.py
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Local-only credentials. No values printed; preserve existing secrets."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
identity=ROOT/'identity'
|
||||
identity.mkdir(exist_ok=True)
|
||||
for role in ('api1','api2'):
|
||||
path=identity/(role+'.txt')
|
||||
if not path.exists():path.write_text(secrets.token_hex(16),encoding='utf-8')
|
||||
folder = ROOT/'secrets'
|
||||
folder.mkdir(exist_ok=True)
|
||||
names = ['postgres_password','minio_root_user','minio_root_password','cursor_secret','grafana_password']
|
||||
names += [role+'_'+kind for role in ('api','worker','publisher','janitor','operator') for kind in ('db_password','s3_key','s3_secret','broker_password')]
|
||||
values = {}
|
||||
for name in names:
|
||||
path = folder/name
|
||||
if not path.exists():
|
||||
path.write_text(secrets.token_hex(24),encoding='utf-8')
|
||||
values[name] = path.read_text().strip()
|
||||
# bootstrap.sh maintains the lab5 policy names with newly generated identities.
|
||||
for old,new in {'s3_access_key_id':'api_s3_key','s3_secret_access_key':'api_s3_secret',
|
||||
'worker_access_key_id':'worker_s3_key','worker_secret_access_key':'worker_s3_secret',
|
||||
'operator_access_key_id':'operator_s3_key','operator_secret_access_key':'operator_s3_secret'}.items():
|
||||
(folder/old).write_text(values[new])
|
||||
if not (ROOT/'.env').exists():
|
||||
(ROOT/'.env').write_text('LAB7_PORT=8443\nSESSION_TTL_SECONDS=3600\n',encoding='utf-8')
|
||||
acl = ['user default off']
|
||||
for role in ('api','worker','publisher','operator'):
|
||||
password = values[role+'_broker_password']
|
||||
if role=='operator':
|
||||
rights = '~* +@all'
|
||||
elif role=='publisher':
|
||||
rights = '~attachments:v1 +ping +xadd'
|
||||
elif role=='api':
|
||||
rights = '+ping'
|
||||
else:
|
||||
rights = '+ping (~attachments:v1 +xreadgroup +xgroup +xautoclaim +xack +xdel) (~attachments:invalid +xadd)'
|
||||
acl.append('user '+role+' on >'+password+' -@all '+rights)
|
||||
(folder/'broker.acl').write_text('\n'.join(acl)+'\n')
|
||||
print('Local lab7 credentials prepared; no secrets displayed.')
|
||||
|
||||
|
||||
def grafana():
|
||||
folder = ROOT/'secrets/grafana-runtime'
|
||||
folder.mkdir(exist_ok=True)
|
||||
ca = (ROOT/'pki/ca.crt').read_text()
|
||||
cert = (ROOT/'secrets/tls/grafana/cert.crt').read_text()
|
||||
key = (ROOT/'secrets/tls/grafana/key.key').read_text()
|
||||
sources = []
|
||||
for name,port,kind in [('prometheus',9443,'prometheus'),('loki',3443,'loki'),('tempo',3443,'tempo')]:
|
||||
sources.append({'name':name.title(),'uid':name,'type':kind,'access':'proxy','url':'https://'+name+':'+str(port),
|
||||
'isDefault':name=='prometheus','jsonData':{'tlsAuth':True,'tlsAuthWithCACert':True,'tlsSkipVerify':False,'serverName':name,'timeInterval':'3s'},
|
||||
'secureJsonData':{'tlsCACert':ca,'tlsClientCert':cert,'tlsClientKey':key}})
|
||||
(folder/'sources.yaml').write_text(json.dumps({'apiVersion':1,'datasources':sources},indent=2))
|
||||
|
||||
|
||||
if (ROOT/'pki/ca.crt').exists():
|
||||
grafana()
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
python scripts/stop-one.py
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,13 @@
|
||||
"""Map public random alias locally, then hard-stop only that lab7 container."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
DC=['docker','compose','--env-file','.env']
|
||||
for role in ('api1','api2'):
|
||||
alias=(ROOT/'identity'/(role+'.txt')).read_text().strip()
|
||||
if alias==os.environ.get('TARGET_INSTANCE_ID'):
|
||||
subprocess.run(['docker','stop','--time','0','mtusi-lab7-'+role+'-1'],cwd=ROOT,check=True)
|
||||
break
|
||||
else:raise RuntimeError('unknown target alias')
|
||||
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/stop-one.py
|
||||
@@ -0,0 +1,35 @@
|
||||
"""One-host bootstrap. Only mtusi-lab7 Compose project is mutated."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def run(*args):
|
||||
subprocess.run(args,cwd=ROOT,check=True)
|
||||
|
||||
|
||||
def compose(*args):
|
||||
run('docker','compose','--env-file','.env',*args)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(sys.executable,'scripts/setup.py')
|
||||
compose('build','api1','s3','s3-bootstrap')
|
||||
compose('run','--rm','--no-deps','operator','python','scripts/pki.py')
|
||||
run(sys.executable,'scripts/setup.py')
|
||||
compose('run','--rm','volume-init')
|
||||
compose('up','-d','postgres','broker','s3','openbao')
|
||||
for attempt in range(20):
|
||||
try:
|
||||
compose('run','--rm','--no-deps','operator','python','scripts/bootstrap.py')
|
||||
compose('run','--rm','s3-bootstrap')
|
||||
break
|
||||
except subprocess.CalledProcessError:
|
||||
if attempt==19:raise
|
||||
time.sleep(2)
|
||||
compose('up','-d','--no-build')
|
||||
compose('up','-d','--no-deps','--force-recreate','api1-tls','api2-tls','broker-tls','otel-collector-tls','prometheus-tls','loki-tls','tempo-tls','grafana-tls')
|
||||
print('Lab7 deployed. Public CA: pki/ca.crt; endpoint https://localhost:8443. Wait for healthy APIs.')
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Explicit security/fault campaign scoped to mtusi-lab7. No secrets in evidence."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0,str(ROOT/'tests'))
|
||||
from client import Client,Failure,check
|
||||
BASE='https://localhost:8443'
|
||||
CA=str(ROOT/'pki/ca.crt')
|
||||
DC=['docker','compose','--env-file','.env']
|
||||
|
||||
|
||||
def command(args,name=None):
|
||||
p=subprocess.run(args,cwd=ROOT,capture_output=True,text=True,encoding='utf-8',errors='replace',timeout=300)
|
||||
if name:(ROOT/'evidence'/name).write_text(p.stdout+p.stderr,encoding='utf-8')
|
||||
check(p.returncode==0,'command failed: '+' '.join(args)+'\n'+p.stdout+p.stderr)
|
||||
return p.stdout
|
||||
|
||||
|
||||
def compose(*args):return command(DC+list(args))
|
||||
|
||||
|
||||
def operator(script,*args):return compose('run','--rm','--no-deps','operator','python',script,*args)
|
||||
|
||||
|
||||
def save(name,data):(ROOT/'evidence'/name).write_text(json.dumps(data,ensure_ascii=False,indent=2),encoding='utf-8')
|
||||
|
||||
|
||||
def wait(fn,timeout=100):
|
||||
until=time.monotonic()+timeout
|
||||
while time.monotonic()<until:
|
||||
try:
|
||||
if result:=fn():return result
|
||||
except Exception:pass
|
||||
time.sleep(1)
|
||||
raise AssertionError('deadline waiting for recovery')
|
||||
|
||||
|
||||
def snapshot():
|
||||
ids=compose('ps','-a','-q').split()
|
||||
values=json.loads(command(['docker','inspect',*ids]))
|
||||
return {x['Config']['Labels']['com.docker.compose.service']:{'id':x['Id'],'image':x['Image'],
|
||||
'started_at':x['State']['StartedAt'],'user':x['Config']['User'],'privileged':x['HostConfig']['Privileged'],
|
||||
'network_mode':x['HostConfig']['NetworkMode'],'read_only':x['HostConfig']['ReadonlyRootfs'],
|
||||
'cap_drop':x['HostConfig']['CapDrop'],'security_opt':x['HostConfig']['SecurityOpt'],
|
||||
'memory_limit':x['HostConfig']['Memory'],'cpu_limit':x['HostConfig']['NanoCpus'],
|
||||
'ports':x['HostConfig']['PortBindings'],'mount_destinations':[m['Destination'] for m in x['Mounts']]} for x in values}
|
||||
|
||||
|
||||
def main():
|
||||
c=Client(BASE,CA,timeout=10)
|
||||
wait(lambda:c.call('GET','/health/ready',schema='Health'))
|
||||
command([sys.executable,'-X','utf8','scripts/check_contract.py'],'check.txt')
|
||||
command([sys.executable,'-X','utf8','tests/smoke.py','--base-url',BASE,'--ca-file',CA],'smoke.txt')
|
||||
command([sys.executable,'-X','utf8','tests/security.py','--base-url',BASE,'--ca-file',CA],'external-tls.txt')
|
||||
print('PASS: public HTTPS smoke and external trust',flush=True)
|
||||
text=operator('student-tests/security.py');(ROOT/'evidence/security-audit.txt').write_text(text,encoding='utf-8')
|
||||
print(text,flush=True)
|
||||
a,b,e,chat=c.bootstrap()
|
||||
try:
|
||||
# Seal leaves bounded cache grace. Afterwards API must fail closed.
|
||||
started=time.monotonic()
|
||||
operator('student-tests/lifecycle.py','seal')
|
||||
time.sleep(17)
|
||||
# LB correctly removes unready APIs and can generate its own 503 without
|
||||
# API headers. Probe the actual API over the required LB mTLS identity.
|
||||
operator('student-tests/lifecycle.py','probe-sealed')
|
||||
operator('scripts/bootstrap.py','unseal')
|
||||
restored=time.monotonic()
|
||||
wait(lambda:c.call('GET','/api/v1/users/me',actor=a,schema='User'))
|
||||
save('bao-sealed.json',{'result':'PASS','sealed_failure_status':503,
|
||||
'cache_grace_bound_seconds':15,'observed_after_seconds':round(time.monotonic()-started,3),
|
||||
'recovery_seconds':round(time.monotonic()-restored,3),'fallback':'none'})
|
||||
print('PASS: sealed Bao -> bounded grace -> 503 -> operator unseal -> recovery',flush=True)
|
||||
# Simulated compromise: worker identity is revoked, accepted work stays durable.
|
||||
compose('stop','-t','1','worker')
|
||||
pending=[c.attachment(a,chat) for _ in range(3)]
|
||||
before=snapshot()
|
||||
operator('student-tests/lifecycle.py','revoke')
|
||||
compose('start','worker')
|
||||
time.sleep(3)
|
||||
metadata=[c.call('GET','/api/v1/attachments/'+att['id'],actor=a,schema='Attachment')['json'] for att,raw in pending]
|
||||
check(all(x['status']=='queued' for x in metadata),'revoked worker processed job')
|
||||
compose('stop','-t','1','worker')
|
||||
operator('student-tests/lifecycle.py','rotate')
|
||||
compose('run','--rm','s3-bootstrap')
|
||||
operator('student-tests/lifecycle.py','old-denied')
|
||||
restored=time.monotonic()
|
||||
compose('start','worker')
|
||||
for att,raw in pending:
|
||||
ready=c.wait_ready(a,att)
|
||||
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=a)['bytes']==raw,'accepted bytes lost')
|
||||
check(len(ready['variants'])==3,'incomplete result')
|
||||
after=snapshot()
|
||||
check(before['worker']['image']==after['worker']['image'],'rotation rebuilt image')
|
||||
save('worker-compromise.json',{'result':'PASS','accepted_jobs':3,'queued_while_revoked':True,
|
||||
'ready_after_rotation':3,'originals_verified':3,'variants_each':3,
|
||||
'recovery_seconds':round(time.monotonic()-restored,3),'image_unchanged':True,
|
||||
'hypothesis':'Scoped worker loses authority to unrelated secrets, user/session/message DB and producer/admin broker operations; revocation blocks new worker connections while durable jobs survive.',
|
||||
'before_worker':before['worker'],'after_worker':after['worker'],
|
||||
'limitation':'Authorized worker can still alter allowed image results and job state. Revocation is bounded by cache/active connection lifetime; host/operator compromise is outside this model.'})
|
||||
print('PASS: compromised worker revoked; leaf and three credentials rotated; 3 jobs preserved',flush=True)
|
||||
finally:
|
||||
operator('scripts/bootstrap.py','unseal')
|
||||
compose('start','api1','api2','worker')
|
||||
suffix='.cmd' if os.name=='nt' else '.sh'
|
||||
save('before-restart.json',snapshot())
|
||||
command([sys.executable,'-X','utf8','tests/resilience.py','--mode','persistence','--action-script',str(ROOT/'scripts'/('restart'+suffix)),'--base-url',BASE,'--ca-file',CA],'persistence.txt')
|
||||
save('after-restart.json',snapshot())
|
||||
print('PASS: public HTTPS persistence',flush=True)
|
||||
try:
|
||||
command([sys.executable,'-X','utf8','tests/resilience.py','--mode','failover','--action-script',str(ROOT/'scripts'/('stop-one'+suffix)),'--base-url',BASE,'--ca-file',CA],'failover.txt')
|
||||
finally:
|
||||
compose('start','api1','api2')
|
||||
compose('up','-d','--no-deps','--force-recreate','api1-tls','api2-tls')
|
||||
wait(lambda:c.call('GET','/health/ready',schema='Health'))
|
||||
command([sys.executable,'-X','utf8','tests/smoke.py','--base-url',BASE,'--ca-file',CA],'final-smoke.txt')
|
||||
save('final-containers.json',snapshot())
|
||||
save('verification.json',{'result':'PASS','HTTPS_smoke':True,'public_TLS_negative':True,'internal_mTLS':True,
|
||||
'scoped_roles':True,'ACL_sessions_rehash_rate_limit':True,'Bao_sealed_fail_closed':True,
|
||||
'secret_and_leaf_rotation':True,'worker_compromise_track':True,'persistence':True,'failover':True})
|
||||
print('PASS: lab7 security campaign complete',flush=True)
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
Reference in New Issue
Block a user