Лаб7: mTLS, Argon2id, OpenBao и исследование отзыва worker
Майорова Софья, БВТ2301, на 5. Трек1. HTTPS/TLS/ACL,18 API tests,13 pipeline groups,3 compromise runs,clean clone,persistence. Original tests/API contract preserved; residual CVE triage in REPORT/security.
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
"""Explicit operator init/unseal/configure. Root and shares only on protected host."""
|
||||
import json
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import os
|
||||
from pki import ROOT
|
||||
|
||||
URL=os.environ.get('BAO_OPERATOR_URL','https://localhost:18207')
|
||||
def call(path,data=None,token=None,method=None):
|
||||
ctx=ssl.create_default_context(cafile=str(ROOT/'operator/ca.crt'))
|
||||
ctx.load_cert_chain(str(ROOT/'pki/operator/tls.crt'),str(ROOT/'pki/operator/tls.key'))
|
||||
headers={'Content-Type':'application/json'}
|
||||
if token:headers['X-Vault-Token']=token
|
||||
req=urllib.request.Request(URL+'/v1/'+path,data=None if data is None else json.dumps(data).encode(),headers=headers,method=method)
|
||||
op=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
|
||||
with op.open(req,timeout=60 if path in ["sys/init","sys/unseal"] else 5) as r:return json.load(r) if r.status!=204 else {}
|
||||
|
||||
def unseal():
|
||||
init=ROOT/'operator/bao-init.json'
|
||||
if not call('sys/init')['initialized']:
|
||||
if init.exists():
|
||||
import shutil
|
||||
shutil.copyfile(init,ROOT/'operator/bao-init.previous.json')
|
||||
(ROOT/'operator/bao-init.previous.json').chmod(0o600)
|
||||
info=call('sys/init',{'secret_shares':3,'secret_threshold':2})
|
||||
init.write_text(json.dumps(info));init.chmod(0o600)
|
||||
data=json.loads(init.read_text())
|
||||
if call('sys/seal-status')['sealed']:
|
||||
for key in data['keys'][:2]:call('sys/unseal',{'key':key})
|
||||
return data['root_token']
|
||||
|
||||
def configure():
|
||||
root=unseal()
|
||||
mounts=call('sys/mounts',token=root)
|
||||
if 'secret/' not in mounts:call('sys/mounts/secret',{'type':'kv','options':{'version':'2'}},root)
|
||||
auth=call('sys/auth',token=root)
|
||||
if 'cert/' not in auth:call('sys/auth/cert',{'type':'cert'},root)
|
||||
audits=call('sys/audit',token=root)
|
||||
assert 'file/' in audits, 'Declarative audit device must be enabled'
|
||||
settings=json.loads((ROOT/'operator/settings.json').read_text())
|
||||
for role in ['api','worker','dispatcher']:
|
||||
policy=(ROOT/'infra/openbao/policies'/(role+'.hcl')).read_text()
|
||||
call('sys/policies/acl/'+role,{'policy':policy},root)
|
||||
# Exact leaf pinning: another valid certificate from the same CA cannot impersonate this service.
|
||||
call('auth/cert/certs/'+role,{'certificate':(ROOT/'pki'/role/'tls.crt').read_text(),'token_policies':[role],'token_ttl':'20s','token_max_ttl':'20s','token_no_default_policy':True},root)
|
||||
db='postgresql://db_'+role+':'+settings[role]+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/tls/ca.crt'
|
||||
values={'DATABASE_URL':db}
|
||||
if role=='api':
|
||||
values['CACHE_URL']='rediss://api:'+settings['cache']+'@redis:8443/0'
|
||||
else:
|
||||
values['BROKER_URL']='rediss://'+role+':'+settings['broker_'+role]+'@broker:8443/0'
|
||||
if role in ['api','worker']:
|
||||
values['S3_ACCESS_KEY_ID']=settings['s3_'+role+'_key'];values['S3_SECRET_ACCESS_KEY']=settings['s3_'+role]
|
||||
call('secret/data/'+role,{'data':values},root)
|
||||
print('OpenBao initialized/unsealed by explicit operator action; scoped service policies and 20s certificate-auth tokens configured.')
|
||||
|
||||
if __name__=='__main__':
|
||||
import sys
|
||||
if '--unseal-only' in sys.argv:
|
||||
import time
|
||||
for _ in range(60):
|
||||
try:call('sys/init');break
|
||||
except Exception:time.sleep(.3)
|
||||
unseal();print('OpenBao unsealed by operator.')
|
||||
else:configure()
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Local secrets/PKI generation, idempotent. Never prints secret values."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
from pki import ROOT,bootstrap
|
||||
|
||||
def main():
|
||||
bootstrap()
|
||||
path=ROOT/'operator/settings.json'
|
||||
if path.exists():data=json.loads(path.read_text())
|
||||
else:
|
||||
data={role:secrets.token_hex(24) for role in ['postgres','api','worker','dispatcher','cache','broker_worker','broker_dispatcher','broker_operator','grafana','s3_api','s3_worker','s3_admin']}
|
||||
data.update({role+'_key':secrets.token_hex(12) for role in ['s3_api','s3_worker','s3_admin']})
|
||||
path.write_text(json.dumps(data));path.chmod(0o600)
|
||||
sql=[]
|
||||
for role in ['api','worker','dispatcher']:
|
||||
sql.append('CREATE ROLE '+role+'_role NOLOGIN;')
|
||||
sql.append("CREATE ROLE db_"+role+" LOGIN PASSWORD '"+data[role]+"' IN ROLE "+role+"_role;")
|
||||
(ROOT/'secrets/pg-init.sql').write_text('\n'.join(sql)+'\n')
|
||||
if 'broker_operator' not in data:
|
||||
data['broker_operator']=secrets.token_hex(24)
|
||||
path.write_text(json.dumps(data,indent=2)+'\n')
|
||||
path.chmod(0o600)
|
||||
(ROOT/'secrets/postgres_password').write_text(data['postgres'])
|
||||
identities=[]
|
||||
for role in ['api','worker','admin']:
|
||||
identities.append({'name':role,'credentials':[{'accessKey':data['s3_'+role+'_key'],'secretKey':data['s3_'+role]}],
|
||||
'actions':['Admin','Read','Write','List'] if role=='admin' else ['Read:messenger-attachments','Write:messenger-attachments']})
|
||||
# Prefix and verb authorization is additionally enforced at the mTLS S3 gateway.
|
||||
(ROOT/'secrets/s3_config').write_text(json.dumps({'identities':identities}))
|
||||
(ROOT/'secrets/redis.conf').write_text('bind 127.0.0.1\nport 6379\nprotected-mode yes\nsave ""\nappendonly no\nmaxmemory 32mb\nmaxmemory-policy allkeys-lru\nuser default off\nuser api on >'+data['cache']+' ~user:* +get +setex +ping +client|setinfo\n')
|
||||
(ROOT/'secrets/broker.conf').write_text('bind 127.0.0.1\nport 6379\nprotected-mode yes\nsave ""\nappendonly yes\nappendfsync always\nmaxmemory 96mb\nmaxmemory-policy noeviction\nuser default off\nuser dispatcher on >'+data['broker_dispatcher']+' ~attachment-jobs +ping +xadd +xgroup|create +client|setinfo\nuser worker on >'+data['broker_worker']+' ~attachment-jobs ~rejected-jobs +ping +xgroup|create +xautoclaim +xreadgroup +xadd +xack +xdel +eval +client|setinfo\nuser operator on >'+data['broker_operator']+' ~* +@all\n')
|
||||
url='postgresql://messenger:'+data['postgres']+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/tls/ca.crt'
|
||||
(ROOT/'operator/database_url').write_text(url)
|
||||
(ROOT/'operator/broker_url').write_text('rediss://operator:'+data['broker_operator']+'@broker:8443/0')
|
||||
(ROOT/'secrets/migration_database_url').write_text(url)
|
||||
(ROOT/'secrets/grafana_admin').write_text(data['grafana'])
|
||||
(ROOT/'secrets/s3_admin_key').write_text(data['s3_admin_key'])
|
||||
(ROOT/'secrets/s3_admin_secret').write_text(data['s3_admin'])
|
||||
for f in (ROOT/'secrets').iterdir():f.chmod(0o644)
|
||||
old=ROOT/'operator/revoked-worker-settings.json'
|
||||
if not old.exists():old.write_text('{}')
|
||||
for f in (ROOT/'operator').iterdir():
|
||||
if f.is_file():f.chmod(0o600)
|
||||
# Native TLS client provisioning; private keys only in ignored generated configuration.
|
||||
sources=[]
|
||||
for name,url in [('Prometheus','https://prometheus:8443'),('Loki','https://loki:8443'),('Tempo','https://tempo:8443')]:
|
||||
options={'tlsAuth':True,'tlsAuthWithCACert':True,'tlsSkipVerify':False}
|
||||
if name=='Loki':
|
||||
options['derivedFields']=[{'name':'TraceID','datasourceUid':'tempo','matcherRegex':'"trace_id":"([a-f0-9]{32})"','url':'$${__value.raw}'}]
|
||||
if name=='Tempo':
|
||||
options['tracesToLogsV2']={'datasourceUid':'loki','spanStartTimeShift':'-1m','spanEndTimeShift':'1m','customQuery':True,'query':'{service_name=~"messenger-.*"} | json | trace_id="$${__trace.traceId}"'}
|
||||
sources.append({'name':name,'uid':name.lower(),'type':name.lower(),'access':'proxy','url':url,'jsonData':options,
|
||||
'secureJsonData':{key:(ROOT/'pki/grafana'/file).read_text() for key,file in [('tlsCACert','ca.crt'),('tlsClientCert','tls.crt'),('tlsClientKey','tls.key')]}})
|
||||
(ROOT/'secrets/grafana-datasources.yaml').write_text(json.dumps({'apiVersion':1,'datasources':sources},indent=2))
|
||||
env=ROOT/'.env'
|
||||
if not env.exists():env.write_text((ROOT/'.env.example').read_text());env.chmod(0o600)
|
||||
print('Local service configuration generated; no credentials printed.')
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Operator-only local PKI. Private CA never mounted into any service."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import subprocess
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
def command(*args):
|
||||
subprocess.run(['openssl',*map(str,args)],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
|
||||
def issue(role,days=1,foreign=False,identity=None,uri_identity=None):
|
||||
name=identity or role
|
||||
folder=ROOT/'pki'/role
|
||||
folder.mkdir(parents=True,exist_ok=True)
|
||||
ca=ROOT/'operator'/('foreign' if foreign else 'ca')
|
||||
config=folder/'request.cnf'
|
||||
config.write_text('[req]\nprompt=no\ndistinguished_name=dn\n[dn]\nCN='+name+'\n[ext]\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName=DNS:'+name+',DNS:localhost,IP:127.0.0.1,URI:spiffe://mtusi.lab/'+(uri_identity or name)+'\n')
|
||||
command('req','-new','-newkey','rsa:2048','-nodes','-keyout',folder/'tls.key','-out',folder/'request.csr','-config',config)
|
||||
if days:
|
||||
command('x509','-req','-in',folder/'request.csr','-CA',str(ca)+'.crt','-CAkey',str(ca)+'.key','-set_serial','0x'+secrets.token_hex(16),'-out',folder/'tls.crt','-days',days,'-sha256','-extfile',config,'-extensions','ext')
|
||||
else:
|
||||
op=ROOT/'operator'
|
||||
(op/'issued').mkdir(exist_ok=True)
|
||||
(op/'index.txt').touch()
|
||||
(op/'serial').write_text(secrets.token_hex(16)+'\n')
|
||||
cfg=op/'expired-ca.cnf'
|
||||
cfg.write_text('[ca]\ndefault_ca=local\n[local]\ndatabase='+str(op/'index.txt')+'\nserial='+str(op/'serial')+'\nnew_certs_dir='+str(op/'issued')+'\ncertificate='+str(ca)+'.crt\nprivate_key='+str(ca)+'.key\ndefault_md=sha256\npolicy=policy\n[policy]\ncommonName=supplied\n')
|
||||
command('ca','-batch','-notext','-config',cfg,'-in',folder/'request.csr','-out',folder/'tls.crt','-startdate','20000101000000Z','-enddate','20000102000000Z','-extfile',config,'-extensions','ext')
|
||||
|
||||
(folder/'tls.pem').write_bytes((folder/'tls.crt').read_bytes()+(folder/'tls.key').read_bytes())
|
||||
(folder/'ca.crt').write_bytes((ROOT/'operator/ca.crt').read_bytes())
|
||||
if not (folder/'revoked.list').exists():
|
||||
(folder/'revoked.list').write_text('00\n')
|
||||
# Parent pki is 0700 on host; a service mounts only its own folder.
|
||||
for f in folder.iterdir():f.chmod(0o644)
|
||||
return folder
|
||||
|
||||
def bootstrap():
|
||||
for n in ['operator','pki','secrets']:
|
||||
f=ROOT/n;f.mkdir(exist_ok=True);f.chmod(0o700)
|
||||
for role in ['ca','foreign']:
|
||||
base=ROOT/'operator'/role
|
||||
if not base.with_suffix('.key').exists():
|
||||
config=ROOT/'operator'/(role+'.cnf')
|
||||
config.write_text('[req]\nprompt=no\ndistinguished_name=dn\nx509_extensions=ext\n[dn]\nCN=MTUSI-LAB7-'+role+'\n[ext]\nbasicConstraints=critical,CA:TRUE\nkeyUsage=critical,keyCertSign,cRLSign\n')
|
||||
command('req','-x509','-newkey','rsa:3072','-nodes','-sha256','-days','30','-keyout',str(base)+'.key','-out',str(base)+'.crt','-config',config)
|
||||
base.with_suffix('.key').chmod(0o600)
|
||||
for role in ['lb','api','worker','dispatcher','operator','s3','broker','redis','otel-collector','collector','prometheus','loki','tempo','grafana','bao','postgres','outsider']:
|
||||
if not (ROOT/'pki'/role/'tls.key').exists():issue(role)
|
||||
if not (ROOT/'pki/foreign-client/tls.key').exists():issue('foreign-client',foreign=True)
|
||||
for identity in ['lb','api','worker','dispatcher','collector','prometheus','grafana']:
|
||||
if not (ROOT/'pki'/('expired-'+identity)/'tls.crt').exists():issue('expired-'+identity,days=0,identity=identity)
|
||||
if not (ROOT/'pki/wrong-lb/tls.crt').exists():issue('wrong-lb',identity='lb',uri_identity='outsider')
|
||||
print('Local PKI ready; CA keys remain in operator/ and are not mounted into services.')
|
||||
|
||||
if __name__=='__main__':bootstrap()
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
python3 scripts/snapshot.py > evidence/restart-before.json
|
||||
docker compose stop api lb worker dispatcher
|
||||
# Keep proxy namespace anchors: restarting the raw processes preserves the local boundary.
|
||||
docker compose restart postgres broker-raw redis-raw s3-store s3-raw otel-collector-raw prometheus-raw loki-raw tempo-raw grafana bao
|
||||
python3 scripts/bao_operator.py --unseal-only
|
||||
docker compose up -d --no-deps api lb worker dispatcher
|
||||
python3 scripts/snapshot.py > evidence/restart-after.json
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Explicit operator revocation/rollover; no image rebuild and no root credential in apps."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
import ssl
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from pki import ROOT,issue
|
||||
from bootstrap import main as bootstrap
|
||||
from bao_operator import URL,call,unseal,configure
|
||||
|
||||
def dc(*a,**kw):return subprocess.run(['docker','compose',*a],cwd=ROOT,check=True,**kw)
|
||||
def run():
|
||||
started=time.monotonic()
|
||||
dc('stop','worker')
|
||||
old=ROOT/'pki/revoked-worker';old.mkdir(exist_ok=True)
|
||||
for file in (ROOT/'pki/worker').iterdir():
|
||||
if file.is_file():shutil.copyfile(file,old/file.name)
|
||||
# Exact cert serial is public correlation data; keys and passwords remain local.
|
||||
serial=subprocess.check_output(['openssl','x509','-in',str(old/'tls.crt'),'-serial','-noout'],text=True).strip().split('=')[1]
|
||||
settings=json.loads((ROOT/'operator/settings.json').read_text())
|
||||
oldfile=ROOT/'operator/revoked-worker-settings.json';oldfile.write_text(json.dumps(settings));oldfile.chmod(0o600)
|
||||
root=unseal()
|
||||
def old_service(path,data=None,token=None):
|
||||
ctx=ssl.create_default_context(cafile=str(ROOT/'pki/worker/ca.crt'))
|
||||
ctx.load_cert_chain(str(ROOT/'pki/worker/tls.crt'),str(ROOT/'pki/worker/tls.key'))
|
||||
headers={'Content-Type':'application/json'}
|
||||
if token:headers['X-Vault-Token']=token
|
||||
req=urllib.request.Request(URL+'/v1/'+path,
|
||||
data=None if data is None else json.dumps(data).encode(),headers=headers)
|
||||
op=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
|
||||
with op.open(req,timeout=5) as response:return json.load(response)
|
||||
auth=old_service('auth/cert/login',{'name':'worker'})['auth']
|
||||
old_token=auth['client_token']
|
||||
assert old_service('secret/data/worker',token=old_token)['data']['data']
|
||||
token_created=time.monotonic()
|
||||
call('auth/cert/certs/worker',token=root,method='DELETE')
|
||||
# Revoke all outstanding worker tokens instead of assuming deleting a role revokes tokens.
|
||||
revoked_tokens=0
|
||||
try:accessors=call('auth/token/accessors',token=root,method='LIST')['data']['keys']
|
||||
except Exception:accessors=[]
|
||||
for accessor in accessors:
|
||||
try:
|
||||
info=call('auth/token/lookup-accessor',{'accessor':accessor},root)
|
||||
if 'worker' in info['data']['policies']:
|
||||
call('auth/token/revoke-accessor',{'accessor':accessor},root);revoked_tokens+=1
|
||||
except Exception:pass # An already-expired token is not still usable.
|
||||
try:old_service('secret/data/worker',token=old_token)
|
||||
except urllib.error.HTTPError as error:assert error.code==403
|
||||
else:raise AssertionError('Outstanding worker token still reads secrets after revocation')
|
||||
revoke_latency=time.monotonic()-token_created
|
||||
assert revoke_latency < auth['lease_duration']-1, 'Prove revocation before natural token expiry'
|
||||
for folder in (ROOT/'pki').iterdir():
|
||||
listing=folder/'revoked.list'
|
||||
if listing.exists() and folder.name!='revoked-worker':
|
||||
rows=set(listing.read_text().splitlines());rows.add(serial.lower());listing.write_text('\n'.join(sorted(rows))+'\n')
|
||||
for proxy in ['broker','s3','otel-collector']:
|
||||
dc('kill','-s','SIGUSR2',proxy)
|
||||
settings['worker']=secrets.token_hex(24)
|
||||
settings['broker_worker']=secrets.token_hex(24)
|
||||
settings['s3_worker']=secrets.token_hex(24)
|
||||
settings['s3_worker_key']=secrets.token_hex(12)
|
||||
file=ROOT/'operator/settings.json';file.write_text(json.dumps(settings));file.chmod(0o600)
|
||||
issue('worker')
|
||||
bootstrap()
|
||||
dc('--profile','tools','run','--rm','--no-deps','audit','/app/student-tests/rotation_db.py')
|
||||
# Raw process restart keeps the stable TLS/network boundary and persistent broker/S3 data.
|
||||
dc('restart','broker-raw','s3-raw')
|
||||
configure()
|
||||
dc('up','-d','--no-deps','worker')
|
||||
result={'revoked_certificate_serial':serial,'worker_tokens_revoked':revoked_tokens,'old_valid_token_denied_before_natural_expiry':True,'token_revoke_latency_seconds':round(revoke_latency,3),
|
||||
'passwords_rotated':['PostgreSQL worker','Redis worker','S3 worker'],
|
||||
'new_leaf_certificate':True,'proxy_hard_stop_seconds':5,'images_rebuilt':False,
|
||||
'seconds':round(time.monotonic()-started,3)}
|
||||
(ROOT/'evidence/worker-rotation.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
print('Worker identity revoked, fresh secrets/certificate installed; no secrets printed.')
|
||||
return result
|
||||
if __name__=='__main__':run()
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Sanitized process and resource evidence; never dump container environments."""
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
ids = subprocess.check_output(['docker', 'compose', 'ps', '-aq'], text=True).split()
|
||||
records = []
|
||||
for container in ids:
|
||||
raw = subprocess.check_output(['docker', 'inspect', container], text=True)
|
||||
data = json.loads(raw)[0]
|
||||
records.append({'container': data['Id'], 'name': data['Name'], 'service': data['Config']['Labels']['com.docker.compose.service'], 'image': data['Config']['Image'], 'user': data['Config']['User'], 'running': data['State']['Running'], 'started_at': data['State']['StartedAt'], 'exit_code': data['State']['ExitCode'], 'oom_killed': data['State']['OOMKilled'], 'memory_limit': data['HostConfig']['Memory'], 'nano_cpus': data['HostConfig']['NanoCpus'], 'ports': data['NetworkSettings']['Ports'], 'mounts': [{'type': m['Type'], 'destination': m['Destination'], 'name': m.get('Name')} for m in data['Mounts']]})
|
||||
print(json.dumps(records, indent=2))
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Reproducible explicit operator bring-up; no automatic unseal inside the Bao container."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
from bootstrap import main as bootstrap
|
||||
from bao_operator import configure,call
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
def dc(*args):subprocess.run(['docker','compose',*args],cwd=ROOT,check=True)
|
||||
bootstrap()
|
||||
dc('build','api')
|
||||
dc('up','-d','postgres','bao','s3-raw','broker-raw','redis-raw','otel-collector-raw','prometheus-raw','loki-raw','tempo-raw','grafana')
|
||||
for _ in range(90):
|
||||
try:call('sys/init');break
|
||||
except Exception:time.sleep(1)
|
||||
else:raise SystemExit('OpenBao TLS startup timeout')
|
||||
configure()
|
||||
# Filer bootstrap is asynchronous; do not mistake initial socket creation for ready S3.
|
||||
for _ in range(60):
|
||||
result=subprocess.run(['docker','compose','run','--rm','--no-deps','bucket-bootstrap'],cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
if result.returncode==0:break
|
||||
time.sleep(1)
|
||||
else:raise SystemExit('Authenticated S3 bootstrap timeout')
|
||||
dc('up','-d','migrate')
|
||||
dc('up','-d','api','lb','worker','dispatcher')
|
||||
print('Lab7 processes started; waiting for verified HTTPS readiness.')
|
||||
import ssl,urllib.request
|
||||
url=os.environ.get('BASE_URL','https://localhost:'+os.environ.get('APP_PORT','18443'))
|
||||
context=ssl.create_default_context(cafile=str(ROOT/'pki/lb/ca.crt'))
|
||||
for _ in range(120):
|
||||
try:
|
||||
with urllib.request.urlopen(url+'/health/ready',context=context,timeout=2) as r:
|
||||
if r.status==200:break
|
||||
except OSError:pass
|
||||
time.sleep(.5)
|
||||
else:raise SystemExit('HTTPS readiness timeout')
|
||||
print('Lab7 ready over trusted HTTPS; operator secrets stay local.')
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/stop_one.py
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Stop the exact alias requested by the public failover test, using operator exec."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
def dc(*a):return subprocess.check_output(['docker',*a],text=True).strip()
|
||||
target=os.environ['TARGET_INSTANCE_ID'];started=time.monotonic()
|
||||
for container in dc('compose','ps','-q','api').splitlines():
|
||||
alias=dc('exec',container,'cat','/tmp/instance')
|
||||
if alias==target:
|
||||
dc('stop','--time','8',container)
|
||||
state=json.loads(dc('inspect','--format','{{json .State}}',container))
|
||||
assert not state['Running']
|
||||
record={'instance':target,'container':container,'running':False,'exit_code':state['ExitCode'],'seconds':round(time.monotonic()-started,3)}
|
||||
with Path('evidence/stopped-instances.jsonl').open('a') as f:f.write(json.dumps(record)+'\n')
|
||||
print(json.dumps(record));break
|
||||
else:raise SystemExit('Exact alias not found')
|
||||
Reference in New Issue
Block a user