ЛР 7 — БПИ2304 — Кирюпина — на 3
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
SashaKirupina
2026-11-28 00:31:13 +03:00
parent 20afc2c790
commit 7fb93b31ba
93 changed files with 8017 additions and 122 deletions
+38
View File
@@ -0,0 +1,38 @@
"""Operator-only init/unseal/configure. Never prints or mounts operator credentials."""
from pathlib import Path
import json,ssl,urllib.request,urllib.error,os,sys,time
ROOT=Path(__file__).resolve().parents[1]
os.chdir(ROOT)
def context(role=None):
ctx=ssl.create_default_context(cafile='certs/ca.crt')
if role:ctx.load_cert_chain('certs/'+role+'.crt','certs/'+role+'.key')
return ctx
def call(path,data=None,token=None,role=None):
req=urllib.request.Request('https://localhost:8207/v1/'+path,data=None if data is None else json.dumps(data).encode(),headers={'Content-Type':'application/json',**({'X-Vault-Token':token} if token else {})})
with urllib.request.urlopen(req,context=context(role),timeout=10) as res:
body=res.read();return json.loads(body) if body else {}
def main():
state=Path('operator/bao-init.json')
if not call('sys/init')['initialized']:
if state.exists():raise RuntimeError('Existing operator backup but Bao storage is empty; restore storage or explicitly start a new lab.')
result=call('sys/init',{'secret_shares':1,'secret_threshold':1})
state.write_text(json.dumps(result),encoding='utf8');state.chmod(0o600)
if not state.exists():raise RuntimeError('Operator unseal backup required')
saved=json.loads(state.read_text())
if call('sys/seal-status')['sealed']:call('sys/unseal',{'key':saved['keys_base64'][0]})
if '--unseal-only' in sys.argv:
print('PASS: OpenBao unsealed by operator; no keys sent to application containers.');return
root=saved['root_token']
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)
c=json.loads(Path('operator/credentials.json').read_text())
for role in ['api','worker']:
call('sys/policies/acl/'+role,{'policy':Path('infra/openbao/'+role+'.hcl').read_text()},root)
call('auth/cert/certs/'+role,{'certificate':Path('certs/ca.crt').read_text(),'allowed_dns_sans':[role],'token_policies':[role],'token_ttl':300,'token_max_ttl':600,'token_no_default_policy':True},root)
call('secret/data/'+role,{'data':{'database_url':'postgresql://'+role+':'+c['db_'+role]+'@db:5432/messenger','broker_url':'amqps://'+role+':'+c['rabbit_'+role]+'@broker:5671/messenger?heartbeat=5','s3_access_key':role,'s3_secret_key':c['s3_'+role]}},root)
print('PASS: persistent OpenBao initialized/unsealed; cert-auth roles and scoped KV policies configured.')
if __name__=='__main__':
try:main()
except urllib.error.HTTPError as e:raise SystemExit('OpenBao operation rejected: HTTP '+str(e.code))
+18
View File
@@ -0,0 +1,18 @@
"""Verify provisioned dashboards using authenticated HTTPS without exporting credentials."""
from pathlib import Path
import json,ssl,urllib.request,base64
ROOT=Path(__file__).resolve().parents[1]
ctx=ssl.create_default_context(cafile=str(ROOT/'certs/ca.crt'))
password=(ROOT/'secrets/grafana_password').read_text().strip()
headers={'Authorization':'Basic '+base64.b64encode(('admin:'+password).encode()).decode()}
def get(path):
with urllib.request.urlopen(urllib.request.Request('https://localhost:3447'+path,headers=headers),context=ctx,timeout=20) as r:return json.load(r)
dashboard=get('/api/dashboards/uid/messenger-lab7')
assert len(dashboard['dashboard']['panels'])==9
result={'dashboard_uid':'messenger-lab7','panel_count':9,'datasources':{}}
for name,path in [('prometheus','/api/v1/query?query=messenger_http_requests_total'),('loki','/loki/api/v1/labels'),('tempo','/api/search?limit=5')]:
value=get('/api/datasources/proxy/uid/'+name+path)
assert value
result['datasources'][name]='verified HTTPS/mTLS query via Grafana'
(ROOT/'evidence/grafana.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf8')
print('PASS: authenticated Grafana HTTPS, nine provisioned panels, real queries through all three TLS/mTLS data sources.')
+22
View File
@@ -0,0 +1,22 @@
"""Inspect only safe Docker configuration fields, never Env or full inspect output."""
from pathlib import Path
import json,subprocess
ROOT=Path(__file__).resolve().parents[1]
ids=subprocess.check_output(['docker','compose','ps','-q'],cwd=ROOT,text=True).split()
raw=json.loads(subprocess.check_output(['docker','inspect',*ids],text=True))
result=[]
for c in raw:
h=c['HostConfig'];service=c['Config']['Labels']['com.docker.compose.service']
assert not h['Privileged'] and h['NetworkMode']!='host'
assert not any('docker.sock' in m['Source'] for m in c['Mounts'])
assert h['Memory']>0 and h['NanoCpus']>0
ports=h.get('PortBindings') or {}
for bindings in ports.values():
for b in bindings or []:assert b['HostIp']=='127.0.0.1'
if service in ['api1','api2','worker']:
assert c['Config']['User']=='1000:1000'
assert 'ALL' in h['CapDrop'] and 'no-new-privileges:true' in h['SecurityOpt']
assert all(m['Destination'] in ['/tls/ca.crt','/tls/cert.crt','/tls/key.pem'] for m in c['Mounts'])
result.append({'service':service,'user':c['Config']['User'],'memory_bytes':h['Memory'],'nano_cpus':h['NanoCpus'],'privileged':False,'published_ports':ports,'cap_drop':h.get('CapDrop'),'security_opt':h.get('SecurityOpt')})
(ROOT/'evidence/hardening.json').write_text(json.dumps(result,indent=2)+'\n')
print('PASS: non-root API/worker, dropped capabilities, resource limits, no privileged/host-network/socket; only localhost TLS/admin ports exposed; app mounts contain only its leaf key/cert and public CA.')
+34
View File
@@ -0,0 +1,34 @@
"""Explicit operator lifecycle hooks; volumes and secrets are preserved."""
from pathlib import Path
import subprocess,sys,os,json,time,urllib.error
import bao
ROOT=Path(__file__).resolve().parents[1];os.chdir(ROOT)
def dc(*args):return subprocess.check_output(['docker','compose',*args],text=True,stderr=subprocess.DEVNULL).strip()
def snapshot():
ids=dc('ps','-a','-q').splitlines()
data=json.loads(subprocess.check_output(['docker','inspect',*ids],text=True))
return [{'service':x['Config']['Labels']['com.docker.compose.service'],'container':x['Id'],'started_at':x['State']['StartedAt'],'running':x['State']['Running'],'volumes':[v['Name'] for v in x['Mounts'] if v['Type']=='volume']} for x in data if x['Config']['Labels']['com.docker.compose.service'] not in ['migrate','s3-init','checks']]
def main():
action=sys.argv[1];before=snapshot()
if action=='restart':
dc('stop');dc('up','-d','db','s3','broker','bao','otel-collector','prometheus','loki','tempo','grafana','otel-collector-tls','prometheus-tls','loki-tls','tempo-tls')
for i in range(40):
try:bao.call('sys/init');break
except urllib.error.URLError:time.sleep(1)
# This script runs on the operator host, never inside an application container.
saved=json.loads((ROOT/'operator/bao-init.json').read_text())
if bao.call('sys/seal-status')['sealed']:bao.call('sys/unseal',{'key':saved['keys_base64'][0]})
dc('up','-d','--wait','--wait-timeout','40','api1','api2','worker');dc('up','-d','lb')
elif action=='stop-one':
target=os.environ['TARGET_INSTANCE_ID'];selected=None
for service in ['api1','api2']:
value=dc('exec','-T',service,'node','-e',"fetch('http://127.0.0.1:9001/health/live').then(r=>console.log(r.headers.get('x-instance-id')))")
if value==target:selected=service;break
if not selected:raise RuntimeError('Unknown API instance')
dc('stop','-t','2',selected)
elif action=='restore':dc('up','-d','--wait','api1','api2')
else:raise RuntimeError('Unknown action')
after=snapshot()
(ROOT/'evidence'/('lifecycle-'+action+'.json')).write_text(json.dumps({'before':before,'after':after},indent=2)+'\n')
print('PASS: '+action+' complete for lab7; volumes preserved')
if __name__=='__main__':main()
+7
View File
@@ -0,0 +1,7 @@
@echo off
if defined LAB_PYTHON (
"%LAB_PYTHON%" -X utf8 "%~dp0control.py" restart
) else (
py -X utf8 "%~dp0control.py" restart
)
exit /b %errorlevel%
+2
View File
@@ -0,0 +1,2 @@
#!/bin/sh
exec python3 "$(dirname "$0")/control.py" restart
+71
View File
@@ -0,0 +1,71 @@
"""Local bootstrap material. Requires cryptography; never overwrites existing keys/secrets."""
from pathlib import Path
from datetime import datetime,timedelta,timezone
import json,secrets,shutil,hashlib,base64,os
from cryptography import x509
from cryptography.x509.oid import NameOID,ExtendedKeyUsageOID
from cryptography.hazmat.primitives import hashes,serialization
from cryptography.hazmat.primitives.asymmetric import rsa
ROOT=Path(__file__).resolve().parents[1]
os.chdir(ROOT)
for d in ['certs','operator','secrets']:
Path(d).mkdir(exist_ok=True);Path(d).chmod(0o700)
def write(path,value,mode=0o644):
p=Path(path);p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(value if isinstance(value,bytes) else value.encode());p.chmod(mode)
def make_ca(name):
certpath=Path('certs/'+name+'.crt');keypath=Path('operator/'+name+'.key')
if certpath.exists() and keypath.exists():return x509.load_pem_x509_certificate(certpath.read_bytes()),serialization.load_pem_private_key(keypath.read_bytes(),None)
if certpath.exists() or keypath.exists():raise SystemExit('Incomplete CA: restore operator backup')
key=rsa.generate_private_key(public_exponent=65537,key_size=3072)
nameobj=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,name)])
now=datetime.now(timezone.utc)
cert=x509.CertificateBuilder().subject_name(nameobj).issuer_name(nameobj).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),critical=True).add_extension(x509.KeyUsage(True,False,False,False,False,True,True,False,False),critical=True).sign(key,hashes.SHA256())
write(certpath,cert.public_bytes(serialization.Encoding.PEM));write(keypath,key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()),0o600)
return cert,key
ca,cakey=make_ca('ca');bad,badkey=make_ca('untrusted-ca')
for name in ['lb','api1','api2','worker','db','s3','broker','bao','collector','prometheus','loki','tempo','grafana','operator','wrong-ca']:
if Path('certs/'+name+'.key').exists():continue
issuer,issuerkey=(bad,badkey) if name=='wrong-ca' else (ca,cakey)
key=rsa.generate_private_key(public_exponent=65537,key_size=2048);now=datetime.now(timezone.utc)
names=[name]
if name in ['api1','api2']:names.append('api')
if name in ['lb','bao','grafana']:names.append('localhost')
if name=='collector':names.append('otel-collector')
cert=x509.CertificateBuilder().subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,name)])).issuer_name(issuer.subject).public_key(key.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-timedelta(minutes=5)).not_valid_after(now+timedelta(days=30)).add_extension(x509.BasicConstraints(ca=False,path_length=None),True).add_extension(x509.SubjectAlternativeName([x509.DNSName(n) for n in names]),False).add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH,ExtendedKeyUsageOID.CLIENT_AUTH]),False).sign(issuerkey,hashes.SHA256())
pub=cert.public_bytes(serialization.Encoding.PEM);priv=key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption())
write('certs/'+name+'.crt',pub);write('certs/'+name+'.key',priv);write('certs/'+name+'.pem',pub+priv)
# Individual key files are readable by non-root container users; the host directory is private.
file=Path('operator/credentials.json')
if not file.exists():write(file,json.dumps({k:secrets.token_hex(24) for k in ['db_admin','db_api','db_worker','s3_admin','s3_api','s3_worker','rabbit_api','rabbit_worker','grafana']},indent=2),0o600)
c=json.loads(file.read_text())
write('secrets/postgres_password',c['db_admin']);write('secrets/database_url','postgresql://messenger:'+c['db_admin']+'@db:5432/messenger')
write('secrets/s3_admin_user','localadmin');write('secrets/s3_admin_password',c['s3_admin']);write('secrets/grafana_password',c['grafana'])
write('secrets/roles.sql',f"CREATE ROLE api LOGIN PASSWORD '{c['db_api']}';\nCREATE ROLE worker LOGIN PASSWORD '{c['db_worker']}';\nREVOKE CREATE ON SCHEMA public FROM PUBLIC;\n")
write('secrets/pg_hba.conf','local all all trust\nhostnossl all all all reject\nhostssl messenger messenger all scram-sha-256\nhostssl messenger api all scram-sha-256\nhostssl messenger worker all scram-sha-256\nhostssl all all all reject\n')
users=[]
for role in ['api','worker']:
salt=secrets.token_bytes(4);hashed=base64.b64encode(salt+hashlib.sha256(salt+c['rabbit_'+role].encode()).digest()).decode()
users.append({'name':role,'password_hash':hashed,'hashing_algorithm':'rabbit_password_hashing_sha256','tags':[]})
write('secrets/rabbit-definitions.json',json.dumps({'users':users,'vhosts':[{'name':'messenger'}],'permissions':[{'user':role,'vhost':'messenger','configure':'^attachments\\.v1$','write':'^(attachments\\.v1|amq\\.default)$','read':'^attachments\\.v1$' if role=='worker' else '^$'} for role in ['api','worker']]}))
write('secrets/rabbitmq.conf','listeners.tcp = none\nlisteners.ssl.default = 5671\nssl_options.cacertfile = /tls/ca.crt\nssl_options.certfile = /tls/cert.crt\nssl_options.keyfile = /tls/key.pem\nssl_options.verify = verify_none\nssl_options.fail_if_no_peer_cert = false\nload_definitions = /etc/rabbitmq/definitions.json\n')
# JSON is also valid YAML; secureJsonData stays in ignored local secrets.
sources=[]
for name,kind,url in [('Prometheus','prometheus','https://prometheus:3443'),('Loki','loki','https://loki:3443'),('Tempo','tempo','https://tempo:3443')]:
data={'name':name,'uid':kind,'type':kind,'access':'proxy','url':url,'editable':False,'isDefault':kind=='prometheus','jsonData':{'tlsAuth':True,'tlsAuthWithCACert':True,'serverName':kind},'secureJsonData':{'tlsCACert':Path('certs/ca.crt').read_text(),'tlsClientCert':Path('certs/grafana.crt').read_text(),'tlsClientKey':Path('certs/grafana.key').read_text()}}
if kind=='loki':data['jsonData']['derivedFields']=[{'name':'TraceID','matcherRegex':'"trace_id":"([a-f0-9]{32})"','datasourceUid':'tempo','url':'$${__value.raw}','urlDisplayLabel':'View trace'}]
sources.append(data)
write('secrets/datasources.yaml',json.dumps({'apiVersion':1,'datasources':sources},indent=2))
# One-time S3 provisioning input, not present in application containers.
script='set -eu\nmc alias set local https://s3:9000 localadmin '+c['s3_admin']+' >/dev/null\nmc mb --ignore-existing local/messenger-attachments >/dev/null\n'
for role in ['api','worker']:
prefix='arn:aws:s3:::messenger-attachments/'
statements=[{'Effect':'Allow','Action':['s3:GetBucketLocation','s3:ListBucket'],'Resource':['arn:aws:s3:::messenger-attachments']}]
if role=='api':
statements += [{'Effect':'Allow','Action':['s3:PutObject','s3:DeleteObject'],'Resource':[prefix+'staging/*']},{'Effect':'Allow','Action':['s3:GetObject'],'Resource':[prefix+'originals/*',prefix+'variants/*']}]
else:
statements += [{'Effect':'Allow','Action':['s3:GetObject'],'Resource':[prefix+'staging/*']},{'Effect':'Allow','Action':['s3:PutObject'],'Resource':[prefix+'originals/*',prefix+'variants/*']}]
write('secrets/s3-'+role+'.json',json.dumps({'Version':'2012-10-17','Statement':statements}))
script+=f'mc admin user add local {role} {c["s3_"+role]} >/dev/null\nmc admin policy create local {role} /config/s3-{role}.json >/dev/null\nmc admin policy attach local {role} --user {role} >/dev/null\n'
write('secrets/s3-init.sh',script)
if not Path('.env').exists():shutil.copyfile('.env.example','.env')
print('PASS: local certificates and bootstrap material ready; secret values not printed.')
+8
View File
@@ -0,0 +1,8 @@
@echo off
if defined LAB_PYTHON (
"%LAB_PYTHON%" -X utf8 "%~dp0control.py" stop-one
) else (
py -X utf8 "%~dp0control.py" stop-one
)
exit /b %errorlevel%
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
exec python3 "$(dirname "$0")/control.py" stop-one
+22
View File
@@ -0,0 +1,22 @@
"""Repeatable local operator startup; no secret values in output."""
from pathlib import Path
import subprocess,sys,time,urllib.error
import bao
ROOT=Path(__file__).resolve().parents[1]
def run(*args):subprocess.run(args,cwd=ROOT,check=True)
def main():
run(sys.executable,str(ROOT/'scripts/setup.py'))
run('docker','compose','build')
run('docker','compose','up','-d','db','s3','broker','bao','otel-collector','prometheus','loki','tempo','grafana','otel-collector-tls','prometheus-tls','loki-tls','tempo-tls')
for i in range(60):
try:bao.call('sys/init');break
except (urllib.error.URLError,TimeoutError):time.sleep(1)
else:raise RuntimeError('OpenBao listener unavailable')
bao.main()
run('docker','compose','run','--rm','migrate')
run('docker','compose','run','--rm','s3-init')
run('docker','compose','up','-d','--wait','--wait-timeout','90','api1','api2','worker')
run('docker','compose','up','-d','lb')
run('docker','compose','restart','lb')
print('PASS: lab7 started. HTTPS https://localhost:8443; CA certs/ca.crt')
if __name__=='__main__':main()