forked from mtusi2026/mtusi2026lab7
Лабораторная 7
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit operator init/unseal/configure. Operator material never mounted in apps."""
|
||||
import json,os,ssl,sys,urllib.request,urllib.error
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1];os.chdir(ROOT);os.umask(0o077)
|
||||
BASE=Path('secrets');local=dict(line.split('=',1) for line in Path('.env').read_text().splitlines() if '=' in line and not line.startswith('#'))
|
||||
ADDR=os.environ.get('BAO_OPERATOR_ADDR','https://localhost:'+os.environ.get('BAO_PORT',local.get('BAO_PORT','18200')))
|
||||
ctx=ssl.create_default_context(cafile=str(BASE/'public/ca.crt'))
|
||||
def call(method,path,data=None,token=None):
|
||||
req=urllib.request.Request(ADDR+'/v1/'+path,data=None if data is None else json.dumps(data).encode(),method=method,headers={'Content-Type':'application/json',**({'X-Vault-Token':token} if token else {})})
|
||||
with urllib.request.urlopen(req,context=ctx,timeout=10) as r:return json.load(r) if r.status!=204 else {}
|
||||
def main():
|
||||
mode=sys.argv[1] if len(sys.argv)>1 else ''
|
||||
if mode not in ('init','unseal','configure','seal','wait'):raise SystemExit('usage: bao-operator.py init|unseal|configure|seal')
|
||||
if mode=='wait':
|
||||
import time
|
||||
for _ in range(60):
|
||||
try:call('GET','sys/init');return
|
||||
except OSError:time.sleep(.5)
|
||||
raise SystemExit('OpenBao listener unavailable')
|
||||
f=BASE/'operator/bao-init.json'
|
||||
if mode=='init' and not f.exists():
|
||||
if call('GET','sys/init')['initialized']:raise SystemExit('Already initialized: restore operator init file, never reinitialize persistent storage.')
|
||||
f.write_text(json.dumps(call('PUT','sys/init',{'secret_shares':1,'secret_threshold':1})))
|
||||
state=json.loads(f.read_text());token=state['root_token']
|
||||
if mode=='seal':call('PUT','sys/seal',{},token);print('OpenBao sealed.');return
|
||||
if mode in ('init','unseal'):
|
||||
call('PUT','sys/unseal',{'key':state['keys'][0]})
|
||||
if mode in ('init','configure'):
|
||||
mounts=call('GET','sys/mounts',token=token)
|
||||
if 'secret/' not in mounts:call('POST','sys/mounts/secret',{'type':'kv','options':{'version':'1'}},token)
|
||||
auth=call('GET','sys/auth',token=token)
|
||||
if 'cert/' not in auth:call('POST','sys/auth/cert',{'type':'cert'},token)
|
||||
for role,values in json.loads((BASE/'operator/service-secrets.json').read_text()).items():
|
||||
policy=(ROOT/'infra/security/policies'/f'{role}.hcl').read_text()
|
||||
call('PUT','sys/policies/acl/'+role,{'policy':policy},token)
|
||||
# Bind exact leaf, not whole CA: rotation can revoke old auth by replacing cert.
|
||||
cert=(BASE/'tls'/role/'cert.crt').read_text()
|
||||
call('POST','auth/cert/certs/'+role,{'certificate':cert,'allowed_dns_sans':[role],'token_policies':[role],'token_ttl':60,'token_max_ttl':120,'token_no_default_policy':True},token)
|
||||
call('POST','secret/'+role,values,token)
|
||||
print('OpenBao operator action complete; no secret values displayed.')
|
||||
if __name__=='__main__':
|
||||
try:main()
|
||||
except (urllib.error.URLError,KeyError,OSError) as e:raise SystemExit('Operator action failed; check OpenBao readiness and local operator files.') from None
|
||||
Reference in New Issue
Block a user