forked from mtusi2026/mtusi2026lab7
158 lines
9.9 KiB
Python
158 lines
9.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Operator-only provisioning. Never emits secret values or passes them in argv."""
|
|
import fcntl, json, os, secrets, ssl, subprocess, sys, time, urllib.request, urllib.error
|
|
from pathlib import Path
|
|
ROOT=Path(__file__).resolve().parent.parent
|
|
os.chdir(ROOT)
|
|
os.umask(0o077)
|
|
DC=[str(ROOT/'scripts/dc.sh')]
|
|
OP=ROOT/'secrets/operator'
|
|
def run(*args, data=None):
|
|
p=subprocess.run(DC+list(args),input=data,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
|
|
if p.returncode:
|
|
raise RuntimeError('Compose operation failed: '+' '.join(args[:3])+' (details withheld to protect secrets)')
|
|
return p.stdout
|
|
|
|
def save(path,value):
|
|
path.parent.mkdir(parents=True,exist_ok=True)
|
|
path.write_text(value);path.chmod(0o600)
|
|
def secret(name):
|
|
path=OP/name
|
|
if not path.exists():save(path,secrets.token_hex(24))
|
|
return path.read_text().strip()
|
|
|
|
def prepare():
|
|
OP.mkdir(parents=True,exist_ok=True)
|
|
for name in ['db-password','minio-user','minio-password','grafana-password','redis-api','redis-worker','s3-api','s3-worker']:secret(name)
|
|
for name in ['postgres','redis','minio','openbao','grafana','prometheus','loki','tempo']:
|
|
(ROOT/'secrets/state'/name).mkdir(parents=True,exist_ok=True)
|
|
# Grafana datasource provisioning embeds public CA and this service's own private key
|
|
# in an ignored runtime file; provider expansion is not supported in datasource YAML.
|
|
source=next((ROOT/'infra/grafana/provisioning/datasources').glob('*'))
|
|
provisioning=json.loads(source.read_text())
|
|
for ds in provisioning['datasources']:
|
|
ds['secureJsonData']={'tlsCACert':(ROOT/'certs/ca.crt').read_text(),
|
|
'tlsClientCert':(ROOT/'certs/grafana/grafana.crt').read_text(),
|
|
'tlsClientKey':(ROOT/'certs/grafana/grafana.key').read_text()}
|
|
save(ROOT/'secrets/grafana-datasources/datasources.yaml',json.dumps(provisioning))
|
|
# Use current operator UID consistently; leaf keys remain 0600, not world-readable.
|
|
if not (ROOT/'.env').exists():
|
|
save(ROOT/'.env',f'LOCAL_UID={os.getuid()}\nLOCAL_GID={os.getgid()}\nHTTPS_PORT=8443\nBAO_PORT=8200\nGRAFANA_PORT=3000\n')
|
|
import hashlib
|
|
acl='user default off\n'
|
|
for role,commands,keys in [
|
|
('api','+ping +get +set +del +eval +incr +expire +xadd','~session:* ~ratelimit:login:* ~jobs:attachments'),
|
|
('worker','+ping (+xgroup +xreadgroup +xautoclaim +xack ~jobs:attachments) (+xadd ~jobs:attachments:dlq)','')]:
|
|
digest=hashlib.sha256(secret('redis-'+role).encode()).hexdigest()
|
|
acl+=f'user {role} on #{digest} {keys} -@all {commands}\n'
|
|
save(ROOT/'secrets/redis/users.acl',acl)
|
|
for role in ['api','worker']:(ROOT/'secrets/approle'/role).mkdir(parents=True,exist_ok=True)
|
|
|
|
OP.mkdir(parents=True,exist_ok=True)
|
|
bootstrap_lock=(OP/"bootstrap.lock").open("a")
|
|
fcntl.flock(bootstrap_lock,fcntl.LOCK_EX)
|
|
prepare()
|
|
if '--prepare' in sys.argv:
|
|
print('Local secret files prepared; .env contains only ports/UID/GID.');sys.exit(0)
|
|
run('up','-d','--wait','--wait-timeout','90','db','cache','minio','openbao')
|
|
# ACL file changes must become active even when the container already exists.
|
|
run('restart','cache')
|
|
ctx=ssl.create_default_context(cafile=str(ROOT/'certs/ca.crt'))
|
|
local_settings=dict(line.split('=',1) for line in (ROOT/'.env').read_text().splitlines() if '=' in line and not line.startswith('#'))
|
|
addr='https://localhost:'+os.environ.get('BAO_PORT',local_settings.get('BAO_PORT','8200'))
|
|
token=None
|
|
|
|
def req(path,body=None):
|
|
headers={'Content-Type':'application/json'}
|
|
if token:headers['X-Vault-Token']=token
|
|
request=urllib.request.Request(addr+'/v1/'+path,data=None if body is None else json.dumps(body).encode(),headers=headers)
|
|
with urllib.request.urlopen(request,context=ctx,timeout=10) as r:
|
|
b=r.read();return json.loads(b) if b else {}
|
|
for _ in range(90):
|
|
try:
|
|
state=req('sys/seal-status');break
|
|
except (OSError,urllib.error.URLError):time.sleep(1)
|
|
else:raise RuntimeError('OpenBao TLS listener did not start')
|
|
initfile=OP/'bao-init.json'
|
|
if not state['initialized']:
|
|
# init output is captured only in the operator's private file.
|
|
save(initfile,run('exec','-T','openbao','bao','operator','init','-key-shares=1','-key-threshold=1','-format=json'))
|
|
init=json.loads(initfile.read_text())
|
|
if state['sealed']:req('sys/unseal',{'key':init['unseal_keys_b64'][0]})
|
|
token=init['root_token']
|
|
# Audit record payloads are HMACed by default; no raw secrets.
|
|
if 'file/' not in req('sys/audit'):
|
|
req('sys/audit/file',{'type':'file','options':{'file_path':'/bao/data/audit.json'}})
|
|
# Migrations run over operator-local Unix socket, never with application credentials.
|
|
sql="CREATE TABLE IF NOT EXISTS schema_migrations(version int PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now());"
|
|
run('exec','-T','db','psql','-U','postgres','-d','messenger','-v','ON_ERROR_STOP=1',data=sql)
|
|
applied=set(run('exec','-T','db','psql','-U','postgres','-d','messenger','-Atc','SELECT version FROM schema_migrations').split())
|
|
for p in sorted((ROOT/'migrations').glob('*.sql')):
|
|
version=int(p.name.split('_')[0])
|
|
if str(version) not in applied:
|
|
run('exec','-T','db','psql','-U','postgres','-d','messenger','-v','ON_ERROR_STOP=1',data='BEGIN;\n'+p.read_text()+f'\nINSERT INTO schema_migrations(version) VALUES({version});COMMIT;')
|
|
roles_sql="""
|
|
DO $$ BEGIN
|
|
IF NOT EXISTS(SELECT FROM pg_roles WHERE rolname='api_access') THEN CREATE ROLE api_access NOLOGIN; END IF;
|
|
IF NOT EXISTS(SELECT FROM pg_roles WHERE rolname='worker_access') THEN CREATE ROLE worker_access NOLOGIN; END IF;
|
|
END $$;
|
|
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
|
|
GRANT USAGE ON SCHEMA public TO api_access,worker_access;
|
|
GRANT SELECT,INSERT,UPDATE,DELETE ON ALL TABLES IN SCHEMA public TO api_access;
|
|
GRANT USAGE,SELECT ON ALL SEQUENCES IN SCHEMA public TO api_access;
|
|
REVOKE ALL ON schema_migrations FROM api_access;
|
|
GRANT SELECT,UPDATE ON attachments,jobs TO worker_access;
|
|
GRANT SELECT,INSERT,UPDATE ON attachment_results TO worker_access;
|
|
GRANT SELECT ON direct_uploads,outbox TO worker_access;
|
|
"""
|
|
run('exec','-T','db','psql','-U','postgres','-d','messenger','-v','ON_ERROR_STOP=1',data=roles_sql)
|
|
mounts=req('sys/mounts')
|
|
for name,typ in [('database','database'),('secret','kv')]:
|
|
if name+'/' not in mounts:req('sys/mounts/'+name,{'type':typ,**({'options':{'version':'2'}} if typ=='kv' else {})})
|
|
# OpenBao DB manager bootstraps using postgres; its secret is held only by the operator/Bao.
|
|
req('database/config/messenger',{'plugin_name':'postgresql-database-plugin','allowed_roles':['api-role','worker-role'],
|
|
'connection_url':'postgresql://{{username}}:{{password}}@db:5432/messenger?sslmode=verify-full&sslrootcert=/pki/ca.crt&sslcert=/identity/openbao.crt&sslkey=/identity/openbao.key',
|
|
'username':'postgres','password':secret('db-password')})
|
|
if 'approle/' not in req('sys/auth'):req('sys/auth/approle',{'type':'approle'})
|
|
for role in ['api','worker']:
|
|
creation=f'''CREATE ROLE "{{{{name}}}}" WITH LOGIN PASSWORD '{{{{password}}}}' VALID UNTIL '{{{{expiration}}}}' IN ROLE {role}_access;'''
|
|
req('database/roles/'+role+'-role',{'db_name':'messenger','creation_statements':[creation],
|
|
'revocation_statements':['''SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='{{name}}'; DROP ROLE IF EXISTS "{{name}}";'''],
|
|
'default_ttl':'15m','max_ttl':'1h'})
|
|
policy=f'''path "database/creds/{role}-role" {{ capabilities=["read"] }}
|
|
path "secret/data/{role}" {{ capabilities=["read"] }}
|
|
path "sys/leases/renew" {{ capabilities=["update"] }}
|
|
path "auth/token/renew-self" {{ capabilities=["update"] }}
|
|
path "auth/token/revoke-self" {{ capabilities=["update"] }}
|
|
'''
|
|
(ROOT/'infra/openbao'/f'{role}.hcl').write_text(policy)
|
|
req('sys/policies/acl/'+role,{'policy':policy})
|
|
req('auth/approle/role/'+role,{'token_policies':[role],'token_no_default_policy':True,
|
|
'token_ttl':'15m','token_max_ttl':'1h','secret_id_ttl':'24h','secret_id_num_uses':0})
|
|
previous=ROOT/'secrets/approle'/role/'secret-id'
|
|
if previous.exists():
|
|
try:req('auth/approle/role/'+role+'/secret-id/destroy',{'secret_id':previous.read_text()})
|
|
except urllib.error.HTTPError as e:
|
|
if e.code != 404:raise
|
|
save(ROOT/'secrets/approle'/role/'role-id',req('auth/approle/role/'+role+'/role-id')['data']['role_id'])
|
|
save(ROOT/'secrets/approle'/role/'secret-id',req('auth/approle/role/'+role+'/secret-id',{})['data']['secret_id'])
|
|
req('secret/data/'+role,{'data':{'redis_url':f'rediss://{role}:{secret("redis-"+role)}@redis:6379/0',
|
|
's3_access_key':'messenger-'+role,'s3_secret_key':secret('s3-'+role)}})
|
|
# mc configuration and credentials live exclusively in its ephemeral /tmp.
|
|
script='''set -eu
|
|
mc alias set local https://minio:9000 "$(cat /operator/minio-user)" "$(cat /operator/minio-password)" >/dev/null
|
|
mc mb --ignore-existing local/attachments >/dev/null
|
|
mc anonymous set none local/attachments >/dev/null
|
|
'''
|
|
for role in ['api','worker']:
|
|
# Track 2 chosen: worker needs all staging objects for lab6 processing and cleanup.
|
|
actions=['s3:GetObject','s3:PutObject','s3:DeleteObject','s3:AbortMultipartUpload','s3:ListMultipartUploadParts']
|
|
policy={'Version':'2012-10-17','Statement':[{'Effect':'Allow','Action':['s3:GetBucketLocation','s3:ListBucket'],'Resource':['arn:aws:s3:::attachments']},{'Effect':'Allow','Action':actions,'Resource':['arn:aws:s3:::attachments/staging/*','arn:aws:s3:::attachments/attachments/*']}]}
|
|
script+=f"cat > /tmp/{role}.json <<'POLICY'\n{json.dumps(policy)}\nPOLICY\n"
|
|
script+=f'mc admin user add local messenger-{role} "$(cat /operator/s3-{role})" >/dev/null\n'
|
|
script+=f'mc admin policy create local {role} /tmp/{role}.json >/dev/null\n'
|
|
script+=f'mc admin policy attach local {role} --user messenger-{role} >/dev/null\n'
|
|
run('run','--rm','-T','mc','-s',data=script)
|
|
print('OpenBao initialized/unsealed, database roles, scoped AppRoles, S3 policies provisioned. No secret values printed.')
|
|
print('Protect secrets/operator/bao-init.json: lab auto-unseal uses it; production requires offline custody/external unseal.')
|