This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator init/unseal/policies and cert-auth KV bootstrap. Root stays on host."""
|
||||
import argparse,json,ssl,time,urllib.error,urllib.request
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1];OPS=ROOT/'secrets/operator'
|
||||
|
||||
def call(path,data=None,token=None,method=None):
|
||||
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca/ca.crt'))
|
||||
ctx.load_cert_chain(str(ROOT/'secrets/tls/operator/server.crt'),str(ROOT/'secrets/tls/operator/server.key'))
|
||||
headers={'Content-Type':'application/json'}
|
||||
if token:headers['X-Vault-Token']=token
|
||||
req=urllib.request.Request('https://localhost:18200/v1/'+path,data=json.dumps(data).encode() if data is not None else None,headers=headers,method=method)
|
||||
with urllib.request.urlopen(req,context=ctx,timeout=5) as response:
|
||||
body=response.read();return json.loads(body) if body else {}
|
||||
|
||||
def root_token():return json.loads((OPS/'bao_init.json').read_text())['root_token']
|
||||
|
||||
def unseal():
|
||||
if not call('sys/init')['initialized']:
|
||||
material=call('sys/init',{'secret_shares':1,'secret_threshold':1},method='PUT')
|
||||
p=OPS/'bao_init.json';p.write_text(json.dumps(material));p.chmod(0o600)
|
||||
if call('sys/seal-status')['sealed']:
|
||||
call('sys/unseal',{'key':json.loads((OPS/'bao_init.json').read_text())['keys'][0]})
|
||||
|
||||
def configure():
|
||||
unseal();token=root_token()
|
||||
mounts=call('sys/mounts',token=token)
|
||||
if 'secret/' not in mounts:call('sys/mounts/secret',{'type':'kv','options':{'version':'2'}},token)
|
||||
auth=call('sys/auth',token=token)
|
||||
if 'cert/' not in auth:call('sys/auth/cert',{'type':'cert'},token)
|
||||
roles=json.loads((OPS/'roles.json').read_text())
|
||||
for role,values in roles.items():
|
||||
policy=(ROOT/'infra/openbao/policies'/(role+'.hcl')).read_text()
|
||||
call('sys/policies/acl/'+role,{'policy':policy},token,method='PUT')
|
||||
names=['api-a','api-b'] if role=='api' else [role]
|
||||
call('auth/cert/certs/'+role,{'certificate':(ROOT/'secrets/ca/ca.crt').read_text(),'allowed_common_names':names,'token_policies':[role],'token_ttl':60,'token_max_ttl':120},token)
|
||||
call('secret/data/'+role,{'data':values},token)
|
||||
print('PASS: OpenBao initialized/unsealed; scoped cert roles and KV configured')
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('action',choices=['init','unseal','seal']);args=p.parse_args()
|
||||
if args.action=='init':configure()
|
||||
elif args.action=='unseal':unseal();print('PASS: operator unseal complete')
|
||||
else:call('sys/seal',{},root_token());print('PASS: OpenBao sealed')
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate local PKI and operator-held bootstrap inputs once."""
|
||||
import base64,hashlib,json,os,secrets
|
||||
from pathlib import Path
|
||||
import pki
|
||||
pki.initialize()
|
||||
root=Path(__file__).resolve().parents[1];folder=root/'secrets';ops=folder/'operator'
|
||||
|
||||
def value(name):
|
||||
p=ops/name
|
||||
if not p.exists():p.write_text(secrets.token_hex(24));p.chmod(0o600)
|
||||
return p.read_text().strip()
|
||||
|
||||
admin=value('postgres_password');cursor=value('cursor_secret');redis=value('redis_password')
|
||||
value('s3_root_password');value('rabbitmq_password');value('grafana_password')
|
||||
roles={}
|
||||
for role in ('api','worker','publisher','cleaner'):
|
||||
roles[role]={
|
||||
'database_url':'postgresql://%s:%s@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/ca/ca.crt&sslcrl=/run/ca/crl.pem'%(role,value('db_'+role)),
|
||||
}
|
||||
if role=='api':
|
||||
roles[role].update(cursor_secret=cursor,cache_url='rediss://api:%s@redis:6379/0'%redis)
|
||||
if role in ('api','worker','cleaner'):
|
||||
roles[role].update(s3_access_key_id='lab7-'+role,s3_secret_access_key=value('s3_'+role))
|
||||
if role in ('worker','publisher'):
|
||||
value('rabbit_'+role)
|
||||
p=ops/'roles.json';p.write_text(json.dumps(roles));p.chmod(0o600)
|
||||
root_dsn='postgresql://messenger:%s@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/ca/ca.crt'%admin
|
||||
p=ops/'database_url';p.write_text(root_dsn);p.chmod(0o600)
|
||||
# Stateful daemons read credentials via their own narrow bootstrap mounts.
|
||||
redis_config='port 0\ntls-port 6379\ntls-cert-file /run/tls/server.crt\ntls-key-file /run/tls/server.key\ntls-ca-cert-file /run/ca/ca.crt\ntls-auth-clients yes\nappendonly yes\nmaxmemory 96mb\nmaxmemory-policy allkeys-lru\nuser default off\nuser api on >'+redis+' ~session:* +get +setex +del +ping\n'
|
||||
pki.save(folder/'redis.conf',redis_config.encode())
|
||||
users=[]
|
||||
for role in ('worker','publisher'):
|
||||
salt=secrets.token_bytes(4);password=value('rabbit_'+role)
|
||||
users.append({'name':role,'password_hash':base64.b64encode(salt+hashlib.sha256(salt+password.encode()).digest()).decode(),'hashing_algorithm':'rabbit_password_hashing_sha256','tags':[]})
|
||||
definitions={'users':users,'vhosts':[{'name':'/'}],'permissions':[{'user':role,'vhost':'/','configure':'^attachment\\.process\\.v1$','write':'^(amq.default|attachment\\.process\\.v1)$' if role=='publisher' else '^$','read':'^attachment\\.process\\.v1$' if role=='worker' else '^$'} for role in ('worker','publisher')]}
|
||||
pki.save(folder/'rabbitmq.json',json.dumps(definitions).encode())
|
||||
# Grafana provisioning holds only Grafana's leaf key, under ignored operator-owned secrets.
|
||||
import yaml
|
||||
sources=[]
|
||||
for name,url in [('Prometheus','https://prometheus:9090'),('Loki','https://loki:3100'),('Tempo','https://tempo:3200')]:
|
||||
source={'name':name,'uid':name.lower(),'type':name.lower(),'access':'proxy','url':url,'jsonData':{'tlsAuth':True,'tlsAuthWithCACert':True,'serverName':name.lower()},'secureJsonData':{'tlsCACert':(folder/'ca/ca.crt').read_text(),'tlsClientCert':(folder/'tls/grafana/server.crt').read_text(),'tlsClientKey':(folder/'tls/grafana/server.key').read_text()}}
|
||||
if name=='Prometheus':source['isDefault']=True;source['jsonData']['timeInterval']='3s'
|
||||
sources.append(source)
|
||||
pki.save(folder/'grafana-datasources.yaml',yaml.safe_dump({'apiVersion':1,'datasources':sources}).encode())
|
||||
print('PASS: scoped bootstrap inputs generated; private values not printed')
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Operator loopback client preserving TLS server-name and CA verification."""
|
||||
import http.client,json,socket,ssl
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
PORTS={'prometheus':17909,'loki':17310,'tempo':17320}
|
||||
class Connection(http.client.HTTPSConnection):
|
||||
def connect(self):
|
||||
raw=socket.create_connection(('127.0.0.1',self.port),timeout=8)
|
||||
self.sock=self._context.wrap_socket(raw,server_hostname=self.host)
|
||||
|
||||
def get(host,path):
|
||||
context=ssl.create_default_context(cafile=str(ROOT/'secrets/ca/bundle.pem'))
|
||||
context.verify_flags|=ssl.VERIFY_CRL_CHECK_LEAF
|
||||
context.load_cert_chain(str(ROOT/'secrets/tls/operator/server.crt'),str(ROOT/'secrets/tls/operator/server.key'))
|
||||
connection=Connection(host,PORTS[host],context=context,timeout=8)
|
||||
try:
|
||||
connection.request('GET',path);response=connection.getresponse();data=response.read()
|
||||
if response.status!=200:raise OSError('Backend not ready: '+host+' '+str(response.status))
|
||||
return json.loads(data)
|
||||
finally:connection.close()
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit, bounded operator actions for this lab's Compose project only."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SERVICES = ('api-a', 'api-b')
|
||||
|
||||
|
||||
def command(args, capture=False):
|
||||
result = subprocess.run(args, cwd=ROOT, check=True, text=True,
|
||||
stdout=subprocess.PIPE if capture else None)
|
||||
return result.stdout.strip() if capture else None
|
||||
|
||||
|
||||
def compose(*args, capture=False):
|
||||
return command(['docker', 'compose', '--env-file', '.env', *args], capture)
|
||||
|
||||
|
||||
def inspect(container):
|
||||
return json.loads(command(['docker', 'inspect', container], True))[0]
|
||||
|
||||
|
||||
def containers(service):
|
||||
return compose('ps', '-a', '-q', service, capture=True).splitlines()
|
||||
|
||||
|
||||
def start_services(*services):
|
||||
for service in services:
|
||||
for container in containers(service):
|
||||
command(['docker', 'start', container])
|
||||
|
||||
|
||||
def wait_healthy(service, timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
ids = containers(service)
|
||||
if ids and all(inspect(c)['State'].get('Health', {}).get('Status') == 'healthy' for c in ids):
|
||||
return
|
||||
time.sleep(.5)
|
||||
raise RuntimeError('%s did not become healthy' % service)
|
||||
|
||||
|
||||
def target_service(target):
|
||||
if not target:
|
||||
raise RuntimeError('TARGET_INSTANCE_ID is required')
|
||||
for service in SERVICES:
|
||||
for container in containers(service):
|
||||
data = inspect(container)
|
||||
if data['Config']['Hostname'] == target:
|
||||
return service, container
|
||||
raise RuntimeError('Unknown API instance alias')
|
||||
|
||||
|
||||
def set_backend(service, enabled):
|
||||
# Fixed allowlist; shell receives no untrusted instance or credential input.
|
||||
if service not in SERVICES:
|
||||
raise ValueError('Unknown service')
|
||||
token = ('serve:' if enabled else 'drain:') + uuid.uuid4().hex
|
||||
path = '/tmp/control-' + service
|
||||
compose('exec', '-T', 'nginx', 'sh', '-ec',
|
||||
"printf '%s\\n' '" + token + "' > " + path + '.next; mv -f ' + path + '.next ' + path)
|
||||
deadline = time.monotonic() + 10
|
||||
expected = token + (' up' if enabled else ' down')
|
||||
while time.monotonic() < deadline:
|
||||
ack = compose('exec', '-T', 'nginx', 'sh', '-c',
|
||||
'cat /tmp/applied-' + service + ' 2>/dev/null || true', capture=True)
|
||||
if ack == expected:
|
||||
return
|
||||
time.sleep(.2)
|
||||
raise RuntimeError('Readiness controller did not acknowledge backend state for ' + service)
|
||||
|
||||
|
||||
def stop_one():
|
||||
service, container = target_service(os.environ.get('TARGET_INSTANCE_ID'))
|
||||
running = [c for name in SERVICES for c in containers(name)
|
||||
if inspect(c)['State'].get('Health', {}).get('Status') == 'healthy'
|
||||
and inspect(c)['State']['Running']]
|
||||
if len(running) < 2:
|
||||
raise RuntimeError('Restore the other replica before this experiment')
|
||||
print('Stopping API replica:', service, container[:12], flush=True)
|
||||
command(['docker', 'stop', '--time', '8', container])
|
||||
if inspect(container)['State']['Running']:
|
||||
raise RuntimeError('Target is still running')
|
||||
|
||||
|
||||
def restart():
|
||||
# Never start the one-shot migration service as part of persistence testing.
|
||||
compose('restart', 'postgres', 'redis', 's3', 'rabbitmq', *SERVICES, 'nginx', 'outbox-publisher', 'worker')
|
||||
for service in (*SERVICES, 'nginx'):
|
||||
wait_healthy(service)
|
||||
|
||||
|
||||
def rolling_update():
|
||||
# Run additive migrations once before replacing either API version.
|
||||
compose('run', '--rm', '--no-deps', 'migrate')
|
||||
for service in SERVICES:
|
||||
other = SERVICES[1] if service == SERVICES[0] else SERVICES[0]
|
||||
wait_healthy(other)
|
||||
set_backend(other, True)
|
||||
before = containers(service)
|
||||
set_backend(service, False)
|
||||
# The old nginx worker can retain the old upstream table until it exits.
|
||||
# worker_shutdown_timeout=6s bounds that drain; no new work then reaches it.
|
||||
time.sleep(6.5)
|
||||
compose('up', '-d', '--no-deps', '--force-recreate', '--no-build', service)
|
||||
wait_healthy(service)
|
||||
set_backend(service, True)
|
||||
time.sleep(2) # DNS valid=1s + readiness before moving to the next replica.
|
||||
after = containers(service)
|
||||
if before == after:
|
||||
raise RuntimeError('Replica was not replaced')
|
||||
print(json.dumps({'service': service, 'before': before, 'after': after}), flush=True)
|
||||
|
||||
|
||||
def restore():
|
||||
start_services(*SERVICES)
|
||||
for service in SERVICES:
|
||||
wait_healthy(service)
|
||||
for service in SERVICES:
|
||||
set_backend(service, True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('stop-one', 'restart', 'restore', 'rolling-update', 'status'))
|
||||
args = parser.parse_args()
|
||||
if args.action == 'stop-one':
|
||||
stop_one()
|
||||
elif args.action == 'restart':
|
||||
restart()
|
||||
elif args.action == 'rolling-update':
|
||||
rolling_update()
|
||||
elif args.action == 'restore':
|
||||
restore()
|
||||
else:
|
||||
for service in ('postgres', 'redis', *SERVICES, 'nginx'):
|
||||
for container in containers(service):
|
||||
data = inspect(container)
|
||||
print(json.dumps({'service': service, 'id': data['Id'][:12],
|
||||
'instance': data['Config']['Hostname'],
|
||||
'running': data['State']['Running'],
|
||||
'started_at': data['State']['StartedAt'],
|
||||
'health': data['State'].get('Health', {}).get('Status'),
|
||||
'image_id': data['Image'],
|
||||
'cpu_limit': data['HostConfig']['NanoCpus'] / 1e9,
|
||||
'memory_limit_bytes': data['HostConfig']['Memory'],
|
||||
'published_ports': data['HostConfig'].get('PortBindings')}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator-owned local CA, service leaves and CRL. No private output."""
|
||||
import argparse,datetime as dt,json,os
|
||||
from pathlib import Path
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes,serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from cryptography.x509.oid import NameOID,ExtendedKeyUsageOID
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
PRIVATE=ROOT/'secrets/operator'; PUBLIC=ROOT/'secrets/ca'; LEAVES=ROOT/'secrets/tls'
|
||||
NAMES=('nginx','api-a','api-b','worker','publisher','cleaner','operator','postgres','redis','s3','rabbitmq','otel-collector','collector','prometheus','loki','tempo','grafana','openbao','intruder')
|
||||
|
||||
def save(path,data,mode=0o444):
|
||||
path.parent.mkdir(parents=True,exist_ok=True)
|
||||
temp=path.with_name(path.name+".next")
|
||||
temp.write_bytes(data);temp.chmod(mode);temp.replace(path)
|
||||
|
||||
def key_bytes(key):
|
||||
return key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption())
|
||||
|
||||
def ca():
|
||||
return (serialization.load_pem_private_key((PRIVATE/'ca.key').read_bytes(),None),
|
||||
x509.load_pem_x509_certificate((PUBLIC/'ca.crt').read_bytes()))
|
||||
|
||||
def issue(name,expired=False):
|
||||
key,authority=ca(); leaf=rsa.generate_private_key(public_exponent=65537,key_size=2048)
|
||||
now=dt.datetime.now(dt.timezone.utc)
|
||||
dns=[name]
|
||||
if name in ('api-a','api-b'):dns+=['messenger-api']
|
||||
if name in ('nginx','openbao','grafana'):dns+=['localhost']
|
||||
cert=(x509.CertificateBuilder().subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,name)]))
|
||||
.issuer_name(authority.subject).public_key(leaf.public_key()).serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now-dt.timedelta(days=2) if expired else now-dt.timedelta(minutes=5))
|
||||
.not_valid_after(now-dt.timedelta(days=1) if expired else now+dt.timedelta(days=2))
|
||||
.add_extension(x509.SubjectAlternativeName([x509.DNSName(value) for value in dns]),False)
|
||||
.add_extension(x509.BasicConstraints(ca=False,path_length=None),True)
|
||||
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH,ExtendedKeyUsageOID.CLIENT_AUTH]),False)
|
||||
.sign(key,hashes.SHA256()))
|
||||
folder=LEAVES/name
|
||||
save(folder/'server.key',key_bytes(leaf))
|
||||
save(folder/'server.crt',cert.public_bytes(serialization.Encoding.PEM))
|
||||
return cert.serial_number
|
||||
|
||||
def crl():
|
||||
key,authority=ca();now=dt.datetime.now(dt.timezone.utc)
|
||||
file=PRIVATE/'revoked.json'; revoked=json.loads(file.read_text()) if file.exists() else []
|
||||
builder=x509.CertificateRevocationListBuilder().issuer_name(authority.subject).last_update(now-dt.timedelta(minutes=1)).next_update(now+dt.timedelta(days=7))
|
||||
for serial in revoked:
|
||||
builder=builder.add_revoked_certificate(x509.RevokedCertificateBuilder().serial_number(serial).revocation_date(now-dt.timedelta(minutes=1)).build())
|
||||
pem=builder.sign(key,hashes.SHA256()).public_bytes(serialization.Encoding.PEM)
|
||||
save(PUBLIC/'crl.pem',pem)
|
||||
save(PUBLIC/'bundle.pem',(PUBLIC/'ca.crt').read_bytes()+pem)
|
||||
|
||||
def initialize():
|
||||
(ROOT/'secrets').mkdir(mode=0o700,exist_ok=True)
|
||||
PRIVATE.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
if not (PRIVATE/'ca.key').exists():
|
||||
key=rsa.generate_private_key(public_exponent=65537,key_size=3072)
|
||||
name=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'Lab7 local CA')]);now=dt.datetime.now(dt.timezone.utc)
|
||||
cert=(x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now-dt.timedelta(minutes=5))
|
||||
.not_valid_after(now+dt.timedelta(days=365)).add_extension(x509.BasicConstraints(ca=True,path_length=0),True)
|
||||
.add_extension(x509.KeyUsage(False,False,False,False,False,True,True,False,False),True)
|
||||
.sign(key,hashes.SHA256()))
|
||||
save(PRIVATE/'ca.key',key_bytes(key),0o600);save(PUBLIC/'ca.crt',cert.public_bytes(serialization.Encoding.PEM))
|
||||
for name in NAMES:
|
||||
path=LEAVES/name/'server.crt'
|
||||
if not path.exists() or x509.load_pem_x509_certificate(path.read_bytes()).not_valid_after_utc < dt.datetime.now(dt.timezone.utc)+dt.timedelta(hours=6):
|
||||
issue(name)
|
||||
if not (LEAVES/'expired'/'server.crt').exists():issue('expired',expired=True)
|
||||
crl();print('PASS: local CA, service certificates and CRL ready')
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('action',choices=['init','rotate','revoke']);p.add_argument('identity',nargs='?');args=p.parse_args()
|
||||
if args.action=='init':initialize()
|
||||
elif args.action=='rotate':
|
||||
assert args.identity in NAMES;issue(args.identity);print('PASS: leaf replaced')
|
||||
else:
|
||||
serial=x509.load_pem_x509_certificate((LEAVES/args.identity/'server.crt').read_bytes()).serial_number
|
||||
path=PRIVATE/'revoked.json';values=json.loads(path.read_text()) if path.exists() else []
|
||||
save(path,json.dumps(sorted(set(values+[serial]))).encode(),0o600);crl();print('PASS: leaf revoked in CRL')
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
|
||||
exec python3 scripts/manage.py restart
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
|
||||
exec python3 scripts/manage.py rolling-update
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator-only worker secret and API leaf rotation, without rebuilding images."""
|
||||
import json,secrets,subprocess
|
||||
from pathlib import Path
|
||||
import bao,pki
|
||||
ROOT=Path(__file__).resolve().parents[1];OPS=ROOT/'secrets/operator'
|
||||
|
||||
def worker_secret():
|
||||
roles=json.loads((OPS/'roles.json').read_text())
|
||||
pending_path=OPS/'worker-rotation-pending.json'
|
||||
if pending_path.exists():
|
||||
pending=json.loads(pending_path.read_text())
|
||||
else:
|
||||
old=roles['worker']['database_url'];new_password=secrets.token_hex(24)
|
||||
replacement=old.replace(old.split(':',2)[2].split('@')[0],new_password,1)
|
||||
pending={'old_dsn':old,'password':new_password,'values':dict(roles['worker'],database_url=replacement)}
|
||||
pki.save(pending_path,json.dumps(pending).encode(),0o600)
|
||||
values=pending['values'];new_password=pending['password']
|
||||
sql="ALTER ROLE worker PASSWORD '"+new_password+"';\n"
|
||||
subprocess.run(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger','-v','ON_ERROR_STOP=1'],cwd=ROOT,input=sql,text=True,check=True,stdout=subprocess.DEVNULL)
|
||||
try:
|
||||
bao.call('secret/data/worker',{'data':values},bao.root_token())
|
||||
except Exception:
|
||||
# A lost response can follow a committed PUT. Reconcile to the saved target.
|
||||
try:
|
||||
actual=bao.call('secret/data/worker',token=bao.root_token())['data']['data']
|
||||
except Exception:
|
||||
raise RuntimeError('Rotation pending; restore OpenBao and rerun worker-secret') from None
|
||||
if actual!=values:
|
||||
raise RuntimeError('Rotation pending; rerun worker-secret to apply saved target') from None
|
||||
roles['worker']=values
|
||||
pki.save(OPS/'roles.json',json.dumps(roles).encode(),0o600)
|
||||
pki.save(OPS/'db_worker',new_password.encode(),0o600)
|
||||
pki.save(OPS/'previous-worker-dsn',pending['old_dsn'].encode(),0o600)
|
||||
pending_path.unlink()
|
||||
print('PASS: worker DB password and scoped KV rotated')
|
||||
|
||||
|
||||
def api_leaf():
|
||||
folder=OPS/'previous-api-a';folder.mkdir(exist_ok=True,mode=0o700)
|
||||
for name in ('server.crt','server.key'):
|
||||
pki.save(folder/name,(ROOT/'secrets/tls/api-a'/name).read_bytes(),0o600)
|
||||
old=pki.x509.load_pem_x509_certificate((folder/'server.crt').read_bytes()).serial_number
|
||||
pki.issue('api-a')
|
||||
path=OPS/'revoked.json';values=json.loads(path.read_text()) if path.exists() else []
|
||||
pki.save(path,json.dumps(sorted(set(values+[old]))).encode(),0o600);pki.crl()
|
||||
bao.call('auth/cert/crls/retired',{'crl':(ROOT/'secrets/ca/crl.pem').read_text()},bao.root_token())
|
||||
subprocess.run(['docker','compose','exec','-T','nginx','nginx','-s','reload'],cwd=ROOT,check=True)
|
||||
print('PASS: API leaf replaced; old serial revoked in CRL and OpenBao')
|
||||
|
||||
if __name__=='__main__':
|
||||
import argparse
|
||||
p=argparse.ArgumentParser();p.add_argument('kind',choices=['worker-secret','api-leaf']);args=p.parse_args()
|
||||
worker_secret() if args.kind=='worker-secret' else api_leaf()
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
|
||||
docker run --rm --entrypoint python mtusi-lab7-api:local -c 'from importlib.metadata import distributions; print("\n".join(sorted(d.metadata["Name"]+"=="+d.version for d in distributions())))' > security/runtime-requirements.txt
|
||||
.venv/bin/pip-audit -r security/runtime-requirements.txt --no-deps --disable-pip -f json -o security/dependency-scan.json
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Audit Debian source-package inventory from the actual runtime image via OSV."""
|
||||
import json,subprocess,time,urllib.request
|
||||
from pathlib import Path
|
||||
image='mtusi-lab7-api:local'
|
||||
raw=subprocess.check_output(['docker','run','--rm','--entrypoint','dpkg-query',image,'-W','-f=${source:Package}\t${source:Version}\n'],text=True)
|
||||
packages=sorted({tuple(line.split('\t')) for line in raw.splitlines() if '\t' in line})
|
||||
queries=[{'package':{'name':name,'ecosystem':'Debian:12'},'version':version} for name,version in packages]
|
||||
results=[]
|
||||
for offset in range(0,len(queries),25):
|
||||
batch=queries[offset:offset+25]
|
||||
for attempt in range(3):
|
||||
try:
|
||||
request=urllib.request.Request('https://api.osv.dev/v1/querybatch',data=json.dumps({'queries':batch}).encode(),headers={'Content-Type':'application/json'})
|
||||
with urllib.request.urlopen(request,timeout=30) as response:data=json.load(response)
|
||||
results.extend(data['results']);break
|
||||
except OSError:
|
||||
if attempt==2:raise
|
||||
time.sleep(2)
|
||||
out={'image':image,'scope':'Debian 12 source packages in final root filesystem; Python packages audited separately with pip-audit','packages':[dict(query,result=result) for query,result in zip(queries,results)]}
|
||||
Path('security/image-osv-scan.json').write_text(json.dumps(out,indent=2)+'\n')
|
||||
print('PASS image inventory audited:',len(queries),'source packages;',sum(bool(r.get('vulns')) for r in results),'with findings')
|
||||
@@ -0,0 +1,33 @@
|
||||
"""One-shot operator grants after migrations. No credentials printed."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import psycopg2
|
||||
from psycopg2 import sql
|
||||
values=json.loads(Path('/run/bootstrap/roles.json').read_text())
|
||||
conn=psycopg2.connect(Path('/run/bootstrap/database_url').read_text().strip())
|
||||
conn.autocommit=False
|
||||
with conn.cursor() as cur:
|
||||
for role,keys in values.items():
|
||||
password=keys['database_url'].split(':',2)[2].split('@')[0]
|
||||
cur.execute('SELECT 1 FROM pg_roles WHERE rolname=%s',(role,))
|
||||
if not cur.fetchone():cur.execute(sql.SQL('CREATE ROLE {} LOGIN').format(sql.Identifier(role)))
|
||||
cur.execute(sql.SQL('ALTER ROLE {} PASSWORD %s NOSUPERUSER NOCREATEDB NOCREATEROLE').format(sql.Identifier(role)),(password,))
|
||||
cur.execute(sql.SQL('GRANT CONNECT ON DATABASE messenger TO {}').format(sql.Identifier(role)))
|
||||
cur.execute(sql.SQL('GRANT USAGE ON SCHEMA public TO {}').format(sql.Identifier(role)))
|
||||
for role in values:
|
||||
cur.execute(sql.SQL('REVOKE ALL ON ALL TABLES IN SCHEMA public FROM {}').format(sql.Identifier(role)))
|
||||
api={'users':'SELECT,INSERT,UPDATE','sessions':'SELECT,INSERT,UPDATE,DELETE','chats':'SELECT,INSERT','chat_members':'SELECT,INSERT','messages':'SELECT,INSERT','attachments':'SELECT,INSERT,UPDATE','attachment_jobs':'SELECT,INSERT','attachment_outbox':'SELECT,INSERT','attachment_variants':'SELECT','message_idempotency':'SELECT,INSERT,UPDATE,DELETE','message_attachments':'SELECT,INSERT','login_budgets':'SELECT,INSERT,UPDATE'}
|
||||
cur.execute("SELECT tablename FROM pg_tables WHERE schemaname='public'")
|
||||
tables={row[0] for row in cur.fetchall()}
|
||||
for table,privileges in api.items():
|
||||
if table in tables:cur.execute(sql.SQL('GRANT '+privileges+' ON {} TO api').format(sql.Identifier(table)))
|
||||
grants={
|
||||
'worker':{'attachments':'SELECT,UPDATE','attachment_jobs':'SELECT,UPDATE','attachment_outbox':'SELECT,INSERT,UPDATE','attachment_variants':'SELECT,INSERT'},
|
||||
'publisher':{'attachments':'SELECT,UPDATE','attachment_jobs':'SELECT,UPDATE','attachment_outbox':'SELECT,INSERT,UPDATE'},
|
||||
'cleaner':{'attachments':'SELECT,DELETE','attachment_jobs':'SELECT,UPDATE','attachment_outbox':'SELECT,UPDATE'},
|
||||
}
|
||||
for role,tables in grants.items():
|
||||
for table,privileges in tables.items():
|
||||
cur.execute(sql.SQL('GRANT '+privileges+' ON {} TO {}').format(sql.Identifier(table),sql.Identifier(role)))
|
||||
cur.execute('GRANT UPDATE (updated_at) ON attachments TO cleaner')
|
||||
conn.commit();conn.close();print('PASS: separate database roles and grants applied')
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
|
||||
exec python3 scripts/manage.py stop-one
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
|
||||
lab_python=${PYTHON:-python3}
|
||||
[ -f .env ] || cp .env.example .env
|
||||
"$lab_python" scripts/bootstrap.py
|
||||
docker compose config --quiet
|
||||
docker compose build api-a s3
|
||||
docker compose up -d --no-build --force-recreate openbao postgres redis s3 rabbitmq otel-collector prometheus loki tempo grafana otel-collector-tls prometheus-tls loki-tls tempo-tls
|
||||
# Operator init/unseal happens before applications need scoped secrets.
|
||||
"$lab_python" - <<'PY'
|
||||
import sys,time
|
||||
sys.path.insert(0,'scripts')
|
||||
import bao
|
||||
for attempt in range(40):
|
||||
try:
|
||||
bao.configure()
|
||||
break
|
||||
except OSError:
|
||||
if attempt==39:raise
|
||||
time.sleep(1)
|
||||
PY
|
||||
docker compose --profile operator run --rm --no-deps migrate
|
||||
docker compose --profile operator run --rm --no-deps setup-db
|
||||
docker compose --profile operator run --rm --no-deps s3-bootstrap
|
||||
docker compose exec -T rabbitmq rabbitmqctl import_definitions /run/bootstrap/rabbitmq.json
|
||||
docker compose up -d --no-build --force-recreate api-a api-b worker outbox-publisher attachment-cleaner nginx
|
||||
"$lab_python" scripts/wait_ready.py
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded verified-HTTPS readiness wait."""
|
||||
import ssl,time,urllib.request
|
||||
context=ssl.create_default_context(cafile='secrets/ca/ca.crt')
|
||||
pending={'api':'https://localhost:8443/health/ready','grafana':'https://localhost:17400/api/health'}
|
||||
deadline=time.monotonic()+120
|
||||
while pending and time.monotonic()<deadline:
|
||||
for name,url in list(pending.items()):
|
||||
try:
|
||||
with urllib.request.urlopen(url,context=context,timeout=2) as response:
|
||||
if response.status==200:del pending[name]
|
||||
except OSError:pass
|
||||
if pending:time.sleep(1)
|
||||
if pending:raise SystemExit('Readiness timeout: '+','.join(pending))
|
||||
print('PASS verified HTTPS API and Grafana ready')
|
||||
Reference in New Issue
Block a user