Files
mtusi2026lab7/scripts/reproduce.py
T

64 lines
3.3 KiB
Python

"""Clean Git export; new CA/secrets, project, images, volumes and free ports."""
import io
import json
from pathlib import Path
import shutil
import socket
import subprocess
import sys
import tarfile
import tempfile
import uuid
ROOT=Path(__file__).resolve().parents[1]
def main():
project='lyakhonov-lab7-repro-'+uuid.uuid4().hex[:8]
target=Path(tempfile.mkdtemp(prefix=project+'-')).resolve()
assert target.is_relative_to(Path(tempfile.gettempdir()).resolve())
assert target.name.startswith(project+'-')
commit=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip()
archive=subprocess.check_output(['git','archive','HEAD'],cwd=ROOT)
with tarfile.open(fileobj=io.BytesIO(archive)) as bundle:
bundle.extractall(target,filter='data')
handles=[]
for _ in range(3):
handle=socket.socket();handle.bind(('127.0.0.1',0));handles.append(handle)
ports=[handle.getsockname()[1] for handle in handles]
for handle in handles:handle.close()
results=[]
def run(command,label):
print(label,flush=True)
result=subprocess.run(command,cwd=target,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
text=result.stdout.decode('utf-8',errors='replace')
results.append({'step':label,'exit':result.returncode,'output':text if result.returncode else
'\n'.join(line for line in text.splitlines() if any(word in line for word in ('PASS','ready','Initialized','unsealed','configured','preserved')))})
if result.returncode:
print(text[-5000:]);raise RuntimeError('Clean reproduction failed at '+label)
py=[sys.executable,'-X','utf8']
summary={'project':project,'exported_commit':commit,'ports':ports,'steps':results}
try:
run(py+['scripts/bootstrap.py','--project',project,'--port',str(ports[0]),'--bao-port',str(ports[1]),'--grafana-port',str(ports[2])],'new PKI and secrets')
# Explicit operator authorization to initialize and unseal THIS new project.
run(py+['scripts/manage.py','start','--initialize','--unseal'],'build, bootstrap OpenBao, migrate, readiness')
run(py+['scripts/check.py','public'],'public HTTPS smoke and external TLS trust')
run(py+['scripts/check.py','internal'],'internal mTLS, TLS links and policy deny')
summary['result']='PASS'
except Exception:
summary['result']='FAIL';raise
finally:
if (target/'.env').exists():
actual=dict(line.split('=',1) for line in (target/'.env').read_text().splitlines() if '=' in line)
assert actual['COMPOSE_PROJECT_NAME']==project
subprocess.run(['docker','compose','down','--volumes','--remove-orphans'],cwd=target,check=True,stdout=subprocess.DEVNULL)
subprocess.run(['docker','image','rm',project+'-app:1.0',project+'-s3:1.0'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
summary['temporary_resources_removed']=True
(ROOT/'evidence/reproduction.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding='utf-8')
assert target.is_relative_to(Path(tempfile.gettempdir()).resolve()) and target.name.startswith(project+'-')
shutil.rmtree(target)
print('PASS clean Git export, new PKI/secrets, startup and security; temporary resources removed.')
if __name__=='__main__':main()