@@ -0,0 +1,371 @@
#!/usr/bin/env python3
"""
lab7: операторские действия стенда (Python 3.9+, только стандартная библиотека; Windows/macOS/Linux).
python scripts/lab7.py bootstrap # первый запуск: PKI, OpenBao, роли БД, MinIO, стенд
python scripts/lab7.py unseal # после рестарта контейнера openbao (он sealed)
python scripts/lab7.py status
python scripts/lab7.py seal # демонстрация: OpenBao запечатан
python scripts/lab7.py rotate-db-password api
python scripts/lab7.py rotate-cert lb # новый leaf + reload LB без пересборки образов
python scripts/lab7.py revoke-cert lb # отзыв ПРЕДЫДУЩЕГО leaf lb (CRL → API, otel-gw)
Где что хранится (ничего из этого не попадает в Git, в образы и в вывод):
./secrets/ — docker secrets инфраструктуры (пароль суперпользователя PostgreSQL,
root MinIO, admin Grafana) и открытый ca.crt для тестов на хосте;
~/.mtusi-lab7/ — материал оператора OpenBao: unseal shares и root token
(MTUSI_OPERATOR_DIR переопределяет путь). В контейнеры не монтируется.
volume pki-ca — закрытый ключ CA (только одноразовый контейнер pki).
Секреты передаются в контейнеры через stdin или переменные окружения процесса docker exec,
никогда — аргументами командной строки.
"""
from __future__ import annotations
import json
import os
import secrets
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path ( __file__ ) . resolve ( ) . parent . parent
SECRETS = ROOT / " secrets "
OPERATOR = Path ( os . getenv ( " MTUSI_OPERATOR_DIR " , str ( Path . home ( ) / " .mtusi-lab7 " ) ) )
INIT_FILE = OPERATOR / " openbao-init.json "
C = [ " docker " , " compose " ] + ( [ " --env-file " , str ( ROOT / " .env " ) ] if ( ROOT / " .env " ) . exists ( ) else [ ] )
ROLES = ( " api " , " worker " , " migrate " )
BUCKET = os . getenv ( " S3_BUCKET " , " messenger-attachments " )
# ----------------------------------------------------------------- утилиты
def run ( args : list [ str ] , * , input : str | None = None , env : dict | None = None , check : bool = True ,
capture : bool = True , quiet : bool = False ) - > subprocess . CompletedProcess :
if not quiet :
print ( " $ " , " " . join ( a if len ( a ) < 120 else a [ : 117 ] + " ... " for a in args ) )
p = subprocess . run ( args , cwd = ROOT , input = input , text = True , encoding = " utf-8 " , errors = " replace " ,
capture_output = capture , env = { * * os . environ , * * ( env or { } ) } )
if check and p . returncode != 0 :
# stderr команд не содержит секретов (секреты идут только через stdin/env)
sys . exit ( f " command failed ( { p . returncode } ): { ' ' . join ( args [ : 6 ] ) } \n { ( p . stderr or ' ' ) [ - 800 : ] } " )
return p
def step ( title : str ) - > None :
print ( f " \n == { title } " )
def rand ( n : int = 24 ) - > str :
return secrets . token_urlsafe ( n )
def write_private ( path : Path , value : str ) - > None :
path . parent . mkdir ( parents = True , exist_ok = True )
path . write_text ( value , encoding = " utf-8 " )
try :
os . chmod ( path , 0o600 )
except OSError :
pass
def compose_ps ( service : str ) - > list [ dict ] :
p = run ( C + [ " ps " , " --all " , " --format " , " json " , service ] , check = False , quiet = True )
out = ( p . stdout or " " ) . strip ( )
if not out :
return [ ]
try :
data = json . loads ( out )
return data if isinstance ( data , list ) else [ data ]
except ValueError :
return [ json . loads ( line ) for line in out . splitlines ( ) if line . strip ( ) . startswith ( " { " ) ]
def wait_healthy ( services : list [ str ] , timeout : int = 240 ) - > None :
deadline = time . time ( ) + timeout
pending = set ( services )
while pending and time . time ( ) < deadline :
for s in list ( pending ) :
rows = compose_ps ( s )
if rows and all ( r . get ( " Health " ) in ( " healthy " , " " ) and r . get ( " State " ) == " running " for r in rows ) \
and any ( r . get ( " Health " ) == " healthy " for r in rows ) :
pending . discard ( s )
if pending :
time . sleep ( 3 )
if pending :
sys . exit ( f " not healthy after { timeout } s: { ' , ' . join ( sorted ( pending ) ) } (docker compose ps / logs) " )
print ( " healthy: " , " , " . join ( services ) )
# ----------------------------------------------------------------- OpenBao
def bao ( args : list [ str ] , * , token : str | None = None , input : str | None = None , check : bool = True ,
quiet : bool = False ) - > subprocess . CompletedProcess :
env = { }
cmd = C + [ " exec " , " -T " ]
if token :
env [ " BAO_TOKEN " ] = token
cmd + = [ " -e " , " BAO_TOKEN " ] # значение берётся из окружения docker CLI, не из argv
return run ( cmd + [ " openbao " , " bao " ] + args , input = input , env = env , check = check , quiet = quiet )
def bao_status ( ) - > dict :
p = bao ( [ " status " , " -format=json " ] , check = False , quiet = True )
try :
return json . loads ( p . stdout )
except ValueError :
return { }
def wait_bao_running ( timeout : int = 90 ) - > dict :
deadline = time . time ( ) + timeout
while time . time ( ) < deadline :
st = bao_status ( )
if st :
return st
time . sleep ( 2 )
sys . exit ( " openbao is not answering (docker compose logs openbao) " )
def load_init ( ) - > dict :
if not INIT_FILE . exists ( ) :
sys . exit ( f " no operator material at { INIT_FILE } : run bootstrap first (or restore your backup) " )
return json . loads ( INIT_FILE . read_text ( encoding = " utf-8 " ) )
def cmd_unseal ( _ = None ) - > None :
step ( " OpenBao unseal (2 of 3 shares, keys via stdin) " )
st = wait_bao_running ( )
if not st . get ( " initialized " ) :
sys . exit ( " openbao is not initialized: run bootstrap " )
if not st . get ( " sealed " ) :
print ( " already unsealed " )
return
keys = load_init ( ) [ " unseal_keys_b64 " ]
for k in keys [ : int ( st . get ( " t " ) or 2 ) ] :
bao ( [ " write " , " -format=json " , " sys/unseal " , " key=- " ] , input = k , quiet = True )
st = bao_status ( )
print ( " sealed: " , st . get ( " sealed " ) )
if st . get ( " sealed " ) :
sys . exit ( " still sealed " )
def root_token ( ) - > str :
return load_init ( ) [ " root_token " ]
def kv_get ( path : str , token : str ) - > dict :
p = bao ( [ " kv " , " get " , " -format=json " , path ] , token = token , check = False , quiet = True )
if p . returncode != 0 :
return { }
d = json . loads ( p . stdout )
return dict ( d . get ( " data " , { } ) . get ( " data " ) or { } )
def kv_put ( path : str , values : dict , token : str ) - > int :
p = bao ( [ " kv " , " put " , " -format=json " , path , " - " ] , token = token , input = json . dumps ( values ) , quiet = True )
return int ( json . loads ( p . stdout ) . get ( " data " , { } ) . get ( " version " ) or 0 )
def configure_openbao ( token : str ) - > dict :
step ( " OpenBao: kv-v2, cert auth, audit, policies, roles " )
mounts = json . loads ( bao ( [ " secrets " , " list " , " -format=json " ] , token = token , quiet = True ) . stdout )
if " kv/ " not in mounts :
bao ( [ " secrets " , " enable " , " -path=kv " , " kv-v2 " ] , token = token )
auths = json . loads ( bao ( [ " auth " , " list " , " -format=json " ] , token = token , quiet = True ) . stdout )
if " cert/ " not in auths :
bao ( [ " auth " , " enable " , " cert " ] , token = token )
audits = json . loads ( bao ( [ " audit " , " list " , " -format=json " ] , token = token , check = False , quiet = True ) . stdout or " {} " )
if " file/ " not in audits :
bao ( [ " audit " , " enable " , " file " , " file_path=/openbao/logs/audit.log " ] , token = token )
for name in ( " messenger-api " , " messenger-worker " , " messenger-migrate " , " operator " ) :
bao ( [ " policy " , " write " , name , f " /openbao/policies/ { name } .hcl " ] , token = token )
for r in ROLES :
# Вход ТОЛЬКО сертификатом нашего CA с CN = роль; токен 15 мин, продление до 1 ч.
bao ( [ " write " , f " auth/cert/certs/ { r } " , " certificate=@/openbao/tls/ca.crt " ,
f " allowed_common_names= { r } " , f " token_policies=messenger- { r } " ,
" token_ttl=15m " , " token_max_ttl=1h " , f " display_name= { r } " ] , token = token )
values = { }
for r in ROLES :
cur = kv_get ( f " kv/messenger/ { r } " , token )
if not cur :
cur = { " db_username " : r , " db_password " : rand ( ) }
if r in ( " api " , " worker " ) :
cur . update ( s3_access_key_id = f " { r } - { secrets . token_hex ( 6 ) } " , s3_secret_access_key = rand ( 30 ) )
kv_put ( f " kv/messenger/ { r } " , cur , token )
print ( f " kv/messenger/ { r } : created (values not shown) " )
else :
print ( f " kv/messenger/ { r } : exists " )
values [ r ] = cur
return values
# ----------------------------------------------------------------- PostgreSQL, MinIO
def sql_quote ( s : str ) - > str :
return " ' " + s . replace ( " ' " , " ' ' " ) + " ' "
def configure_postgres ( values : dict ) - > None :
step ( " PostgreSQL: roles api/worker/migrate (password from OpenBao, via stdin) " )
lines = [ ]
for r in ROLES :
lines . append ( f " DO $$BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = ' { r } ' ) "
f " THEN CREATE ROLE { r } LOGIN; END IF; END$$; " )
lines . append ( f " ALTER ROLE { r } LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION "
f " PASSWORD { sql_quote ( values [ r ] [ ' db_password ' ] ) } ; " )
lines + = [ " ALTER DATABASE messenger OWNER TO migrate; " ,
" REVOKE ALL ON DATABASE messenger FROM PUBLIC; " ,
" GRANT CONNECT ON DATABASE messenger TO api, worker, migrate; " ]
run ( C + [ " exec " , " -T " , " postgres " , " psql " , " -U " , " postgres " , " -d " , " messenger " , " -v " , " ON_ERROR_STOP=1 " , " -q " ] ,
input = " \n " . join ( lines ) + " \n " )
print ( " roles ready; network access only TLS + client certificate CN = role (pg_hba) " )
def s3_policy ( role : str ) - > str :
b = f " arn:aws:s3::: { BUCKET } "
if role == " api " :
st = [
{ " Effect " : " Allow " , " Action " : [ " s3:PutObject " , " s3:DeleteObject " ] , " Resource " : [ f " { b } /staging/* " ] } ,
{ " Effect " : " Allow " , " Action " : [ " s3:GetObject " ] , " Resource " : [ f " { b } /originals/* " , f " { b } /variants/* " ] } ,
{ " Effect " : " Allow " , " Action " : [ " s3:ListBucket " ] , " Resource " : [ b ] ,
" Condition " : { " StringLike " : { " s3:prefix " : [ " staging/* " ] } } } ,
{ " Effect " : " Allow " , " Action " : [ " s3:GetBucketLocation " ] , " Resource " : [ b ] } ]
else :
st = [
{ " Effect " : " Allow " , " Action " : [ " s3:GetObject " ] ,
" Resource " : [ f " { b } /staging/* " , f " { b } /originals/* " , f " { b } /variants/* " ] } ,
{ " Effect " : " Allow " , " Action " : [ " s3:PutObject " ] , " Resource " : [ f " { b } /originals/* " , f " { b } /variants/* " ] } ,
{ " Effect " : " Allow " , " Action " : [ " s3:DeleteObject " ] , " Resource " : [ f " { b } /staging/* " ] } ,
{ " Effect " : " Allow " , " Action " : [ " s3:ListBucket " , " s3:GetBucketLocation " ] , " Resource " : [ b ] } ]
return json . dumps ( { " Version " : " 2012-10-17 " , " Statement " : st } )
def configure_minio ( values : dict ) - > None :
step ( " MinIO: private bucket, per-role users and prefix policies (script via stdin) " )
script = [ " set -eu " ,
' mc alias set root https://127.0.0.1:9000 " $(cat /run/secrets/minio_root_user) " '
' " $(cat /run/secrets/minio_root_password) " >/dev/null ' ,
f " mc mb --ignore-existing root/ { BUCKET } >/dev/null " ,
f " mc anonymous set none root/ { BUCKET } >/dev/null " ]
for r in ( " api " , " worker " ) :
ak , sk = values [ r ] [ " s3_access_key_id " ] , values [ r ] [ " s3_secret_access_key " ]
script + = [ f " cat > /tmp/p- { r } .json << ' POLICY ' " , s3_policy ( r ) , " POLICY " ,
f " mc admin policy create root lab7- { r } /tmp/p- { r } .json >/dev/null " ,
f " mc admin user add root ' { ak } ' ' { sk } ' >/dev/null " ,
f " mc admin policy attach root lab7- { r } --user ' { ak } ' >/dev/null 2>&1 || true " ,
f " rm -f /tmp/p- { r } .json " , f " echo ' user for { r } : policy lab7- { r } ' " ]
script + = [ " mc alias remove root >/dev/null " , " echo ' bucket private, root credentials not kept ' " ]
p = run ( C + [ " exec " , " -T " , " s3 " , " sh " , " -s " ] , input = " \n " . join ( script ) + " \n " )
print ( p . stdout . rstrip ( ) )
# ----------------------------------------------------------------- команды
def prepare_files ( ) - > None :
step ( " Local files: .env, docker secrets (./secrets), operator dir " )
if not ( ROOT / " .env " ) . exists ( ) and ( ROOT / " .env.example " ) . exists ( ) :
( ROOT / " .env " ) . write_text ( ( ROOT / " .env.example " ) . read_text ( encoding = " utf-8 " ) , encoding = " utf-8 " )
print ( " .env created from .env.example (no secrets inside) " )
for name , gen in ( ( " postgres_password " , rand ) , ( " minio_root_user " , lambda : " root- " + secrets . token_hex ( 4 ) ) ,
( " minio_root_password " , rand ) , ( " grafana_admin_password " , lambda : rand ( 18 ) ) ) :
p = SECRETS / name
if not p . exists ( ) :
write_private ( p , gen ( ) )
print ( f " secrets/ { name } : generated " )
OPERATOR . mkdir ( parents = True , exist_ok = True )
print ( f " operator dir: { OPERATOR } " )
def cmd_bootstrap ( _ = None ) - > None :
global C
prepare_files ( )
C = [ " docker " , " compose " , " --env-file " , str ( ROOT / " .env " ) ]
step ( " Build application image (also used by the PKI tool) " )
run ( C + [ " build " , " api " ] , capture = False )
step ( " PKI: CA + leaf certificates for every identity, CRL " )
run ( C + [ " --profile " , " ops " , " run " , " --rm " , " pki " , " init " ] , capture = False )
step ( " Start OpenBao (non-dev, raft storage, TLS) " )
run ( C + [ " up " , " -d " , " openbao " ] )
st = wait_bao_running ( )
if not st . get ( " initialized " ) :
step ( " OpenBao init: 3 shares, threshold 2 → operator dir (not printed) " )
p = bao ( [ " operator " , " init " , " -key-shares=3 " , " -key-threshold=2 " , " -format=json " ] , quiet = True )
write_private ( INIT_FILE , p . stdout )
print ( f " saved to { INIT_FILE } (в реальной эксплуатации shares раздаются разным людям) " )
cmd_unseal ( )
values = configure_openbao ( root_token ( ) )
step ( " Start data stores " )
run ( C + [ " up " , " -d " , " postgres " , " redis " , " broker " , " s3 " ] )
wait_healthy ( [ " postgres " , " redis " , " broker " , " s3 " ] )
configure_postgres ( values )
configure_minio ( values )
step ( " Start everything (migrate → api × 2 → worker → lb; telemetry; grafana) " )
run ( C + [ " up " , " -d " ] , capture = False )
wait_healthy ( [ " api " , " worker " , " lb " ] , timeout = 300 )
step ( " Done " )
print ( f " CA for clients: { SECRETS / ' ca.crt ' } " )
print ( " API: https://localhost:8443 (python tests/smoke.py --ca-file secrets/ca.crt) " )
print ( " Grafana: https://localhost:3000 admin / password in secrets/grafana_admin_password " )
print ( f " OpenBao unseal keys and root token: { INIT_FILE } (keep it safe; needed after OpenBao restart) " )
def cmd_status ( _ = None ) - > None :
st = bao_status ( )
print ( " openbao: " , { k : st . get ( k ) for k in ( " initialized " , " sealed " , " version " , " storage_type " ) } )
run ( C + [ " --profile " , " ops " , " run " , " --rm " , " pki " , " list " ] , capture = False , check = False )
run ( C + [ " ps " ] , capture = False , check = False )
def cmd_seal ( _ = None ) - > None :
step ( " OpenBao seal (operator action) " )
bao ( [ " operator " , " seal " ] , token = root_token ( ) )
print ( " sealed: " , bao_status ( ) . get ( " sealed " ) )
def cmd_rotate_db_password ( args ) - > None :
role = args [ 0 ] if args else " api "
if role not in ( " api " , " worker " ) :
sys . exit ( " role: api | worker " )
token = root_token ( )
step ( f " Rotate DB password of role { role } (KV first, then ALTER ROLE — no downtime) " )
cur = kv_get ( f " kv/messenger/ { role } " , token )
new = dict ( cur , db_password = rand ( ) , db_password_previous = cur . get ( " db_password " , " " ) )
ver = kv_put ( f " kv/messenger/ { role } " , new , token )
print ( f " kv/messenger/ { role } : version { ver } (current + previous password) " )
run ( C + [ " exec " , " -T " , " postgres " , " psql " , " -U " , " postgres " , " -d " , " messenger " , " -v " , " ON_ERROR_STOP=1 " , " -q " ] ,
input = f " ALTER ROLE { role } PASSWORD { sql_quote ( new [ ' db_password ' ] ) } ; \n " , quiet = True )
print ( f " ALTER ROLE { role } : old password no longer accepted for NEW connections " )
print ( f " { role } picks up version { ver } within SECRETS_REFRESH_SECONDS; open connections keep working " )
def cmd_rotate_cert ( args ) - > None :
ident = args [ 0 ] if args else " lb "
step ( f " Rotate leaf certificate of { ident } (new key + serial; images unchanged) " )
run ( C + [ " --profile " , " ops " , " run " , " --rm " , " pki " , " issue " , ident ] , capture = False )
reload_identity ( ident )
def reload_identity ( ident : str ) - > None :
if ident in ( " lb " , " otel-gw " ) :
run ( C + [ " kill " , " -s " , " USR2 " , ident ] ) # HAProxy master-worker: graceful reload
print ( f " { ident } : reloaded (new certificate/CRL for new connections) " )
elif ident in ( " api " , " worker " ) :
run ( C + [ " restart " , ident ] )
else :
run ( C + [ " restart " , ident ] )
def cmd_revoke_cert ( args ) - > None :
ident = args [ 0 ] if args else " lb "
step ( f " Revoke PREVIOUS certificate of { ident } (CRL → every identity dir) " )
run ( C + [ " --profile " , " ops " , " run " , " --rm " , " pki " , " revoke " , ident , " --previous " ] , capture = False )
run ( C + [ " kill " , " -s " , " USR2 " , " otel-gw " ] , check = False ) # HAProxy читает crl-file при reload
print ( " API reloads CRL automatically (TLS_CRL_RELOAD_SECONDS); otel-gw reloaded " )
COMMANDS = { " bootstrap " : cmd_bootstrap , " unseal " : cmd_unseal , " status " : cmd_status , " seal " : cmd_seal ,
" rotate-db-password " : cmd_rotate_db_password , " rotate-cert " : cmd_rotate_cert ,
" revoke-cert " : cmd_revoke_cert }
if __name__ == " __main__ " :
if len ( sys . argv ) < 2 or sys . argv [ 1 ] not in COMMANDS :
print ( __doc__ )
sys . exit ( 2 )
COMMANDS [ sys . argv [ 1 ] ] ( sys . argv [ 2 : ] )