forked from mtusi2026/mtusi2026lab7
all for 3
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
"""Prepare a new lab in a Linux filesystem (WSL supported). Never overwrite a CA."""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
os.chdir(ROOT)
|
||||
os.umask(0o077)
|
||||
if Path('.local').exists():
|
||||
raise SystemExit('Existing .local: bootstrap is for a fresh installation.')
|
||||
operator = Path(os.environ['LAB7_OPERATOR_DIR']).expanduser().resolve()
|
||||
if operator.is_relative_to(ROOT):
|
||||
raise SystemExit('Keep the operator directory outside the repository.')
|
||||
operator.mkdir(mode=0o700, parents=True, exist_ok=False)
|
||||
local = Path('.local')
|
||||
local.mkdir()
|
||||
def openssl(*args):
|
||||
subprocess.run(['openssl', *map(str,args)],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE)
|
||||
def write(path, content, public=False):
|
||||
path = Path(path)
|
||||
path.write_text(content)
|
||||
if public:
|
||||
path.chmod(0o444)
|
||||
ca = local/'ca.crt'
|
||||
key = operator/'ca.key'
|
||||
openssl('req','-x509','-newkey','ec','-pkeyopt','ec_paramgen_curve:P-256','-nodes','-keyout',key,
|
||||
'-out',ca,'-days','365','-subj','/CN=Messenger Lab7 CA','-addext','basicConstraints=critical,CA:TRUE',
|
||||
'-addext','keyUsage=critical,keyCertSign,cRLSign')
|
||||
ca.chmod(0o444)
|
||||
roles = ['lb','api','worker','openbao','postgres','redis','rabbitmq','minio','otel-collector','prometheus','loki','tempo','grafana']
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for role in roles:
|
||||
d = local/'id'/role
|
||||
d.mkdir(parents=True)
|
||||
names = [role,role+'-tls']
|
||||
if role in ['lb','openbao','grafana']:
|
||||
names.append('localhost')
|
||||
ext = Path(tmp)/'ext'
|
||||
write(ext,'basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName='+','.join('DNS:'+n for n in names)+'\n')
|
||||
csr = Path(tmp)/'leaf.csr'
|
||||
openssl('req','-new','-newkey','ec','-pkeyopt','ec_paramgen_curve:P-256','-nodes','-keyout',d/'key.pem','-subj','/CN='+role,'-out',csr)
|
||||
openssl('x509','-req','-in',csr,'-CA',ca,'-CAkey',key,'-set_serial',str(secrets.randbits(150)+1),'-days','30','-extfile',ext,'-out',d/'cert.pem')
|
||||
shutil.copyfile(ca,d/'ca.crt')
|
||||
write(d/'bundle.pem',(d/'cert.pem').read_text()+(d/'key.pem').read_text())
|
||||
# Bind only this subdirectory into its own identity's containers.
|
||||
d.chmod(0o555)
|
||||
for f in d.iterdir():
|
||||
f.chmod(0o444)
|
||||
env = {'POSTGRES_DB':'messenger','POSTGRES_USER':'operator','MINIO_ROOT_USER':'operator_s3','S3_BUCKET':'messenger-attachments','S3_ACCESS_KEY':'messenger_api'}
|
||||
password_keys = ('POSTGRES_PASSWORD','MINIO_ROOT_PASSWORD','S3_SECRET_KEY','WORKER_S3_PASSWORD','GRAFANA_PASSWORD')
|
||||
if Path('.env').exists():
|
||||
supplied = dict(line.split('=',1) for line in Path('.env').read_text().splitlines() if line.strip() and not line.startswith('#'))
|
||||
if any(supplied.get(k) != v for k,v in env.items()) or any(not supplied.get(k) for k in password_keys):
|
||||
raise SystemExit('Missing or incompatible .env values')
|
||||
env.update(supplied)
|
||||
else:
|
||||
for k in password_keys:
|
||||
env[k] = secrets.token_hex(24)
|
||||
write('.env',''.join(k+'='+v+'\n' for k,v in env.items()))
|
||||
redis = secrets.token_hex(24)
|
||||
write(local/'redis.acl','user default off\nuser api on #'+hashlib.sha256(redis.encode()).hexdigest()+' ~session:* +get +set +psetex +setex +del +ping +hello +client|setname +client|setinfo +select\n',True)
|
||||
sql = []
|
||||
defs = {'vhosts':[{'name':'/'}],'users':[],'permissions':[],'queues':[]}
|
||||
for name in ['attachments.v1','attachments.v1.dlq']:
|
||||
args = {'x-dead-letter-exchange':'','x-dead-letter-routing-key':'attachments.v1.dlq'} if not name.endswith('dlq') else {}
|
||||
defs['queues'].append(dict(name=name,vhost='/',durable=True,auto_delete=False,arguments=args))
|
||||
for role in ('api','worker'):
|
||||
db,broker = secrets.token_hex(24),secrets.token_hex(24)
|
||||
value=dict(DB_USERNAME=role, DB_PASSWORD=db, RABBITMQ_USER=role,RABBITMQ_PASSWORD=broker,
|
||||
S3_ACCESS_KEY='messenger_'+role,S3_SECRET_KEY=env['S3_SECRET_KEY' if role=='api' else 'WORKER_S3_PASSWORD'])
|
||||
if role=='api':
|
||||
value.update(REDIS_PASSWORD=redis,SPRING_DATA_REDIS_USERNAME='api')
|
||||
write(local/(role+'.json'), json.dumps(value))
|
||||
sql.append(f"CREATE ROLE {role} LOGIN PASSWORD '{db}';")
|
||||
salt=secrets.token_bytes(4)
|
||||
defs['users'].append(dict(name=role,tags=[],hashing_algorithm='rabbit_password_hashing_sha256',
|
||||
password_hash=base64.b64encode(salt+hashlib.sha256(salt+broker.encode()).digest()).decode()))
|
||||
defs['permissions'].append(dict(user=role,vhost='/',configure='^$',write='^amq[.]default$' if role=='api' else '^$',read='^attachments[.]v1$' if role=='worker' else '^$'))
|
||||
write(local/'roles.sql','\n'.join(sql)+'\n',True)
|
||||
write(local/'rabbit.json',json.dumps(defs),True)
|
||||
print('Generated identities and secrets. Start OpenBao, then initialize and unseal it.')
|
||||
foreign=local/'id/foreign'
|
||||
foreign.mkdir()
|
||||
openssl('req','-x509','-newkey','ec','-pkeyopt','ec_paramgen_curve:P-256','-nodes',
|
||||
'-keyout',foreign/'key.pem','-out',foreign/'cert.pem','-days','2','-subj','/CN=lb')
|
||||
for f in foreign.iterdir():
|
||||
f.chmod(0o444)
|
||||
foreign.chmod(0o555)
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Check generated identities and explicit trust boundaries without a running stack."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
ca=root/'.local/ca.crt'
|
||||
def verify(role,host,allowed=True):
|
||||
cert=root/'.local/id'/role/'cert.pem'
|
||||
p=subprocess.run(['openssl','verify','-CAfile',str(ca),'-verify_hostname',host,str(cert)],capture_output=True)
|
||||
if (p.returncode==0)!=allowed:
|
||||
raise SystemExit(f'Unexpected certificate result for {role} / {host}')
|
||||
for d in sorted((root/'.local/id').iterdir()):
|
||||
if d.name!='foreign':
|
||||
verify(d.name,d.name)
|
||||
verify('lb','localhost')
|
||||
verify('openbao','localhost')
|
||||
verify('grafana','localhost')
|
||||
verify('lb','wrong.invalid',False)
|
||||
verify('foreign','lb',False)
|
||||
print('PASS: generated service SANs, local ingress/admin hostnames, foreign issuer and hostname mismatch')
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Operator-only, repeatable configuration. Reads root token from a hidden prompt."""
|
||||
import getpass
|
||||
import json
|
||||
import ssl
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
ctx = ssl.create_default_context(cafile=root/'.local/ca.crt')
|
||||
token = getpass.getpass('OpenBao operator token: ')
|
||||
def request(path, body=None):
|
||||
req = urllib.request.Request('https://localhost:8200/v1/'+path,
|
||||
data=json.dumps(body).encode() if body is not None else None,
|
||||
headers={'X-Vault-Token':token,'Content-Type':'application/json'})
|
||||
with urllib.request.urlopen(req,context=ctx,timeout=10) as res:
|
||||
data = res.read()
|
||||
return json.loads(data) if data else {}
|
||||
if 'messenger/' not in request('sys/mounts')['data']:
|
||||
request('sys/mounts/messenger',{'type':'kv','options':{'version':'2'}})
|
||||
if 'cert/' not in request('sys/auth')['data']:
|
||||
request('sys/auth/cert',{'type':'cert'})
|
||||
for role in ['api','worker']:
|
||||
policy = 'messenger-'+role
|
||||
request('sys/policies/acl/'+policy,{'policy':'path "messenger/data/'+role+'" { capabilities = ["read"] }'})
|
||||
request('auth/cert/certs/'+role,{'certificate':(root/'.local/id'/role/'cert.pem').read_text(),
|
||||
'allowed_dns_sans':[role],'token_policies':[policy],'token_ttl':'2m','token_max_ttl':'5m'})
|
||||
request('messenger/data/'+role,{'data':json.loads((root/'.local'/(role+'.json')).read_text())})
|
||||
print('Configured API and worker certificate roles, policies and KV records.')
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
# OpenBao remains unsealed; named volumes are retained. The test polls readiness.
|
||||
docker compose restart -t 3 postgres redis minio rabbitmq
|
||||
docker compose restart -t 3 api worker lb
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?Не задан TARGET_INSTANCE_ID}"
|
||||
|
||||
compose() {
|
||||
docker compose --env-file .env -f compose.yml "$@"
|
||||
}
|
||||
|
||||
containers=$(compose ps --status running -q api)
|
||||
|
||||
target=""
|
||||
count=0
|
||||
|
||||
for container in $containers; do
|
||||
count=$((count + 1))
|
||||
|
||||
instance_id=$(docker inspect \
|
||||
--format '{{.Config.Hostname}}' "$container")
|
||||
|
||||
if [ "$instance_id" = "$TARGET_INSTANCE_ID" ]; then
|
||||
if [ -n "$target" ]; then
|
||||
printf '%s\n' 'Ошибка: найдено несколько подходящих реплик.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
target="$container"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$count" -lt 2 ]; then
|
||||
printf '%s\n' 'Ошибка: должны работать минимум две API-реплики.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "$target" ]; then
|
||||
printf '%s\n' 'Ошибка: указанная API-реплика не найдена.' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
docker stop -t 0 "$target" >/dev/null
|
||||
|
||||
printf '%s\n' "Остановлена API-реплика: $TARGET_INSTANCE_ID"
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p evidence
|
||||
exec > >(tee evidence/stand.txt) 2>&1
|
||||
docker compose version
|
||||
docker compose config --quiet
|
||||
docker compose ps
|
||||
make check validate test test-security benchmark
|
||||
make test-persistence ACTION_SCRIPT=./scripts/restart.sh
|
||||
make test-failover ACTION_SCRIPT=./scripts/stop-one.sh
|
||||
docker compose up -d --no-deps --scale api=2 --wait api
|
||||
make test-expiry
|
||||
make security-extra
|
||||
Reference in New Issue
Block a user