Проверить уровень 3, устойчивость и отрицательные сценарии, оформить отчёт

This commit is contained in:
2026-12-04 07:15:24 +03:00
parent d4f64bed85
commit 06459d3eed
54 changed files with 1934 additions and 126 deletions
+91
View File
@@ -0,0 +1,91 @@
"""Read-only contract, Git, secret, container and image-layer audit."""
import ast
import json
from pathlib import Path
import re
import subprocess
import sys
import tarfile
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'student-tests'))
from telemetry import secret_values
def command(*args):
return subprocess.check_output(args,cwd=ROOT,text=True,encoding='utf-8').strip()
def main():
baseline='20afc2c'
original=command('git','ls-tree','-r','--name-only',baseline).splitlines()
editable={'REPORT.md','contracts/trust-matrix.md','security/THREAT_MODEL.md','.github/pull_request_template.md'}
normative=[name for name in original if name not in editable]
assert not command('git','diff',baseline,'--',*normative),'Normative materials changed'
files=set(command('git','ls-files','--cached','--others','--exclude-standard').splitlines())
assert not any(name.startswith('secrets/') or name=='.env' or name.endswith(('.key','.pem')) for name in files)
values=[v.encode() for v in secret_values()]
for path in (ROOT/'secrets/tls').glob('*/key.key'):values.append(path.read_bytes())
values.append((ROOT/'secrets/operator/ca.key').read_bytes())
for name in files:
path=ROOT/name
if not path.is_file():continue
data=path.read_bytes()
assert not any(value in data for value in values),'Credential in tracked/evidence file: '+name
assert not re.search(rb'-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----',data),'Private key in '+name
if path.suffix=='.py':ast.parse(data,filename=name)
previous=[]
for name in ('vysoko-nagr 6_2','vysoko-nagr 6','vysoko-nagr 5','vysoko-nagr 4'):
folder=ROOT.parent/name
if not folder.exists():continue
def git(*args):return subprocess.check_output(['git','-C',str(folder),*args],text=True,encoding='utf-8').strip()
assert not git('diff','--name-only') and not git('diff','--cached','--name-only'),name+' changed'
previous.append({'folder':name,'head':git('rev-parse','HEAD'),'status':git('status','--short','--branch'),'origin':git('remote','get-url','origin')})
ids=command('docker','compose','ps','-q').splitlines()
objects=json.loads(command('docker','inspect',*ids))
containers=[]
for item in objects:
label=item['Config']['Labels']['com.docker.compose.service'];h=item['HostConfig']
assert not h['Privileged'] and h['NetworkMode']!='host'
assert h['Memory']>0 and h['NanoCpus']>0
assert not any('/docker.sock' in str(m) for m in item['Mounts'])
published=h.get('PortBindings') or {}
for port,bindings in published.items():
assert label in ('lb','openbao','grafana')
assert all(binding['HostIp']=='127.0.0.1' for binding in bindings)
if label in ('api1','api2','worker','dispatcher','cleaner'):
uid=int(command('docker','exec',item['Id'],'id','-u'));assert uid!=0
assert 'ALL' in (h['CapDrop'] or [])
containers.append({'service':label,'id':item['Id'][:12],'image':item['Config']['Image'],
'image_id':item['Image'],'state':item['State']['Status'],'started_at':item['State']['StartedAt'],
'cpu_limit':h['NanoCpus']/10**9,'memory_bytes':h['Memory'],'published':published,'user':item['Config']['User']})
env=dict(line.split('=',1) for line in (ROOT/'.env').read_text().splitlines() if '=' in line)
image_results=[]
for image in (env['APP_IMAGE'],env['S3_IMAGE']):
print('Scanning exported image layers:',image,flush=True)
proc=subprocess.Popen(['docker','image','save',image],stdout=subprocess.PIPE)
count=0
with tarfile.open(fileobj=proc.stdout,mode='r|*') as bundle:
for entry in bundle:
if not entry.isfile():continue
count+=1
source=bundle.extractfile(entry);tail=b''
while True:
block=source.read(1024*1024)
if not block:break
data=tail+block
assert not any(value in data for value in values),'Credential in exported image'
tail=data[-16384:]
assert proc.wait()==0
image_results.append({'image':image,'archive_members_scanned':count,'actual_credentials':'absent'})
commits=command('git','log',baseline+'..HEAD','--format=%h %an <%ae> | %cn <%ce>').splitlines()
assert all('Sergey Lyakhonov <lyserg119@gmail.com> | Sergey Lyakhonov <lyserg119@gmail.com>' in line for line in commits)
summary={'commit':command('git','rev-parse','HEAD'),'branch':command('git','branch','--show-current'),
'origin':command('git','remote','get-url','origin'),'normative_files_unchanged':len(normative),
'files_scanned':len(files),'secrets_scan':'PASS; actual credentials, private keys, tracked/evidence and exported layers',
'previous_projects':previous,'commits':commits,'containers':containers,'images':image_results}
(ROOT/'evidence/audit.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2),encoding='utf-8')
print('PASS normative materials, credentials, previous checkouts, identities and container hardening')
if __name__=='__main__':main()
+12 -3
View File
@@ -24,7 +24,9 @@ def write(path, data):
return
path.write_bytes(data if isinstance(data, bytes) else data.encode())
if os.name != 'nt':
path.chmod(0o600)
# Host root secrets directory is 0700. A role container receives ONLY
# its own files; read-only bind mounts must be readable by its nonroot UID.
path.chmod(0o600 if 'operator' in path.parts else 0o444)
def password(name):
@@ -47,6 +49,8 @@ def cert(name, ca_key, ca, foreign=False):
.not_valid_before(now-timedelta(minutes=5)).not_valid_after(now+timedelta(days=30))
.add_extension(x509.SubjectAlternativeName([x509.DNSName(n) for n in names]), False)
.add_extension(x509.BasicConstraints(ca=False, path_length=None), True)
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()),False)
.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),False)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH,ExtendedKeyUsageOID.CLIENT_AUTH]),False)
.sign(ca_key, hashes.SHA256()))
key_bytes = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
@@ -71,6 +75,9 @@ def main():
subprocess.run(['icacls',str(PRIVATE),'/inheritance:r','/grant:r',account+':(OI)(CI)F'],check=True,stdout=subprocess.DEVNULL)
else:
PRIVATE.chmod(0o700)
(PRIVATE/'operator').mkdir(exist_ok=True)
if os.name != 'nt':
(PRIVATE/'operator').chmod(0o700)
keypath = PRIVATE/'operator/ca.key'
capath = PRIVATE/'ca.crt'
if not keypath.exists():
@@ -83,12 +90,14 @@ def main():
.public_key(key.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(now-timedelta(minutes=5)).not_valid_after(now+timedelta(days=365))
.add_extension(x509.BasicConstraints(ca=True,path_length=0),True)
.add_extension(x509.KeyUsage(False,False,False,False,False,True,True,False,False),True)
.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),False)
.sign(key,hashes.SHA256()))
write(keypath,key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()))
write(capath,ca.public_bytes(serialization.Encoding.PEM))
key = serialization.load_pem_private_key(keypath.read_bytes(),password=None)
ca = x509.load_pem_x509_certificate(capath.read_bytes())
for name in ('lb','api1','api2','api','worker','dispatcher','cleaner','db','s3','broker','otel-collector','prometheus','loki','tempo','grafana','probe'):
for name in ('lb','api1','api2','api','worker','dispatcher','cleaner','openbao','db','s3','broker','otel-collector','prometheus','loki','tempo','grafana','probe'):
cert(name,key,ca)
foreign_key = rsa.generate_private_key(public_exponent=65537,key_size=2048)
now=datetime.now(timezone.utc)
@@ -115,7 +124,7 @@ def main():
for role in ('dispatcher','worker'):
definitions['users'].append({'name':role,'password':password('broker_'+role),'tags':[]})
definitions['permissions'].append({'user':role,'vhost':'lab7','configure':'^attachment\\.process\\.v1$',
'write':'^attachment\\.process\\.v1$' if role=='dispatcher' else '^$',
'write':'^amq.default$' if role=='dispatcher' else '^$',
'read':'^attachment\\.process\\.v1$' if role=='worker' else '^$'})
write(PRIVATE/'broker.json',json.dumps(definitions))
for role in ('api','worker','dispatcher','cleaner'):
+61
View File
@@ -0,0 +1,61 @@
"""Run checks with captured exit codes, sanitized output and guaranteed restore."""
import argparse
import os
from pathlib import Path
import subprocess
import sys
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'scripts'))
from manage import env,ready
def run(name,command):
result=subprocess.run(command,cwd=ROOT,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output=result.stdout.decode('utf-8',errors='replace')
(ROOT/'evidence'/name).write_text('COMMAND: '+' '.join(command)+'\nEXIT: '+str(result.returncode)+'\n'+output,encoding='utf-8')
print(output,flush=True)
if result.returncode:
raise RuntimeError(name+' failed with exit '+str(result.returncode))
def main():
p=argparse.ArgumentParser();p.add_argument('check',choices=['internal','public','persistence','failover','business','all']);a=p.parse_args()
os.chdir(ROOT)
base='https://localhost:'+env()['HTTPS_PORT']
common=['--base-url',base,'--ca-file',str(ROOT/'secrets/ca.crt')]
py=[sys.executable,'-X','utf8']
if a.check in ('internal','all'):
run('internal.txt',['docker','compose','run','--rm','verifier'])
if a.check in ('public','all'):
for script in ('smoke','security'):
run(script+'.txt',py+['tests/'+script+'.py']+common)
if a.check in ('business','all'):
run('business-security.txt',py+['student-tests/security_suite.py'])
if a.check in ('persistence','all'):
hook='scripts/restart.'+('cmd' if os.name=='nt' else 'sh')
run('persistence.txt',py+['tests/resilience.py','--mode','persistence','--action-script',hook]+common)
if a.check in ('failover','all'):
hook='scripts/stop-one.'+('cmd' if os.name=='nt' else 'sh')
completed=set()
for path in ROOT.glob('evidence/stop-api*.json'):
path.unlink() # Only this runner's known generated summaries.
for attempt in range(6):
try:
# Reject execution against a different checkout/project.
assert env()['COMPOSE_PROJECT_NAME'].startswith('lyakhonov-lab7')
config=subprocess.check_output(['docker','compose','config','--format','json'],cwd=ROOT)
import json
assert json.loads(config)['name']==env()['COMPOSE_PROJECT_NAME']
ready()
run('failover-'+str(attempt+1)+'.txt',py+['tests/resilience.py','--mode','failover','--action-script',hook]+common)
completed={path.stem for path in ROOT.glob('evidence/stop-api*.json')}
finally:
subprocess.run(['docker','compose','start','api1','api2'],cwd=ROOT,check=True)
ready()
if completed=={'stop-api1','stop-api2'}:
print('PASS sequential failover proved for both real API containers; both restored.');return
raise RuntimeError('Both replica failures were not observed in six public scenarios')
if __name__=='__main__':main()
+116
View File
@@ -0,0 +1,116 @@
"""Reproducible orchestration, scoped to this checkout and project."""
import argparse
import json
import os
from pathlib import Path
import ssl
import subprocess
import sys
import time
import urllib.request
ROOT=Path(__file__).resolve().parents[1]
os.chdir(ROOT)
def compose(*args, **kwargs):
return subprocess.run(['docker','compose',*args],check=True,**kwargs)
def python(script,*args):
subprocess.run([sys.executable,'-X','utf8',str(ROOT/script),*args],check=True)
def env():
return dict(line.split('=',1) for line in (ROOT/'.env').read_text().splitlines() if '=' in line)
def ready():
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca.crt'))
endpoint='https://localhost:'+env()['HTTPS_PORT']+'/health/ready'
deadline=time.monotonic()+120
while time.monotonic()<deadline:
try:
with urllib.request.urlopen(endpoint,context=ctx,timeout=3) as response:
assert response.status==200
print('HTTPS readiness: 200, CA and localhost SAN verified');return
except (OSError,AssertionError):
time.sleep(.5)
raise RuntimeError('HTTPS readiness exceeded 120 seconds')
def snapshot():
ids=subprocess.check_output(['docker','compose','ps','-aq'],text=True).split()
result=[]
objects=json.loads(subprocess.check_output(['docker','inspect',*ids],text=True)) if ids else []
for d in objects:
result.append({'service':d['Config']['Labels']['com.docker.compose.service'],'id':d['Id'][:12],
'started_at':d['State']['StartedAt'],'status':d['State']['Status']})
return result
def main():
parser=argparse.ArgumentParser()
parser.add_argument('action',choices=['start','restart','stop-one','ready'])
parser.add_argument('--initialize',action='store_true')
parser.add_argument('--unseal',action='store_true')
a=parser.parse_args()
assert env()['COMPOSE_PROJECT_NAME'].startswith('lyakhonov-lab7')
if a.action=='ready':
ready();return
if a.action=='start':
compose('build','api1','s3')
compose('up','-d','db','s3','broker','openbao','prometheus','loki','tempo','otel-collector')
# Health init endpoint works while sealed, and validates CA/hostname.
sys.path.insert(0,str(ROOT/'scripts'))
from bao import request
for _ in range(60):
try:
request('sys/init');break
except OSError:
time.sleep(.5)
else:
raise RuntimeError('OpenBao TLS listener not ready')
if a.initialize:
python('scripts/bao.py','init')
if a.unseal:
python('scripts/bao.py','unseal')
python('scripts/bao.py','configure')
for _ in range(60):
probe=subprocess.run(['docker','compose','exec','-T','db','pg_isready','-U','messenger','-d','messenger'],stdout=subprocess.DEVNULL)
if probe.returncode==0:break
time.sleep(.5)
compose('run','--rm','migrate')
compose('exec','-T','db','psql','-v','ON_ERROR_STOP=1','-U','messenger','-d','messenger',input=(ROOT/'infra/grants.sql').read_bytes())
compose('run','--rm','bucket-init')
compose('up','-d')
ready();return
before=snapshot()
if a.action=='restart':
compose('restart','api1','api2','worker','dispatcher','cleaner','db','s3','broker','openbao','prometheus','loki','tempo','grafana','otel-collector')
compose('restart','prometheus-tls','loki-tls','tempo-tls','tempo-tls-ingest')
if not a.unseal:
raise RuntimeError('Explicit --unseal operator action required after OpenBao restart')
# The key remains on the host. This hook is run by the operator, not app.
for _ in range(40):
result=subprocess.run([sys.executable,'-X','utf8','scripts/bao.py','unseal'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
if result.returncode==0:break
time.sleep(.5)
else:raise RuntimeError('Unseal failed')
ready()
else:
target=os.environ['TARGET_INSTANCE_ID']
found=[]
code="import urllib.request;print(urllib.request.urlopen('http://127.0.0.1:8080/health/live').headers['X-Instance-Id'])"
for service in ('api1','api2'):
current=subprocess.check_output(['docker','compose','exec','-T',service,'python','-c',code],text=True).strip()
if current==target:found.append(service)
assert len(found)==1,'Unknown or ambiguous process alias'
compose('stop','-t','1',found[0])
result={'action':a.action,'before':before,'after':snapshot()}
path=ROOT/'evidence'/('restart.json' if a.action=='restart' else 'stop-'+found[0]+'.json')
path.write_text(json.dumps(result,indent=2),encoding='utf-8')
if __name__=='__main__':
main()
+63
View File
@@ -0,0 +1,63 @@
"""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()
+2
View File
@@ -0,0 +1,2 @@
@echo off
"%~dp0..\.venv\Scripts\python.exe" -X utf8 "%~dp0manage.py" restart --unseal
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
set -eu
exec python3 -X utf8 "$(dirname "$0")/manage.py" restart --unseal
+2
View File
@@ -0,0 +1,2 @@
@echo off
"%~dp0..\.venv\Scripts\python.exe" -X utf8 "%~dp0manage.py" stop-one
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
set -eu
exec python3 -X utf8 "$(dirname "$0")/manage.py" stop-one