Реализовать ЛР 7 на оценку 3
This commit is contained in:
@@ -0,0 +1,303 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare the local Lab 7 CA, workload identities and initial credentials."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shlex
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LOOPBACK = 'DNS:localhost,IP:127.0.0.1'
|
||||
HOSTS = {
|
||||
'ingress': ('serverAuth', LOOPBACK),
|
||||
'api': ('serverAuth', 'DNS:api'),
|
||||
'lb': ('clientAuth', 'DNS:lb'),
|
||||
'postgres': ('serverAuth', 'DNS:postgres'),
|
||||
'redis': ('serverAuth', 'DNS:redis'),
|
||||
'broker': ('serverAuth', 'DNS:broker'),
|
||||
's3': ('serverAuth', 'DNS:s3'),
|
||||
'otel-collector': ('serverAuth', 'DNS:otel-collector'),
|
||||
'prometheus': ('serverAuth', 'DNS:prometheus'),
|
||||
'loki': ('serverAuth', 'DNS:loki'),
|
||||
'tempo': ('serverAuth', 'DNS:tempo'),
|
||||
'grafana': ('serverAuth', f'DNS:grafana,{LOOPBACK}'),
|
||||
'openbao': ('serverAuth', f'DNS:openbao,{LOOPBACK}'),
|
||||
**{
|
||||
name: ('clientAuth', f'DNS:{name}')
|
||||
for name in ('messenger-api', 'messenger-publisher', 'messenger-worker',
|
||||
'telemetry-export', 'telemetry-query', 'telemetry-scrape')
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def openssl(directory: Path, *arguments: str) -> None:
|
||||
subprocess.run(
|
||||
['openssl', *arguments], cwd=directory, check=True, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
|
||||
|
||||
def write(path: Path, value: str, mode: int = 0o444) -> None:
|
||||
if path.is_file() and path.read_text(encoding='utf-8') == value:
|
||||
path.chmod(mode)
|
||||
return
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode='w', encoding='utf-8', dir=path.parent, prefix='.bootstrap-', delete=False
|
||||
) as fp:
|
||||
fp.write(value)
|
||||
temporary = Path(fp.name)
|
||||
try:
|
||||
temporary.chmod(mode)
|
||||
temporary.replace(path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def read_or_create(path: Path, default: str) -> str:
|
||||
if not path.is_file():
|
||||
write(path, default)
|
||||
return path.read_text(encoding='utf-8').strip()
|
||||
|
||||
|
||||
def create_ca(directory: Path) -> None:
|
||||
with tempfile.TemporaryDirectory(prefix='.bootstrap-', dir=directory) as temporary:
|
||||
source = Path(temporary)
|
||||
openssl(
|
||||
source, 'req', '-x509', '-newkey', 'rsa:3072', '-nodes', '-sha256',
|
||||
'-days', '365', '-subj', '/CN=Messenger Lab 7 Local CA',
|
||||
'-addext', 'basicConstraints=critical,CA:TRUE,pathlen:0',
|
||||
'-addext', 'keyUsage=critical,keyCertSign,cRLSign',
|
||||
'-keyout', 'ca.key', '-out', 'ca.crt',
|
||||
)
|
||||
write(directory / 'ca.key', (source / 'ca.key').read_text(), 0o600)
|
||||
write(directory / 'ca.crt', (source / 'ca.crt').read_text())
|
||||
|
||||
|
||||
def create_certificates(directory: Path) -> None:
|
||||
have_ca = (directory / 'ca.key').is_file(), (directory / 'ca.crt').is_file()
|
||||
if have_ca[0] != have_ca[1]:
|
||||
raise ValueError('Восстановите отсутствующий файл существующего CA.')
|
||||
if not all(have_ca):
|
||||
create_ca(directory)
|
||||
for host, (purpose, san) in HOSTS.items():
|
||||
pair = directory / host
|
||||
pair.mkdir(exist_ok=True)
|
||||
pair.chmod(0o755)
|
||||
key = pair / 'private.key'
|
||||
cert = pair / 'public.crt'
|
||||
if not key.is_file() or not cert.is_file():
|
||||
with tempfile.TemporaryDirectory(prefix='.bootstrap-', dir=directory) as temporary:
|
||||
source = Path(temporary)
|
||||
openssl(
|
||||
source, 'req', '-new', '-newkey', 'rsa:2048', '-nodes', '-sha256',
|
||||
'-subj', f'/CN={host}', '-keyout', 'private.key', '-out', 'leaf.csr',
|
||||
)
|
||||
(source / 'leaf.ext').write_text(
|
||||
'basicConstraints=critical,CA:FALSE\n'
|
||||
'keyUsage=critical,digitalSignature,keyEncipherment\n'
|
||||
f'extendedKeyUsage={purpose}\nsubjectAltName={san}\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
openssl(
|
||||
source, 'x509', '-req', '-in', 'leaf.csr', '-CA', str(directory / 'ca.crt'),
|
||||
'-CAkey', str(directory / 'ca.key'), '-set_serial', f'0x01{secrets.token_hex(15)}',
|
||||
'-days', '90', '-sha256', '-extfile', 'leaf.ext', '-out', 'public.crt',
|
||||
)
|
||||
write(key, (source / 'private.key').read_text())
|
||||
write(cert, (source / 'public.crt').read_text())
|
||||
if host in {'ingress', 'lb', 'otel-collector', 'prometheus', 'loki', 'tempo'}:
|
||||
write(directory / f'{host}.pem', cert.read_text() + key.read_text())
|
||||
(directory / 's3' / 'CAs').mkdir(mode=0o755, exist_ok=True)
|
||||
|
||||
|
||||
def create_foreign_test_identity(directory: Path) -> None:
|
||||
output = directory / 'foreign-client'
|
||||
output.mkdir(exist_ok=True)
|
||||
output.chmod(0o755)
|
||||
if (output / 'public.crt').is_file() and (output / 'private.key').is_file():
|
||||
return
|
||||
with tempfile.TemporaryDirectory(prefix='.bootstrap-', dir=directory) as temporary:
|
||||
source = Path(temporary)
|
||||
openssl(
|
||||
source, 'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-sha256',
|
||||
'-days', '7', '-subj', '/CN=Lab 7 foreign client',
|
||||
'-addext', 'extendedKeyUsage=clientAuth',
|
||||
'-keyout', 'private.key', '-out', 'public.crt',
|
||||
)
|
||||
for name in ('private.key', 'public.crt'):
|
||||
write(output / name, (source / name).read_text())
|
||||
|
||||
|
||||
def create_credentials(directory: Path) -> None:
|
||||
postgres_password = read_or_create(directory / 'postgres_password', secrets.token_hex(24))
|
||||
write(directory / 'database_url',
|
||||
f'postgresql+asyncpg://messenger:{postgres_password}@postgres:5432/messenger')
|
||||
read_or_create(directory / 's3_root_user', 'messenger-admin')
|
||||
read_or_create(directory / 's3_root_password', secrets.token_hex(24))
|
||||
read_or_create(directory / 'grafana_admin_password', secrets.token_hex(24))
|
||||
|
||||
operator = directory / 'operator'
|
||||
operator.mkdir(mode=0o700, exist_ok=True)
|
||||
role_file = operator / 'credentials.json'
|
||||
if role_file.is_file():
|
||||
passwords = json.loads(role_file.read_text(encoding='utf-8'))
|
||||
else:
|
||||
passwords = {
|
||||
role: {component: secrets.token_hex(24) for component in components}
|
||||
for role, components in (
|
||||
('api', ('database', 'redis', 's3')),
|
||||
('publisher', ('database', 'broker')),
|
||||
('worker', ('database', 'broker', 's3')),
|
||||
)
|
||||
}
|
||||
for role in ('publisher', 'worker'):
|
||||
credentials = passwords[role]
|
||||
if 'broker_salt' not in credentials:
|
||||
credentials['broker_salt'] = secrets.token_hex(4)
|
||||
write(role_file, json.dumps(passwords), 0o600)
|
||||
|
||||
roles = []
|
||||
for role, credentials in passwords.items():
|
||||
name = f'messenger_{role}'
|
||||
password = credentials['database']
|
||||
roles.append(f"""DO $role$ BEGIN
|
||||
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '{name}') THEN
|
||||
CREATE ROLE {name} LOGIN;
|
||||
END IF;
|
||||
END $role$;
|
||||
ALTER ROLE {name} PASSWORD '{password}';
|
||||
""")
|
||||
if 's3' in credentials:
|
||||
write(directory / f's3_{role}_secret', credentials['s3'])
|
||||
write(directory / 'postgres_roles.sql', ''.join(roles))
|
||||
|
||||
redis_password = passwords['api']['redis']
|
||||
write(directory / 'redis_api_password', redis_password)
|
||||
write(directory / 'redis-lab.conf', f'''port 0
|
||||
tls-port 6379
|
||||
tls-cert-file /run/tls/public.crt
|
||||
tls-key-file /run/tls/private.key
|
||||
tls-ca-cert-file /run/secrets/lab_ca
|
||||
tls-auth-clients no
|
||||
user default off
|
||||
user messenger_api on >{redis_password} ~session:* ~login:* +ping +get +set +del +eval +incr +expire +ttl +client|setinfo
|
||||
appendonly yes
|
||||
appendfsync always
|
||||
''')
|
||||
|
||||
write(directory / 'rabbitmq-lab.conf', '''listeners.tcp = none
|
||||
distribution.listener.interface = 127.0.0.1
|
||||
listeners.ssl.default = 5671
|
||||
ssl_options.cacertfile = /run/secrets/lab_ca
|
||||
ssl_options.certfile = /run/tls/public.crt
|
||||
ssl_options.keyfile = /run/tls/private.key
|
||||
ssl_options.verify = verify_none
|
||||
ssl_options.fail_if_no_peer_cert = false
|
||||
definitions.import_backend = local_filesystem
|
||||
definitions.local.path = /run/secrets/broker_definitions
|
||||
''')
|
||||
definitions_path = directory / 'rabbitmq-definitions.json'
|
||||
def broker_user(role: str) -> dict:
|
||||
salt = bytes.fromhex(passwords[role]['broker_salt'])
|
||||
digest = hashlib.sha256(salt + passwords[role]['broker'].encode()).digest()
|
||||
return {
|
||||
'name': f'messenger_{role}',
|
||||
'password_hash': base64.b64encode(salt + digest).decode(),
|
||||
'hashing_algorithm': 'rabbit_password_hashing_sha256',
|
||||
'tags': [],
|
||||
}
|
||||
|
||||
definitions = {
|
||||
'vhosts': [{'name': '/'}],
|
||||
'users': [broker_user(role) for role in ('publisher', 'worker')],
|
||||
'permissions': [
|
||||
{'user': 'messenger_publisher', 'vhost': '/', 'configure': '^$',
|
||||
'write': '^attachments$', 'read': '^$'},
|
||||
{'user': 'messenger_worker', 'vhost': '/', 'configure': '^$',
|
||||
'write': '^$', 'read': r'^attachments\.process$'},
|
||||
],
|
||||
'exchanges': [
|
||||
{'name': name, 'vhost': '/', 'type': 'direct', 'durable': True,
|
||||
'auto_delete': False, 'internal': False, 'arguments': {}}
|
||||
for name in ('attachments', 'attachments.dead')
|
||||
],
|
||||
'queues': [
|
||||
{'name': 'attachments.process', 'vhost': '/', 'durable': True, 'auto_delete': False,
|
||||
'arguments': {'x-dead-letter-exchange': 'attachments.dead',
|
||||
'x-dead-letter-routing-key': 'attachment.process.v1'}},
|
||||
{'name': 'attachments.failed', 'vhost': '/', 'durable': True, 'auto_delete': False,
|
||||
'arguments': {}},
|
||||
],
|
||||
'bindings': [
|
||||
{'source': exchange, 'destination': queue, 'destination_type': 'queue', 'vhost': '/',
|
||||
'routing_key': 'attachment.process.v1', 'arguments': {}}
|
||||
for exchange, queue in (
|
||||
('attachments', 'attachments.process'), ('attachments.dead', 'attachments.failed')
|
||||
)
|
||||
],
|
||||
}
|
||||
write(definitions_path, json.dumps(definitions))
|
||||
|
||||
|
||||
def env_value(env_file: Path, name: str, default: str) -> str:
|
||||
value = os.environ.get(name)
|
||||
if value:
|
||||
return value
|
||||
if env_file.is_file():
|
||||
for line in env_file.read_text(encoding='utf-8').splitlines():
|
||||
key, separator, value = line.partition('=')
|
||||
if separator and key.strip() == name:
|
||||
parts = shlex.split(value, comments=True)
|
||||
if len(parts) != 1:
|
||||
raise ValueError(f'{env_file}: expected a value for {name}')
|
||||
return parts[0]
|
||||
return default
|
||||
|
||||
|
||||
def secrets_directory(env_file: Path) -> Path:
|
||||
return (ROOT / env_value(env_file, 'LAB_SECRETS_DIR', 'secrets')).resolve()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--env-file', type=Path, default=ROOT / '.env')
|
||||
parser.add_argument('--secrets-dir', type=Path)
|
||||
parser.add_argument('--test-fixtures', action='store_true')
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
directory = (args.secrets_dir or secrets_directory(args.env_file)).resolve()
|
||||
if directory.is_relative_to(ROOT) and not directory.is_relative_to(ROOT / 'secrets'):
|
||||
parser.error('Каталог секретов внутри проекта должен находиться в secrets/.')
|
||||
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
directory.chmod(0o700)
|
||||
create_credentials(directory)
|
||||
create_certificates(directory)
|
||||
if args.test_fixtures:
|
||||
create_foreign_test_identity(directory)
|
||||
except ValueError as error:
|
||||
parser.error(str(error))
|
||||
except FileNotFoundError as error:
|
||||
parser.exit(1, f'Отсутствует инструмент или файл: {error.filename}\n')
|
||||
except subprocess.CalledProcessError as error:
|
||||
parser.exit(1, f'OpenSSL: {error.stderr.decode().strip()}\n')
|
||||
|
||||
if not args.env_file.exists():
|
||||
template = (ROOT / '.env.example').read_text(encoding='utf-8')
|
||||
if directory != ROOT / 'secrets':
|
||||
template = template.replace('LAB_SECRETS_DIR=./secrets', f"LAB_SECRETS_DIR='{directory}'")
|
||||
args.env_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with args.env_file.open('x', encoding='utf-8') as target:
|
||||
target.write(template)
|
||||
print(f'Локальная конфигурация: {args.env_file}; CA: {directory / "ca.crt"}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,116 @@
|
||||
#!/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()
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
compose() {
|
||||
docker compose --env-file "${COMPOSE_ENV_FILE:-.env}" "$@"
|
||||
}
|
||||
|
||||
compose stop --timeout 8 lb api publisher worker
|
||||
compose restart postgres redis broker s3 openbao
|
||||
"${PYTHON:-python3}" -m scripts.provision_openbao --env-file "${COMPOSE_ENV_FILE:-.env}"
|
||||
compose up -d --wait --wait-timeout 45 postgres redis broker s3
|
||||
compose up -d --wait --wait-timeout 35 --no-deps api publisher worker lb
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?Set TARGET_INSTANCE_ID to the API replica alias}"
|
||||
containers=$(docker compose --env-file "${COMPOSE_ENV_FILE:-.env}" ps -q api)
|
||||
for container in $containers; do
|
||||
if [ "$(docker exec "$container" cat /tmp/lab-instance-id)" = "$TARGET_INSTANCE_ID" ]; then
|
||||
docker stop -t 3 "$container"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
|
||||
echo "API replica $TARGET_INSTANCE_ID is not running in this project" >&2
|
||||
exit 1
|
||||
Reference in New Issue
Block a user