117 lines
4.5 KiB
Python
117 lines
4.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Configure the local server as the operator; application containers never run this."""
|
|
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
import time
|
|
|
|
from app.config.bao import BaoClient, BaoError
|
|
from scripts.bootstrap import env_value, secrets_directory, write
|
|
|
|
|
|
ROLES = ('api', 'publisher', 'worker')
|
|
|
|
|
|
def bundle(role: str, passwords: dict[str, str]) -> dict[str, str]:
|
|
name = f'messenger_{role}'
|
|
result = {'DATABASE_URL': (
|
|
f'postgresql+asyncpg://{name}:{passwords["database"]}@postgres:5432/messenger'
|
|
)}
|
|
if 'redis' in passwords:
|
|
result['REDIS_URL'] = f'rediss://{name}:{passwords["redis"]}@redis:6379/0'
|
|
if 'broker' in passwords:
|
|
result['BROKER_URL'] = f'amqps://{name}:{passwords["broker"]}@broker:5671/'
|
|
if 's3' in passwords:
|
|
result.update(
|
|
S3_ACCESS_KEY_ID=f'messenger-{role}',
|
|
S3_SECRET_ACCESS_KEY=passwords['s3'],
|
|
)
|
|
return result
|
|
|
|
|
|
def seal_status(client: BaoClient) -> dict:
|
|
for attempt in range(30):
|
|
try:
|
|
return client.request('sys/seal-status')
|
|
except BaoError as error:
|
|
if error.status is not None or attempt == 29:
|
|
raise
|
|
time.sleep(1)
|
|
raise AssertionError('unreachable')
|
|
|
|
|
|
def provision(client: BaoClient, directory: Path) -> None:
|
|
operator = directory / 'operator'
|
|
recovery = operator / 'openbao-init.json'
|
|
status = seal_status(client)
|
|
if not status['initialized']:
|
|
if recovery.exists():
|
|
raise RuntimeError(
|
|
'OpenBao storage is empty but an operator recovery file already exists. '
|
|
'Restore the matching volume, or use a separate secrets directory for a new stand.'
|
|
)
|
|
init = client.request('sys/init', {'secret_shares': 3, 'secret_threshold': 2}, method='PUT')
|
|
write(recovery, json.dumps(init), 0o600)
|
|
if not recovery.is_file():
|
|
raise RuntimeError('Restore the original operator/openbao-init.json for this volume.')
|
|
state = json.loads(recovery.read_text(encoding='utf-8'))
|
|
if status['sealed']:
|
|
for key in state['keys_base64']:
|
|
result = client.request('sys/unseal', {'key': key}, method='PUT')
|
|
if not result['sealed']:
|
|
break
|
|
else:
|
|
raise RuntimeError('OpenBao remained sealed after trying the operator shares')
|
|
|
|
root = state['root_token']
|
|
if 'messenger/' not in client.request('sys/mounts', token=root):
|
|
client.request('sys/mounts/messenger', {'type': 'kv', 'options': {'version': '2'}}, token=root)
|
|
if 'cert/' not in client.request('sys/auth', token=root):
|
|
client.request('sys/auth/cert', {'type': 'cert'}, token=root)
|
|
credentials = json.loads((operator / 'credentials.json').read_text(encoding='utf-8'))
|
|
for role in ROLES:
|
|
policy = f'messenger-{role}'
|
|
client.request(f'sys/policies/acl/{policy}', {
|
|
'policy': (
|
|
f'path "messenger/data/{role}" {{ capabilities = ["read"] }}\n'
|
|
'path "auth/token/revoke-self" { capabilities = ["update"] }'
|
|
),
|
|
}, token=root)
|
|
certificate = (directory / policy / 'public.crt').read_text(encoding='utf-8')
|
|
client.request(f'auth/cert/certs/{role}', {
|
|
'certificate': certificate,
|
|
'token_policies': [policy],
|
|
'token_no_default_policy': True,
|
|
'token_ttl': 300,
|
|
'token_max_ttl': 300,
|
|
}, token=root)
|
|
secret = bundle(role, credentials[role])
|
|
try:
|
|
previous = client.read_service(role, root)
|
|
except BaoError as error:
|
|
if error.status != 404:
|
|
raise
|
|
previous = None
|
|
if previous != secret:
|
|
client.request(f'messenger/data/{role}', {'data': secret}, token=root)
|
|
print('OpenBao is unsealed and the three workload policies are configured.')
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--env-file', type=Path, default=Path('.env'))
|
|
parser.add_argument('--address')
|
|
args = parser.parse_args()
|
|
directory = secrets_directory(args.env_file)
|
|
try:
|
|
port = env_value(args.env_file, 'BAO_PORT', '8200')
|
|
address = args.address or f'https://localhost:{port}'
|
|
provision(BaoClient(address, directory / 'ca.crt'), directory)
|
|
except (BaoError, OSError, ValueError, RuntimeError) as error:
|
|
parser.exit(1, f'{error}\n')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|