[+] lab7
Grade 3 secure application acceptance / secure (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Xabenskie
2026-11-30 09:09:57 +03:00
parent 20afc2c790
commit 4eca49fe3d
149 changed files with 68317 additions and 58 deletions
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Operator-only init/unseal/policies and scoped workload provisioning. Never print secrets."""
import argparse
import json
from pathlib import Path
import ssl
import time
import urllib.request
import urllib.error
ROOT=Path(__file__).resolve().parents[1]
SECRETS=ROOT/'secrets'
OPERATOR=SECRETS/'operator'
def request(method,path,body=None,token=True):
context=ssl.create_default_context(cafile=str(SECRETS/'trust/ca.crt'))
context.load_cert_chain(str(SECRETS/'pki/operator/tls.crt'),str(SECRETS/'pki/operator/tls.key'))
headers={'Content-Type':'application/json'}
if token:
headers['X-Vault-Token']=json.loads((OPERATOR/'bao-init.json').read_text())['root_token']
req=urllib.request.Request('https://localhost:8200/v1/'+path,data=None if body is None else json.dumps(body).encode(),headers=headers,method=method)
with urllib.request.urlopen(req,context=context,timeout=5) as response:
raw=response.read()
return json.loads(raw) if raw else {}
def bootstrap():
end=time.monotonic()+60
while True:
try: status=request('GET','sys/init',token=False);break
except (OSError,urllib.error.URLError):
if time.monotonic()>end: raise RuntimeError('OpenBao TLS endpoint not ready') from None
time.sleep(.5)
path=OPERATOR/'bao-init.json'
if not status['initialized']:
result=request('POST','sys/init',{'secret_shares':1,'secret_threshold':1},token=False)
path.write_text(json.dumps(result));path.chmod(0o600)
if not path.exists(): raise RuntimeError('Operator init material is required; no automatic reset')
status=request('GET','sys/seal-status',token=False)
if status['sealed']:
result=json.loads(path.read_text())
request('POST','sys/unseal',{'key':result['keys_base64'][0]},token=False)
mounts=request('GET','sys/mounts')
if 'secret/' not in mounts: request('POST','sys/mounts/secret',{'type':'kv','options':{'version':'2'}})
auth=request('GET','sys/auth')
if 'cert/' not in auth: request('POST','sys/auth/cert',{'type':'cert'})
values=json.loads((OPERATOR/'workloads.json').read_text())
for role in ('api','worker','relay'):
policy='path "secret/data/'+role+'" { capabilities = ["read"] }'
request('PUT','sys/policies/acl/'+role,{'policy':policy})
request('POST','auth/cert/certs/'+role,{'certificate':(SECRETS/'pki'/role/'tls.crt').read_text(),
'allowed_common_names':[role],'allowed_dns_sans':[role],
'token_policies':[role],'token_ttl':'60s','token_max_ttl':'300s','token_explicit_max_ttl':'300s'})
request('POST','secret/data/'+role,{'data':values[role]})
print('OpenBao initialized/unsealed; scoped cert auth and KV policies ready. Values hidden.')
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('action',choices=['bootstrap','seal','unseal'],default='bootstrap',nargs='?');args=parser.parse_args()
if args.action=='seal': request('PUT','sys/seal',{});print('OpenBao sealed')
else: bootstrap()
+33
View File
@@ -0,0 +1,33 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
umask 077
mkdir -p secrets
python3 - <<'PY'
from pathlib import Path
import secrets
root = Path('secrets')
p = root / 'postgres_password'
if not p.exists():
p.write_text(secrets.token_hex(24))
pw = p.read_text().strip()
for name, value in {
'database_url': f'postgresql://messenger:{pw}@postgres:5432/messenger',
'grafana_password': secrets.token_hex(24),
'cache_url': 'redis://redis:6379/0',
'minio_root_user': 'lab4-admin',
'minio_root_password': secrets.token_hex(24),
's3_access_key_id': 'messenger-api',
's3_secret_access_key': secrets.token_hex(24),
}.items():
path = root / name
if not path.exists():
path.write_text(value)
# Bind-mounted Docker secrets must be readable by container uid 10001.
# Parent directory remains 0700 on the host.
for path in root.iterdir():
if path.is_file(): path.chmod(0o444)
if not Path('.env').exists():
Path('.env').write_text('SESSION_TTL_SECONDS=3600\n')
print('Local secrets ready (values hidden).')
PY
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""Generate local role secrets and operator-only provisioning material."""
import hashlib
import json
import os
from pathlib import Path
import secrets
import urllib.parse
ROOT=Path(__file__).resolve().parents[1]
S=ROOT/'secrets';OP=S/'operator'
def secret(name):
path=S/name
if not path.exists(): path.write_text(secrets.token_hex(24));path.chmod(0o444)
return path.read_text().strip()
def main():
os.umask(0o077)
roles={};workloads={}
for role in ('api','worker','relay'):
roles['db_'+role]=secret('db_'+role+'_password')
sid='lab7-'+role
password=secret('s3_'+role+'_secret')
id_path=S/('s3_'+role+'_id')
if id_path.exists(): id_path.chmod(0o600)
id_path.write_text(sid);(S/('s3_'+role+'_id')).chmod(0o444)
broker_user='consumer' if role=='worker' else 'producer'
broker_password=secret('broker_'+broker_user+'_password')
values={'DATABASE_URL':'postgresql://db_'+role+':'+roles['db_'+role]+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/trust/ca.crt',
'S3_ACCESS_KEY_ID':sid,'S3_SECRET_ACCESS_KEY':password,
'BROKER_URL':'rediss://'+broker_user+':'+broker_password+'@broker:'+('6381' if role=='worker' else '6380')+'/0'}
if role=='api': values['CACHE_URL']='rediss://profile:'+secret('cache_password')+'@redis:6380/0'
workloads[role]=values
secret('s3_test_secret')
test_id=S/'s3_test_id'
if test_id.exists():test_id.chmod(0o600)
test_id.write_text('lab7-test');test_id.chmod(0o444)
if (OP/'workloads.json').exists(): (OP/'workloads.json').chmod(0o600)
(OP/'workloads.json').write_text(json.dumps(workloads));(OP/'workloads.json').chmod(0o444)
if (OP/'db-roles.json').exists(): (OP/'db-roles.json').chmod(0o600)
(OP/'db-roles.json').write_text(json.dumps(roles));(OP/'db-roles.json').chmod(0o444)
# Root URL exists only for migrate/operator test containers, with verify-full.
root_url=S/'database_url';root_url.chmod(0o600)
root_url.write_text('postgresql://messenger:'+secret('postgres_password')+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/trust/ca.crt');root_url.chmod(0o444)
# Redis authenticates separately from TLS listener identities. No default data permissions.
def pw(value): return '#'+hashlib.sha256(value.encode()).hexdigest()
broker_acl='user default on nopass -@all +ping\n'
broker_acl+='user producer on '+pw(secret('broker_producer_password'))+' ~attachment-jobs -@all +xadd +ping +client|setinfo\n'
broker_acl+='user consumer on '+pw(secret('broker_consumer_password'))+' ~attachment-jobs -@all +xgroup|create +xreadgroup +xautoclaim +xack +xdel +ping +client|setinfo\n'
cache_acl='user default on nopass -@all +ping\nuser profile on '+pw(secret('cache_password'))+' ~user:* -@all +get +set +ping +client|setinfo\n'
cache_acl+='user tester on '+pw(secret('cache_test_password'))+' ~* -@all +get +set +del +ttl +flushdb +ping +client|setinfo\n'
test_cache=S/'test_cache_url'
if test_cache.exists():test_cache.chmod(0o600)
test_cache.write_text('rediss://tester:'+secret('cache_test_password')+'@redis:6382/0');test_cache.chmod(0o444)
for name,value in [('broker.acl',broker_acl),('cache.acl',cache_acl)]:
p=S/name
if p.exists():p.chmod(0o600)
p.write_text(value);p.chmod(0o444)
# Scoped S3 policies: API writes staging only; worker publishes; relay performs cleanup.
policies=S/'policies';policies.mkdir(exist_ok=True);policies.chmod(0o755)
for role in ('api','worker','relay','test'):
entries=[{'Effect':'Allow','Action':['s3:GetBucketLocation'],'Resource':['arn:aws:s3:::messenger-attachments']},
{'Effect':'Allow','Action':['s3:ListBucket'],'Resource':['arn:aws:s3:::messenger-attachments'],
'Condition':{'StringLike':{'s3:prefix':['originals/*','staging/*','variants/*']}}}]
rights={'api':{'staging':['GetObject','PutObject','DeleteObject'],'originals':['GetObject'],'variants':['GetObject']},
'worker':{'staging':['GetObject','DeleteObject'],'originals':['GetObject','PutObject'],'variants':['GetObject','PutObject']},
'relay':{prefix:['GetObject','DeleteObject'] for prefix in ['staging','originals','variants']},
'test':{prefix:['GetObject','PutObject','DeleteObject'] for prefix in ['staging','originals','variants']}}[role]
for prefix,actions in rights.items(): entries.append({'Effect':'Allow','Action':['s3:'+a for a in actions],'Resource':['arn:aws:s3:::messenger-attachments/'+prefix+'/*']})
p=policies/(role+'.json')
if p.exists():p.chmod(0o600)
p.write_text(json.dumps({'Version':'2012-10-17','Statement':entries}));p.chmod(0o444)
# Provisioning includes Grafana's own private TLS client key, generated outside Git.
template={'apiVersion':1,'datasources':[{'name':name,'uid':name.lower(),'type':name.lower(),'access':'proxy','isDefault':name=='Prometheus'} for name in ['Prometheus','Loki','Tempo']]}
for item in template['datasources']:
hostname={'Prometheus':'prometheus','Loki':'loki','Tempo':'tempo'}[item['name']]
item['url']='https://'+hostname+':9443'
item.setdefault('jsonData',{}).update(tlsAuth=True,tlsAuthWithCACert=True,httpMethod='GET')
item['secureJsonData']={'tlsCACert':(S/'trust/ca.crt').read_text(),'tlsClientCert':(S/'pki/grafana/tls.crt').read_text(),'tlsClientKey':(S/'pki/grafana/tls.key').read_text()}
target=S/'grafana-datasources.yaml'
if target.exists():target.chmod(0o600)
target.write_text(json.dumps(template));target.chmod(0o444)
print('Scoped backend credentials and private provisioning ready; values hidden.')
if __name__=='__main__': main()
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
project="mtusi-lab7-fresh-$$"
cleanup() { docker compose -p "$project" down --volumes >/dev/null 2>&1; }
trap cleanup EXIT INT TERM
docker compose -p "$project" up -d --wait --wait-timeout 120 postgres redis redis-tls minio minio-init
docker compose -p "$project" run --rm --no-deps migrate
docker compose -p "$project" run --rm --no-deps migrate
docker compose -p "$project" run --rm --no-deps student-tests
printf '%s\n' 'PASS: TLS-backed fresh volumes, migrations 001–005 twice and full operator test suite.'
+202
View File
@@ -0,0 +1,202 @@
#!/usr/bin/env python3
"""Local Compose orchestration. No credentials, tokens or environment dumps in evidence."""
import argparse
import datetime
import json
import os
import ssl
import re
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BASE_URL = os.environ.get('BASE_URL', 'https://localhost:8443').rstrip('/')
TLS_CONTEXT=ssl.create_default_context(cafile=str(ROOT/'secrets/trust/ca.crt'))
def command(args, timeout=120):
return subprocess.run(args, cwd=ROOT, check=True, capture_output=True, text=True, timeout=timeout).stdout.strip()
def compose(*args, timeout=120):
return command(['docker', 'compose', *args], timeout=timeout)
def inspect(containers):
if not containers:
return []
return json.loads(command(['docker','inspect',*containers]))
def container_ids(service=None, all_containers=False):
args = ['ps'] + (['--all'] if all_containers else []) + ['-q'] + ([service] if service else [])
return compose(*args).split()
def probe(container, host='127.0.0.1', path='/health/live'):
code = '''import json,sys,urllib.request,urllib.error
try:
r=urllib.request.urlopen('http://'+sys.argv[1]+':8080'+sys.argv[2],timeout=4)
except urllib.error.HTTPError as exc:
r=exc
print(json.dumps({'status':r.code,'instance':r.headers.get('X-Instance-Id'),'release':r.headers.get('X-App-Release')}))
'''
return json.loads(command(['docker','exec',container,'python','-c',code,host,path], timeout=8))
def replicas():
items = []
for data in inspect(container_ids('api')):
if data['State']['Running']:
result = probe(data['Id'])
items.append({'container':data['Id'], 'name':data['Name'].lstrip('/'),
'instance':result['instance'], 'release':result['release'], 'image_id':data['Image']})
return items
def snapshot():
items = []
for data in inspect(container_ids(all_containers=True)):
service = data['Config']['Labels']['com.docker.compose.service']
item = {
'service':service, 'container':data['Id'], 'name':data['Name'].lstrip('/'),
'status':data['State']['Status'], 'health':data['State'].get('Health',{}).get('Status'),
'started_at':data['State']['StartedAt'], 'image':data['Config']['Image'], 'image_id':data['Image'],
'memory_bytes':data['HostConfig']['Memory'], 'nano_cpus':data['HostConfig']['NanoCpus'],
'published_ports':data['HostConfig']['PortBindings'],
'volumes':sorted(m['Name'] for m in data['Mounts'] if m['Type']=='volume'),
'networks':sorted(data['NetworkSettings']['Networks']),
}
if service == 'api' and data['State']['Running']:
result = probe(data['Id'])
item.update({'http_status':result['status'], 'instance':result['instance'], 'release':result['release']})
items.append(item)
return items
def wait_healthy(container, timeout=60):
deadline = time.monotonic()+timeout
while time.monotonic() < deadline:
data = inspect([container])[0]
if data['State'].get('Health',{}).get('Status') == 'healthy':
return
time.sleep(0.3)
raise RuntimeError('Container did not become healthy')
def wait_cluster(count=2, timeout=60):
deadline = time.monotonic()+timeout
seen = set()
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(BASE_URL+'/health/ready',context=TLS_CONTEXT,timeout=5) as response:
alias = response.headers.get('X-Instance-Id')
if alias:
seen.add(alias)
if len(seen) >= count:
return sorted(seen)
except (OSError, urllib.error.URLError):
pass
time.sleep(0.1)
raise RuntimeError('Load balancer did not discover required API instances')
def stop_one(target):
if not re.fullmatch(r'[a-f0-9]{32}', target):
raise ValueError('Invalid target instance alias')
matching = [item for item in replicas() if item['instance']==target]
if len(matching) != 1:
raise RuntimeError('Target must match exactly one running API process')
item = matching[0]
started = time.monotonic()
command(['docker','stop','--time','7',item['container']],timeout=9)
state = inspect([item['container']])[0]['State']
if state['Running'] or state['ExitCode'] != 0:
raise RuntimeError('API did not stop gracefully')
result = {**item, 'stopped_at_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),
'stop_seconds':round(time.monotonic()-started,4), 'exit_code':state['ExitCode'], 'left_stopped':True}
(ROOT/'evidence/last-stop.json').write_text(json.dumps(result,indent=2)+'\n')
return result
def restart():
compose('stop','api','worker','relay',timeout=60)
compose('restart','postgres','redis','minio','broker','openbao','collector','prometheus','loki','tempo','grafana',timeout=60)
command(['python3','scripts/bao_operator.py','unseal'],timeout=70)
compose('restart','redis-tls','broker-tls','collector-tls','prometheus-tls','loki-tls','tempo-tls',timeout=30)
compose('up','-d','--no-deps','--wait','--wait-timeout','90','api','worker','relay',timeout=100)
compose('restart','lb',timeout=15)
return wait_cluster(2,timeout=30)
def front_address(container):
networks = inspect([container])[0]['NetworkSettings']['Networks']
return next(value['IPAddress'] for name,value in networks.items() if name.endswith('_front'))
def replace_one(container):
before = set(container_ids('api'))
if container not in before or len(before) != 2:
raise RuntimeError('Replacement expects exactly two running API containers')
old_address = front_address(container)
# Start-first ensures a genuinely different IP while the old address is still occupied.
compose('up','-d','--no-deps','--no-recreate','--scale','api=3','api')
expanded = set(container_ids('api'))
added = expanded-before
if len(added) != 1 or not before.issubset(expanded):
raise RuntimeError('Start-first step unexpectedly changed an existing container')
replacement = added.pop()
wait_healthy(replacement)
new_address = front_address(replacement)
if new_address == old_address:
raise RuntimeError('Replacement did not get a different IP')
expected_three = {item['instance'] for item in replicas()}
if set(wait_cluster(3)) != expected_three:
raise RuntimeError('Load balancer did not discover all three live addresses')
command(['docker','stop','--time','7',container],timeout=10)
state = inspect([container])[0]['State']
if state['ExitCode'] != 0:
raise RuntimeError('Old release did not terminate gracefully')
command(['docker','rm',container])
compose('up','-d','--no-deps','--no-recreate','--scale','api=2','api')
after = set(container_ids('api'))
if after != (before-{container}) | {replacement}:
raise RuntimeError('Sequential replacement changed the wrong containers')
expected = {item['instance'] for item in replicas()}
if set(wait_cluster(2)) != expected:
raise RuntimeError('Unexpected final backend aliases')
return {'old_container':container,'new_container':replacement,
'old_ip':old_address,'new_ip':new_address,'dns_discovered_new_address':True,
'instances_during_start_first':sorted(expected_three),
'observed_instances':sorted(expected),'old_exit_code':state['ExitCode']}
def main():
parser = argparse.ArgumentParser()
parser.add_argument('action',choices=['wait','snapshot','stop-one','restart','rolling','exec'])
parser.add_argument('arguments',nargs=argparse.REMAINDER)
args = parser.parse_args()
if args.action == 'wait':
print(json.dumps({'instances':wait_cluster()}))
elif args.action == 'snapshot':
print(json.dumps(snapshot(),indent=2))
elif args.action == 'stop-one':
print(json.dumps(stop_one(os.environ['TARGET_INSTANCE_ID'])))
elif args.action == 'exec':
ids = container_ids('api')
if not ids or not args.arguments:
raise RuntimeError('A live API container and command are required')
raise SystemExit(subprocess.call(['docker','exec',ids[0],*args.arguments],cwd=ROOT))
elif args.action == 'restart':
print(json.dumps({'instances':restart()}))
else:
compose('run','--rm','--no-deps','migrate')
print(json.dumps([replace_one(item['container']) for item in replicas()],indent=2))
if __name__ == '__main__':
main()
+28
View File
@@ -0,0 +1,28 @@
"""Operator migration phase only; application roles cannot create/alter database objects."""
import json
from pathlib import Path
import psycopg
from psycopg import sql
from messenger.db import setting
def main():
values=json.loads(Path('/operator/db-roles.json').read_text())
with psycopg.connect(setting('DATABASE_URL')) as conn:
for role,password in values.items():
if not conn.execute('SELECT 1 FROM pg_roles WHERE rolname=%s',(role,)).fetchone():
conn.execute(sql.SQL('CREATE ROLE {} LOGIN').format(sql.Identifier(role)))
conn.execute(sql.SQL('ALTER ROLE {} PASSWORD {} NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION').format(sql.Identifier(role),sql.Literal(password)))
conn.execute(sql.SQL('GRANT CONNECT ON DATABASE messenger TO {}').format(sql.Identifier(role)))
conn.execute(sql.SQL('GRANT USAGE ON SCHEMA public TO {}').format(sql.Identifier(role)))
api=['users','chats','chat_members','messages','sessions','idempotency_records','attachments','message_attachments','attachment_jobs','job_outbox','auth_rate_limits']
conn.execute(sql.SQL('GRANT SELECT,INSERT,UPDATE,DELETE ON {} TO db_api').format(sql.SQL(',').join(map(sql.Identifier,api))))
for role in ['db_worker','db_relay']:
conn.execute(sql.SQL('GRANT SELECT,UPDATE ON attachments,attachment_jobs,job_outbox TO {}').format(sql.Identifier(role)))
conn.execute('GRANT SELECT,INSERT ON job_replays TO db_worker')
conn.execute('GRANT USAGE,SELECT ON SEQUENCE job_replays_id_seq TO db_worker')
conn.execute('REVOKE CREATE ON SCHEMA public FROM PUBLIC')
print('Least privilege DB roles ready')
if __name__=='__main__': main()
+184
View File
@@ -0,0 +1,184 @@
#!/usr/bin/env python3
"""Operator-profile audit of real TLS boundaries and backend permissions."""
import io
import json
import socket
import ssl
import time
import urllib.request
import urllib.error
from pathlib import Path
from urllib.parse import urlsplit
import boto3
from botocore.config import Config
from redis import Redis
import psycopg
VALUES=json.loads(Path('/operator/workloads.json').read_text())
RESULT={}
def context(role=None,foreign=False):
ctx=ssl.create_default_context(cafile='/trust/ca.crt')
if role:
root=Path('/foreign') if foreign else Path('/identities')/role
ctx.load_cert_chain(str(root/'tls.crt'),str(root/'tls.key'))
return ctx
def http(host,port,path='/',role=None,method='GET',body=b'',foreign=False,ip=None):
sock=None
try:
raw=socket.create_connection((ip or host,port),timeout=3)
sock=context(role,foreign).wrap_socket(raw,server_hostname=host)
headers=(method+' '+path+' HTTP/1.1\r\nHost: '+host+'\r\nConnection: close\r\nContent-Type: application/x-protobuf\r\nContent-Length: '+str(len(body))+'\r\n\r\n').encode()
sock.sendall(headers+body)
data=b''
while True:
chunk=sock.recv(65536)
if not chunk: break
data+=chunk
if len(data)>2*1024*1024: break
line=data.split(b'\r\n')[0]
code=int(line.split()[1]) if line.startswith(b'HTTP/') else 0
return code,data
except (OSError,ssl.SSLError,ValueError): return 0,b''
finally:
if sock: sock.close()
def require(condition,message):
if not condition: raise AssertionError(message)
def internal_mtls():
addresses=sorted({r[4][0] for r in socket.getaddrinfo('api',9443,type=socket.SOCK_STREAM)})
api=[]
for ip in addresses:
good=http('api',9443,'/health/ready','lb',ip=ip)[0]
bad=[http('api',9443,'/health/ready',role,foreign=foreign,ip=ip)[0] for role,foreign in [(None,False),('lb',True),('intruder',False)]]
require(good==200 and all(v!=200 for v in bad),'API mTLS allow/deny failed')
try:
with socket.create_connection((ip,8080),timeout=.3): bypass=True
except OSError: bypass=False
require(not bypass,'API loopback plaintext bypass')
api.append({'allowed':good,'missing_foreign_wrong_identity':bad,'plaintext_bypass':bypass})
require(len(api)==2,'Expected two independently protected API replicas')
collector={}
for role in ['api','worker','relay']:
code=http('collector',4319,'/v1/traces',role,'POST')[0]
require(code==200,'Collector rejected valid '+role)
collector[role]=code
bad=[http('collector',4319,'/v1/traces',role,'POST',foreign=foreign)[0] for role,foreign in [(None,False),('api',True),('intruder',False)]]
require(all(v!=200 for v in bad),'Collector accepted unauthorized identity')
RESULT['api_mtls']={'replicas':api}
RESULT['collector_mtls']={'allow':collector,'deny':bad}
def redis_client(role,workload,port=None,foreign=False):
url=VALUES[workload]['BROKER_URL']
parts=urlsplit(url)
root=Path('/foreign') if foreign else Path('/identities')/role
return Redis(host=parts.hostname,port=port or parts.port,username=parts.username,password=parts.password,
ssl=True,ssl_ca_certs='/trust/ca.crt',ssl_certfile=str(root/'tls.crt'),ssl_keyfile=str(root/'tls.key'),
ssl_check_hostname=True,socket_connect_timeout=2,socket_timeout=2,decode_responses=True)
def denied(call):
try: call();return False
except Exception: return True
def broker_acl():
producer=redis_client('api','api');consumer=redis_client('worker','worker')
require(producer.ping() and consumer.ping(),'Valid broker role failed')
require(denied(lambda:producer.xreadgroup('image-workers','audit',{'attachment-jobs':'>'},count=1,block=1)),'Producer can consume')
require(denied(lambda:consumer.xadd('attachment-jobs',{'payload':'unauthorized'})),'Consumer can publish')
require(denied(lambda:redis_client('api','worker',6380).ping()),'Consumer AUTH accepted on producer listener')
require(denied(lambda:redis_client('api','worker',6381).ping()),'API identity accepted on consumer listener')
for foreign,role in [(False,'intruder'),(True,'api')]:
require(denied(lambda:redis_client(role,'api',foreign=foreign).ping()),'Unauthorized broker TLS identity')
# No cert at all must also fail before RESP authorization.
parts=urlsplit(VALUES['api']['BROKER_URL'])
missing=Redis(host='broker',port=6380,username=parts.username,password=parts.password,ssl=True,
ssl_ca_certs='/trust/ca.crt',ssl_check_hostname=True,socket_connect_timeout=2,socket_timeout=2)
require(denied(missing.ping),'Broker accepted missing client cert')
producer.close();consumer.close();missing.close()
RESULT['broker_mtls_acl']={'producer_consumer_ping':True,'producer_consume_denied':True,'consumer_publish_denied':True,'cross_listener_auth_denied':True,'missing_foreign_wrong_identity_denied':True}
parts=urlsplit(VALUES['api']['CACHE_URL'])
cache=Redis.from_url(VALUES['api']['CACHE_URL'],ssl_ca_certs='/trust/ca.crt',ssl_certfile='/identities/api/tls.crt',ssl_keyfile='/identities/api/tls.key',ssl_check_hostname=True,socket_timeout=2,socket_connect_timeout=2)
cache.set('user:audit','synthetic',ex=5);require(cache.get('user:audit')==b'synthetic','Cache read/write failed')
require(denied(lambda:cache.get('private:outside-prefix')),'Cache prefix ACL missing')
require(denied(cache.flushdb),'Cache admin permission granted')
cache.close();RESULT['cache_tls_acl']={'allowed_profile':True,'outside_prefix_denied':True,'flushdb_denied':True}
def backend_boundaries():
for host,path in [('loki','/ready'),('tempo','/ready'),('prometheus','/-/ready')]:
deadline=time.monotonic()+90
while True:
code=http(host,9443,path,'grafana')[0]
if code==200 or time.monotonic()>=deadline: break
time.sleep(.5)
require(code==200,'Grafana datasource TLS failed '+host+' status='+str(code))
require(http(host,9443,path,'worker')[0]!=200,'Worker can query telemetry backend')
require(http('loki',9443,'/loki/api/v1/push','grafana','POST')[0]==403,'Grafana can ingest logs')
require(http('collector',9465,'/metrics','prometheus')[0]==200,'Scrape TLS failed')
require(http('collector',9465,'/metrics','intruder')[0]!=200,'Arbitrary scrape allowed')
for host,port in [('redis',6379),('broker',6379),('collector',4318),('collector',9464),('collector',8888),('loki',3100),('tempo',3200),('tempo',4317),('prometheus',9090)]:
try:
with socket.create_connection((host,port),timeout=.3): bypass=True
except OSError: bypass=False
require(not bypass,'Plaintext bypass '+host+':'+str(port))
RESULT['telemetry_tls']={'grafana_queries':True,'grafana_post_denied':True,'worker_queries_denied':True,'scrape_identity_checked':True,'plaintext_bypasses':False}
def bao_policies():
for role in ('api','worker','relay'):
def call(path,body=None,token=None):
headers={'Content-Type':'application/json'}
if token:headers['X-Vault-Token']=token
req=urllib.request.Request('https://openbao:8200/v1/'+path,data=None if body is None else json.dumps(body).encode(),headers=headers)
with urllib.request.urlopen(req,context=context(role),timeout=3) as response:return json.load(response)
auth=call('auth/cert/login',{'name':role})['auth'];token=auth['client_token']
values=call('secret/data/'+role,token=token)['data']['data']
require('DATABASE_URL' in values and auth['lease_duration']<=60,'Scoped credentials/TTL failed')
other='worker' if role=='api' else 'api'
require(denied(lambda:call('secret/data/'+other,token=token)),'Bao cross-role read allowed')
require(denied(lambda:call('sys/policies/acl/evil',{'policy':'path "*" { capabilities=["sudo"] }'},token)),'Bao policy mutation allowed')
require(denied(lambda:call('auth/cert/login',{'name':other})),'Certificate can impersonate another Bao role')
RESULT['openbao']={'cert_auth':True,'token_ttl_seconds_max':60,'cross_path_policy_write_impersonation_denied':True}
def pg_s3():
values=VALUES['api']
# URL embeds /trust path and verify-full; values stay inside operator helper.
with psycopg.connect(values['DATABASE_URL'],connect_timeout=3) as conn:
encrypted=conn.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()[0]
require(encrypted,'DB not TLS')
require(conn.execute('SELECT NOT rolsuper FROM pg_roles WHERE rolname=current_user').fetchone()[0],'API DB superuser')
plain=values['DATABASE_URL'].split('?')[0]+'?sslmode=disable'
require(denied(lambda:psycopg.connect(plain,connect_timeout=2)),'Plaintext PostgreSQL accepted')
with psycopg.connect(VALUES['worker']['DATABASE_URL'],connect_timeout=3) as conn:
require(denied(lambda:conn.execute('SELECT password_hash FROM users LIMIT 1')),'Worker reads password hashes')
def s3(role):
v=VALUES[role]
return boto3.client('s3',endpoint_url='https://minio:9000',region_name='us-east-1',verify='/trust/ca.crt',
aws_access_key_id=v['S3_ACCESS_KEY_ID'],aws_secret_access_key=v['S3_SECRET_ACCESS_KEY'],
config=Config(signature_version='s3v4',connect_timeout=2,read_timeout=2,retries={'total_max_attempts':1},s3={'addressing_style':'path'}))
api=s3('api');worker=s3('worker');bucket='messenger-attachments'
api.list_objects_v2(Bucket=bucket,Prefix='originals/',MaxKeys=1)
require(denied(lambda:api.put_object(Bucket=bucket,Key='variants/audit-forbidden',Body=b'x')),'API can publish final variant')
require(denied(lambda:worker.put_object(Bucket=bucket,Key='staging/audit-forbidden',Body=b'x')),'Worker can replace staging')
require(denied(lambda:api.list_objects_v2(Bucket=bucket,Prefix='outside/')),'S3 prefix ACL missing')
require(denied(lambda:urllib.request.urlopen('https://minio:9000/'+bucket+'/originals/unknown',context=context(),timeout=2)),'Anonymous S3 accepted')
RESULT['postgres_s3']={'verify_full_tls':True,'pg_plaintext_rejected':True,'worker_hash_read_denied':True,'api_final_write_denied':True,'worker_staging_write_denied':True,'outside_prefix_anonymous_denied':True}
def main():
internal_mtls();broker_acl();backend_boundaries();bao_policies();pg_s3()
RESULT['result']='PASS';print(json.dumps(RESULT,indent=2),flush=True)
if __name__=='__main__':main()
Executable
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env python3
"""Local operator-owned PKI; keys never enter the build context or Git."""
import argparse
import json
import os
from pathlib import Path
import secrets
import subprocess
ROOT=Path(__file__).resolve().parents[1]
BASE=ROOT/'secrets'
ROLES=['lb','api','worker','relay','minio','broker','redis','collector','prometheus','loki','tempo','grafana','openbao','postgres','operator','intruder']
def run(*args):
subprocess.run(['openssl',*map(str,args)],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE)
def issue(role,ca=None,output=None,days=1):
ca=ca or BASE/'operator'
path=output or BASE/'pki'/role
path.mkdir(parents=True,exist_ok=True)
path.chmod(0o755)
for file in path.iterdir():
if file.is_file(): file.chmod(0o600)
aliases=[role]
if role in ('lb','grafana','openbao','loki','tempo','prometheus'): aliases+=['localhost']
extra=path/'extensions.cnf'
extra.write_text('basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName='+','.join('DNS:'+alias for alias in aliases)+'\n')
run('req','-new','-newkey','rsa:2048','-nodes','-subj','/CN='+role,'-keyout',path/'tls.key','-out',path/'request.csr')
serial=secrets.randbits(120)
run('x509','-req','-in',path/'request.csr','-CA',ca/'ca.crt','-CAkey',ca/'ca.key','-set_serial',str(serial),'-days',str(days),'-sha256','-extfile',extra,'-out',path/'tls.crt')
(path/'request.csr').unlink();extra.unlink()
for file in path.iterdir(): file.chmod(0o444)
return format(serial,'X')
def bootstrap():
os.umask(0o077)
operator=BASE/'operator';operator.mkdir(parents=True,exist_ok=True)
trust=BASE/'trust';trust.mkdir(parents=True,exist_ok=True);trust.chmod(0o755)
existing=(operator/'ca.crt').exists()
text=subprocess.check_output(['openssl','x509','-in',str(operator/'ca.crt'),'-noout','-text']) if existing else b''
new_ca=not existing or b'Key Usage' not in text
if new_ca:
config=operator/'ca.cnf'
config.write_text('[req]\ndistinguished_name=dn\nx509_extensions=ca\n[dn]\n[ca]\nbasicConstraints=critical,CA:TRUE\nkeyUsage=critical,keyCertSign,cRLSign\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid:always\n')
if not (operator/'ca.key').exists(): run('genrsa','-out',operator/'ca.key','3072')
run('req','-x509','-key',operator/'ca.key','-days','30','-sha256','-subj','/CN=lab7-local-ca','-config',config,'-out',operator/'ca.crt')
if (trust/'ca.crt').exists(): (trust/'ca.crt').chmod(0o600)
(trust/'ca.crt').write_bytes((operator/'ca.crt').read_bytes());(trust/'ca.crt').chmod(0o444)
if not (trust/'revoked.json').exists():
(trust/'revoked.json').write_text('[]\n');(trust/'revoked.json').chmod(0o444)
for role in ROLES:
leaf=BASE/'pki'/role/'tls.crt'
leaf_text=subprocess.check_output(['openssl','x509','-in',str(leaf),'-noout','-text']) if leaf.exists() else b''
expiring=leaf.exists() and subprocess.run(['openssl','x509','-in',str(leaf),'-noout','-checkend','3600'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode!=0
if new_ca or b'Authority Key Identifier' not in leaf_text or expiring: issue(role)
# Untrusted CA is used only by negative tests; its keys remain operator-owned.
foreign=operator/'foreign';foreign.mkdir(exist_ok=True)
foreign_cert=foreign/'leaf/tls.crt'
foreign_expiring=not foreign_cert.exists() or subprocess.run(['openssl','x509','-in',str(foreign_cert),'-noout','-checkend','3600'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode!=0
if not (foreign/'ca.key').exists() or foreign_expiring:
for file in [foreign/'ca.key',foreign/'ca.crt']:
if file.exists(): file.chmod(0o600)
run('req','-x509','-newkey','rsa:2048','-nodes','-days','2','-sha256','-subj','/CN=foreign-test-ca','-keyout',foreign/'ca.key','-out',foreign/'ca.crt')
issue('lb',foreign,foreign/'leaf')
operator.chmod(0o700)
print('Local CA/role certificates ready; private values hidden.')
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--rotate',choices=ROLES);args=parser.parse_args()
if args.rotate:
path=BASE/'pki'/args.rotate
old=BASE/'operator'/('old-'+args.rotate);old.mkdir(exist_ok=True)
for name in ('tls.crt','tls.key'):
if (old/name).exists(): (old/name).chmod(0o600)
(old/name).write_bytes((path/name).read_bytes())
raw=subprocess.check_output(['openssl','x509','-in',str(path/'tls.crt'),'-noout','-serial'],text=True)
revoked=BASE/'trust/revoked.json';values=json.loads(revoked.read_text());values.append(raw.strip().split('=')[1].upper().lstrip('0'))
revoked.chmod(0o600);revoked.write_text(json.dumps(values)+'\n');revoked.chmod(0o444)
# Existing mounted directory sees replacements; leaf files need no image rebuild.
for name in ('tls.crt','tls.key'): (path/name).chmod(0o600)
issue(args.rotate)
print('Rotated leaf; previous serial revoked for new gateway connections.')
else: bootstrap()
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
exec python3 scripts/cluster.py restart
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
"""Sanitized container privileges/ports/mount proof; never dump environment or secret values."""
import json
from pathlib import Path
import subprocess
ROOT=Path(__file__).resolve().parents[1]
ids=subprocess.check_output(['docker','compose','ps','-aq'],cwd=ROOT,text=True).split()
state=json.loads(subprocess.check_output(['docker','inspect',*ids],text=True))
items=[]
for value in state:
h=value['HostConfig'];c=value['Config'];role=c['Labels']['com.docker.compose.service']
mounts=[m['Destination'] for m in value['Mounts']]
assert not h['Privileged'] and h['NetworkMode']!='host' and not any('docker.sock' in m for m in mounts)
if role in ('api','worker','relay'):
assert c['User'] not in ('','0','root','0:0') and h['ReadonlyRootfs']
assert 'ALL' in h.get('CapDrop',[]) and 'no-new-privileges:true' in h.get('SecurityOpt',[])
assert not any('/operator' in m or 'minio_root' in m or 'database_url' in m for m in mounts)
items.append({'service':role,'image':c['Image'],'image_id':value['Image'],'state':value['State']['Status'],
'user':c['User'],'read_only':h['ReadonlyRootfs'],'cap_drop':h.get('CapDrop'), 'cap_add':h.get('CapAdd'),
'security_opt':h.get('SecurityOpt'),'memory_bytes':h['Memory'],'nano_cpus':h['NanoCpus'],
'ports':h['PortBindings'],'mount_targets':mounts,'network_mode':h['NetworkMode']})
assert not subprocess.check_output(['git','ls-files','secrets'],cwd=ROOT,text=True).strip()
ignored=subprocess.run(['git','check-ignore','secrets/operator/ca.key','secrets/operator/bao-init.json'],cwd=ROOT,capture_output=True,text=True)
assert ignored.returncode==0
result={'result':'PASS','root_operator_material_not_mounted_in_workloads':True,'no_tracked_secrets':True,'containers':items}
(ROOT/'evidence/runtime-hardening.json').write_text(json.dumps(result,indent=2)+'\n')
print('PASS: runtime-hardening.json')
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env python3
"""Scan the fully pinned app environment in an isolated, secret-free tool container."""
import os
from pathlib import Path
import subprocess
ROOT=Path(__file__).resolve().parents[1]
subprocess.run(['docker','build','-f','infra/security/audit.Dockerfile','-t','mtusi-lab7-audit:2.9.0','.'],cwd=ROOT,check=True)
subprocess.run(['docker','run','--rm','--user',str(os.getuid())+':'+str(os.getgid()),'--read-only','--cap-drop','ALL',
'--security-opt','no-new-privileges','--tmpfs','/tmp:rw,nosuid,size=128m,mode=1777',
'-v',str(ROOT/'requirements.lock')+':/requirements.lock:ro','-v',str(ROOT/'evidence')+':/out','mtusi-lab7-audit:2.9.0'],check=True)
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env python3
"""Scan a local image archive without mounting the Docker socket into a scanner."""
import os
from pathlib import Path
import subprocess
import tempfile
ROOT=Path(__file__).resolve().parents[1]
with tempfile.TemporaryDirectory(prefix='lab7-image-scan-') as directory:
archive=Path(directory)/'image.tar'
cache=Path(directory)/'cache';cache.mkdir()
temporary=Path(directory)/'tmp';temporary.mkdir()
subprocess.run(['docker','save','--output',str(archive),'mtusi-lab7-api:lab7'],check=True)
subprocess.run(['docker','run','--rm','--user',str(os.getuid())+':'+str(os.getgid()),'--read-only',
'--cap-drop','ALL','--security-opt','no-new-privileges','--memory','1g','--cpus','1','-v',str(temporary)+':/tmp',
'-v',str(cache)+':/cache',
'-v',str(archive)+':/image.tar:ro','-v',str(ROOT/'evidence')+':/out','aquasec/trivy:0.62.1',
'--quiet','image','--parallel','1','--input','/image.tar','--cache-dir','/cache','--skip-java-db-update','--scanners','vuln',
'--format','json','--output','/out/image-scan.json'],check=True)
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
exec python3 scripts/cluster.py stop-one
+462
View File
@@ -0,0 +1,462 @@
#!/usr/bin/env python3
"""Grade4 distributed acceptance through the only public entry point; no tokens in artifacts."""
import argparse
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor
import uuid
import cluster
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client as PublicClient, Failure, check
class Client(PublicClient):
def __init__(self,*args,**kwargs):
kwargs.setdefault("base_url","https://localhost:8443")
kwargs.setdefault("ca_file",str(ROOT/"secrets/trust/ca.crt"))
super().__init__(*args,**kwargs)
from resilience import history
def save(name, value):
(ROOT/'evidence'/name).write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n')
print('PASS:', name)
def percentiles(values):
values = sorted(values)
return {name:round(1000*values[max(0,math.ceil(p*len(values))-1)],3) if values else None
for name,p in [('p50',.50),('p95',.95),('p99',.99)]}
class Traffic:
def __init__(self, concurrency=4):
self.c = Client(timeout=6)
self.alice,self.bob,_,self.chat = self.c.bootstrap()
self.concurrency = concurrency
self.done = threading.Event()
self.lock = threading.Lock()
self.attempts = []
self.confirmed = {}
self.prefix = uuid.uuid4().hex
def worker(self, number):
client = Client(timeout=6)
index = 0
while not self.done.is_set():
text = self.prefix+'-'+str(number)+'-'+str(index)
key = self.prefix+'-'+str(number)+'-'+str(index)
started = time.monotonic()
try:
response = client.message(self.alice,self.chat,text,key=key)
row = response['json']
attempt = {'started':started,'ended':time.monotonic(),'ok':True,
'latency':response['elapsed'],'instance':response['headers']['X-Instance-Id']}
with self.lock:
self.confirmed[row['id']] = row
index += 1
except Failure:
# Only idempotent message POST is retried, with its original body and key.
attempt = {'started':started,'ended':time.monotonic(),'ok':False,'instance':None}
time.sleep(0.02)
with self.lock:
self.attempts.append(attempt)
def start(self):
self.started = time.monotonic()
self.pool = ThreadPoolExecutor(max_workers=self.concurrency)
self.futures = [self.pool.submit(self.worker,n) for n in range(self.concurrency)]
return self
def stop(self):
self.done.set()
for future in self.futures:
future.result(timeout=10)
self.pool.shutdown()
self.ended = time.monotonic()
def summary(self, start=None, end=None):
start = self.started if start is None else start
end = getattr(self,'ended',time.monotonic()) if end is None else end
with self.lock:
attempts = [a for a in self.attempts if start <= a['started'] < end]
success = [a for a in attempts if a['ok']]
duration = end-start
return {'seconds':round(duration,4),'concurrency':self.concurrency,
'successful_requests':len(success),'failed_attempts':len(attempts)-len(success),
'successful_rps':round(len(success)/duration,3),
'error_ratio':round((len(attempts)-len(success))/len(attempts),6) if attempts else 0,
'successful_latency_ms':percentiles([a['latency'] for a in success]),
'instances':sorted({a['instance'] for a in success})}
def verify_data(self):
rows = history(self.c,self.bob,self.chat)
actual = {row['id']:row for row in rows}
check(len(actual)==len(rows),'duplicated message ids')
check(len({row['text'] for row in rows})==len(rows),'retry duplicated a message')
check(all(actual.get(mid)==row for mid,row in self.confirmed.items()),'confirmed message lost or changed')
return {'confirmed_unique_messages':len(self.confirmed), 'history_messages':len(rows),
'confirmed_preserved':True, 'duplicate_ids':0, 'duplicate_texts':0}
def concurrent_replay():
cluster.wait_cluster()
c = Client()
alice,bob,_,chat = c.bootstrap()
key = uuid.uuid4().hex
barrier = threading.Barrier(8)
def send(_):
local = Client()
barrier.wait()
return local.message(alice,chat,'Один результат через разные процессы',key=key)
with ThreadPoolExecutor(max_workers=8) as pool:
results = list(pool.map(send,range(8)))
instances = {r['headers']['X-Instance-Id'] for r in results}
check(len(instances)>=2,'concurrent retry did not reach different API processes')
check(all(r['json']==results[0]['json'] for r in results),'concurrent key returned different messages')
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=alice,
body={'text':'Другой body'},headers={'Idempotency-Key':key})
check(history(c,bob,chat)==[results[0]['json']],'repeated key created duplicates')
save('concurrent-idempotency.json',{'result':'PASS','parallel_requests':8,'observed_instances':sorted(instances),
'responses_201':8,'messages_created':1,'different_body_status':409})
def verify_persistence():
before = cluster.snapshot()
result = subprocess.run([sys.executable,'tests/resilience.py','--mode','persistence','--action-script','scripts/restart.sh','--base-url','https://localhost:8443','--ca-file',str(ROOT/'secrets/trust/ca.crt')],
cwd=ROOT,check=True,capture_output=True,text=True,timeout=190)
after = cluster.snapshot()
roles = ['api','postgres','redis','minio','broker','relay','worker','lb']
# Compose may replace stateless workers after a rolling image update.
# Verify each named service process restarted and each persistent volume survived.
previous = {(item['service'],item['name']):item for item in before if item['service'] in roles}
current = {(item['service'],item['name']):item for item in after if item['service'] in roles}
check(previous.keys()==current.keys(),'restart changed the service/replica set')
for key,item in current.items():
old = previous[key]
check(old['started_at']!=item['started_at'],'service did not restart: '+item['service'])
check(old['volumes']==item['volumes'],'volume identities changed')
(ROOT/'evidence/persistence.txt').write_text(result.stdout)
save('persistence.json',{'result':'PASS','before':before,'after':after,'public_test':result.stdout.strip()})
def public_failover():
cluster.wait_cluster()
try:
result = subprocess.run([sys.executable,'tests/resilience.py','--mode','failover','--action-script','scripts/stop-one.sh','--base-url','https://localhost:8443','--ca-file',str(ROOT/'secrets/trust/ca.crt')],
cwd=ROOT,check=True,capture_output=True,text=True,timeout=100)
(ROOT/'evidence/public-failover.txt').write_text(result.stdout)
save('public-failover.json',{'result':'PASS','public_test':result.stdout.strip(),
'stopped':json.loads((ROOT/'evidence/last-stop.json').read_text())})
finally:
cluster.compose('up','-d','--no-recreate','--wait','--wait-timeout','90')
cluster.wait_cluster()
def reject_new_connection(survivor, address):
code = '''import json,socket,sys
try:
s=socket.create_connection((sys.argv[1],9443),timeout=1)
except OSError as exc:
print(json.dumps({'accepted':False,'error_type':type(exc).__name__}))
else:
s.close()
print(json.dumps({'accepted':True}))
'''
return json.loads(cluster.command(['docker','exec',survivor,'python','-c',code,address]))
def failover_each():
cluster.wait_cluster()
originals = cluster.replicas()
check(len(originals)==2,'two running replicas required')
traffic = Traffic().start()
phases = []
try:
time.sleep(3)
baseline_end = time.monotonic()
baseline = traffic.summary(end=baseline_end)
for original in originals:
# Alias changes on restart, so resolve the current process of this exact container.
current = next(r for r in cluster.replicas() if r['container']==original['container'])
all_before = cluster.inspect([current['container']])[0]
address = next(v['IPAddress'] for k,v in all_before['NetworkSettings']['Networks'].items() if k.endswith('_front'))
survivor = next(r['container'] for r in cluster.replicas() if r['container']!=current['container'])
read_path = '/api/v1/chats/'+traffic.chat['id']+'/messages?limit=1'
marker = traffic.c.call('GET',read_path,actor=traffic.bob,schema='MessagePage')['json']['items'][0]
start = time.monotonic()
try:
env = {**os.environ,'TARGET_INSTANCE_ID':current['instance']}
subprocess.run(['scripts/stop-one.sh'],cwd=ROOT,env=env,check=True,capture_output=True,text=True,timeout=10)
stop_returned = time.monotonic()
stopped = json.loads((ROOT/'evidence/last-stop.json').read_text())
read_deadline = start+10
while True:
try:
read = traffic.c.call('GET',read_path,actor=traffic.bob,schema='MessagePage')
check(read['json']['items'][0]==marker,'pre-failure message unavailable during outage')
check(read['headers']['X-Instance-Id']!=current['instance'],'read served by stopped process')
read_done = time.monotonic()
break
except Failure:
check(time.monotonic()<read_deadline,'reads did not recover within10s')
time.sleep(0.1)
check(read_done-start<=10,'read recovery exceeded10s')
rejected = reject_new_connection(survivor,address)
check(not rejected['accepted'],'new connection accepted by stopped API')
time.sleep(max(0,8-(time.monotonic()-start)))
end = time.monotonic()
summary = traffic.summary(start,end)
with traffic.lock:
successful = [a for a in traffic.attempts if a['ok'] and a['started']>=start]
recent = [a for a in successful if a['started']>stop_returned]
recovery = min(a['ended'] for a in recent)-start if recent else None
after_stop = min(a['ended'] for a in recent)-stop_returned if recent else None
check(recovery is not None and recovery<=10,'post-stop writes did not recover within10s of action start')
check(len(recent)>=5 and all(a['instance']!=current['instance'] for a in recent[-5:]),'stopped alias still served requests')
phases.append({'stopped':stopped, 'traffic':summary,'post_stop_write_seconds_from_action_start':round(recovery,4),
'post_stop_write_seconds_from_stop_completion':round(after_stop,4),
'read_during_outage':{'status':200,'confirmed_message_preserved':True,
'seconds_from_action_start':round(read_done-start,4),
'seconds_from_stop_completion':round(read_done-stop_returned,4)},
'new_connection_after_stop':rejected,'stopped_remains_stopped':not cluster.inspect([current['container']])[0]['State']['Running']})
finally:
cluster.command(['docker','start',current['container']])
cluster.wait_healthy(current['container'])
cluster.wait_cluster()
time.sleep(2)
finally:
traffic.stop()
save('sequential-failover.json',{'result':'PASS','baseline':baseline,'phases':phases,
'total':traffic.summary(),'data':traffic.verify_data(),
'each_original_container_tested':len({p['stopped']['container'] for p in phases})==2})
def rolling_update():
cluster.wait_cluster()
before = cluster.replicas()
check(len(before)==2,'rolling demonstration expects two replicas')
lb_before = next(item for item in cluster.snapshot() if item['service']=='lb')
target_release = 'lab7-'+uuid.uuid4().hex[:8]
traffic = Traffic().start()
replacements = []
try:
time.sleep(3)
build_start = time.monotonic()
cluster.compose('build','--build-arg','APP_RELEASE='+target_release,'api',timeout=180)
build_end = time.monotonic()
migration_output = cluster.compose('run','--rm','--no-deps','migrate')
swap_start = time.monotonic()
for old in before:
step_start = time.monotonic()
result = cluster.replace_one(old['container'])
result['seconds'] = round(time.monotonic()-step_start,4)
replacements.append(result)
swap_end = time.monotonic()
time.sleep(3)
finally:
traffic.stop()
after = cluster.replicas()
lb_after = next(item for item in cluster.snapshot() if item['service']=='lb')
check(lb_before['container']==lb_after['container'] and lb_before['started_at']==lb_after['started_at'],'LB restarted during DNS test')
check(all(r['release']==target_release for r in after),'new release not observed on all replicas')
check(not {r['container'] for r in before}&{r['container'] for r in after},'old containers remain after replacement')
check(not {r['image_id'] for r in before}&{r['image_id'] for r in after},'image did not actually change')
save('rolling-update.json',{'result':'PASS','before':before,'after':after,'target_release':target_release,
'lb_before':lb_before,'lb_after':lb_after,'lb_not_restarted':True,
'build_seconds':round(build_end-build_start,4),'migration_output':migration_output,
'replacements':replacements,'during_replacement':traffic.summary(swap_start,swap_end),
'total':traffic.summary(),'data':traffic.verify_data(),
'change':'New image with a distinct release header; API code and schema remain compatible. Start-first: scale to3, prove new IP in DNS/LB, stop/remove one old container, return to2 with --no-recreate.'})
def database_fixture(container, data):
code = '''import json,sys,psycopg
from psycopg import sql
from messenger.db import setting
p=json.load(sys.stdin)
with psycopg.connect(setting('DATABASE_URL'),connect_timeout=3) as c:
if p['action']=='install':
c.execute(sql.SQL("CREATE FUNCTION {}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.text = {} THEN PERFORM pg_sleep(2); END IF; RETURN NEW; END $$").format(sql.Identifier(p['function']),sql.Literal(p['text'])))
c.execute(sql.SQL('CREATE TRIGGER {} BEFORE INSERT ON messages FOR EACH ROW EXECUTE FUNCTION {}()').format(sql.Identifier(p['trigger']),sql.Identifier(p['function'])))
result={'installed':True}
elif p['action']=='remove':
c.execute(sql.SQL('DROP TRIGGER IF EXISTS {} ON messages').format(sql.Identifier(p['trigger'])))
c.execute(sql.SQL('DROP FUNCTION IF EXISTS {}()').format(sql.Identifier(p['function'])))
result={'removed':True}
else:
result={'waiting':c.execute("SELECT count(*) FROM pg_stat_activity WHERE datname=current_database() AND wait_event='PgSleep' AND query LIKE 'INSERT INTO messages%%'").fetchone()[0]}
print(json.dumps(result))
'''
response = subprocess.run(['docker','compose','run','--rm','--no-deps','-T','security-audit','python','-c',code],cwd=ROOT,
input=json.dumps(data),capture_output=True,text=True,check=True,timeout=8)
return json.loads(response.stdout)
def graceful_shutdown():
cluster.wait_cluster()
nodes = cluster.replicas()
target,survivor = nodes[0],nodes[1]
address = cluster.front_address(target['container'])
c = Client()
alice,bob,_,chat = c.bootstrap()
path = '/api/v1/chats/'+chat['id']+'/messages'
marker = 'drain_'+uuid.uuid4().hex
fixture = {'function':'drain_'+uuid.uuid4().hex,'trigger':'drain_'+uuid.uuid4().hex,'text':marker}
database_fixture(survivor['container'],{**fixture,'action':'install'})
code = '''import json,sys,urllib.request,urllib.error,ssl,socket
p=json.load(sys.stdin)
ctx=ssl.create_default_context(cafile='/trust/ca.crt');ctx.load_cert_chain('/identities/lb/tls.crt','/identities/lb/tls.key')
original=socket.getaddrinfo
socket.getaddrinfo=lambda host,port,*a,**kw:original(p['address'] if host=='api' else host,port,*a,**kw)
r=urllib.request.Request('https://api:9443'+p['path'],data=json.dumps({'text':p['text']}).encode(),method='POST',headers={'Content-Type':'application/json','Authorization':'Bearer '+p['token'],'Idempotency-Key':p['key']})
try:
response=urllib.request.urlopen(r,context=ctx,timeout=6)
except urllib.error.HTTPError as exc:
response=exc
print(json.dumps({'status':response.code,'instance':response.headers.get('X-Instance-Id'),'message':json.load(response)}))
'''
request_data = {'address':address,'path':path,'text':marker,'token':alice['token'],'key':uuid.uuid4().hex}
def in_flight():
result = subprocess.run(['docker','compose','run','--rm','--no-deps','-T','security-audit','python','-c',code],cwd=ROOT,
input=json.dumps(request_data),capture_output=True,text=True,check=True,timeout=8)
return json.loads(result.stdout)
pool = ThreadPoolExecutor(max_workers=1)
future = pool.submit(in_flight)
try:
deadline = time.monotonic()+3
while not database_fixture(survivor['container'],{'action':'waiting'})['waiting']:
check(time.monotonic()<deadline and not future.done(),'did not observe an in-flight SQL request')
time.sleep(0.05)
signaled = time.monotonic()
cluster.command(['docker','kill','--signal','SIGTERM',target['container']])
deadline = signaled+1.5
while True:
rejected = reject_new_connection(survivor['container'],address)
still_running = cluster.inspect([target['container']])[0]['State']['Running']
if not rejected['accepted']:
break
check(time.monotonic()<deadline,'new TCP connections still accepted after SIGTERM')
time.sleep(0.05)
check(still_running,'connection refusal observed only after process exit, not during drain')
drained = future.result(timeout=8)
check(drained['status']==201 and drained['instance']==target['instance'],'in-flight request did not finish on signaled process')
check(drained['message']['text']==marker,'in-flight body changed')
exit_code = cluster.command(['docker','wait',target['container']],timeout=8)
elapsed = time.monotonic()-signaled
check(exit_code=='0' and elapsed<5,'SIGTERM exceeded graceful budget or exited with error')
check(history(c,bob,chat)==[drained['message']],'drained message missing or duplicated')
result = {'result':'PASS','target_container':target['container'],'target_instance':target['instance'],
'fixture':'temporary BEFORE INSERT trigger sleeps2s for one synthetic text; removed afterwards',
'in_flight_observed_in_pg_stat_activity':True,'in_flight_response':201,
'new_tcp_after_sigterm':rejected,'target_still_running_when_new_tcp_rejected':still_running,
'exit_code':int(exit_code),'shutdown_seconds_from_sigterm':round(elapsed,4),
'confirmed_message_preserved':True}
finally:
pool.shutdown(wait=True)
database_fixture(survivor['container'],{**fixture,'action':'remove'})
cluster.command(['docker','start',target['container']])
cluster.wait_healthy(target['container'])
cluster.wait_cluster()
save('graceful-shutdown.json',result)
def infrastructure():
state = cluster.snapshot()
for item in state:
check(item['memory_bytes']>0 and item['nano_cpus']>0,'resource limit missing')
ports={'lb':'8443','grafana':'3000','prometheus':'9090','loki':'3100','tempo':'3200','openbao':'8200'}
if item['service'] in ports:
for bindings in (item['published_ports'] or {}).values():
check(all(b['HostIp']=='127.0.0.1' and b['HostPort']==ports[item['service']] for b in bindings),'unexpected public/admin port')
else:
check(not item['published_ports'],'service exposed a bypass port')
check(len([r for r in state if r['service']=='api' and r['status']=='running'])==2,'expected2live replicas')
check(all(r['service']!='migrate' or r['status']=='exited' for r in state),'migration job still running')
save('infrastructure.json',{'result':'PASS','containers':state})
def dependency_failures():
c = Client(timeout=6)
actor = c.user('dependencies')
c.call('GET','/api/v1/users/me',actor=actor,schema='User')
result = {'result':'PASS'}
try:
cluster.compose('stop','-t','2','redis')
response = c.call('GET','/api/v1/users/me',actor=actor,schema='User')
check(response['json']==actor['user'] and response['elapsed']<3,
'Redis fallback failed: same_profile='+str(response['json']==actor['user'])+', seconds='+str(round(response['elapsed'],4)))
c.call('GET','/api/v1/users/me',401)
c.call('GET','/health/ready',schema='Health')
result['redis'] = {'profile_status':200,'fallback_seconds':round(response['elapsed'],4),'anonymous':401,'readiness':200}
finally:
cluster.compose('up','-d','--no-deps','redis')
cluster.compose('up','-d','--no-deps','--force-recreate','redis-tls')
import urllib.request
import urllib.error
def status(path, token=None):
headers = {'Authorization':'Bearer '+token} if token else {}
request = urllib.request.Request(c.base+path,headers=headers)
started = time.monotonic()
try:
response = urllib.request.urlopen(request,context=cluster.TLS_CONTEXT,timeout=6)
except urllib.error.HTTPError as error:
response = error
with response:
return response.code, round(time.monotonic()-started,4)
try:
cluster.compose('stop','-t','2','postgres')
code,elapsed = status('/api/v1/users/me',actor['token'])
check(code in (502,503,504) and elapsed<6,'PostgreSQL outage did not safely reject authenticated request')
anonymous,_ = status('/api/v1/users/me')
check(anonymous in (401,502,503,504),'anonymous user trusted during DB outage')
live = [cluster.probe(node['container'])['status'] for node in cluster.replicas()]
check(all(code==200 for code in live),'API process liveness depends on DB')
result['postgres'] = {'authenticated_status':code,'response_seconds':elapsed,'anonymous_status':anonymous,
'internal_api_liveness':live,'note':'Nginx-generated502/503/504 may have no API JSON/instance headers when all backends become unavailable.'}
finally:
cluster.compose('start','postgres')
cluster.wait_cluster()
c.call('GET','/api/v1/users/me',actor=actor,schema='User')
result['same_session_after_recovery'] = True
save('dependency-failures.json',result)
def verify_nginx():
state = cluster.snapshot()
lb = next(item for item in state if item['service']=='lb')
check(lb['image'].startswith('nginx:'),'load balancer must use Nginx')
cluster.command(['docker','exec',lb['container'],'nginx','-t'])
version = cluster.command(['docker','exec',lb['container'],'sh','-c','nginx -v 2>&1'])
c = Client()
response = c.call('GET','/health/ready',schema='Health')
check(response['headers'].get('Server')=='nginx','public entry point is not Nginx')
check(len(cluster.wait_cluster())==2,'Nginx must discover two replicas')
save('nginx.json',{'result':'PASS','version':version,'image':lb['image'],'public_server_header':'nginx',
'config_syntax':'PASS','observed_instances':cluster.wait_cluster()})
def main():
parser = argparse.ArgumentParser()
parser.add_argument('mode',choices=['idempotency','persistence','public-failover','failover','rolling','sigterm','dependencies','infra','nginx','all'],default='all',nargs='?')
args = parser.parse_args()
modes = {'nginx':verify_nginx,'idempotency':concurrent_replay,'persistence':verify_persistence,'public-failover':public_failover,
'failover':failover_each,'sigterm':graceful_shutdown,'rolling':rolling_update,'dependencies':dependency_failures,'infra':infrastructure}
if args.mode=='all':
for function in modes.values():
function()
else:
modes[args.mode]()
if __name__ == '__main__':
main()
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Explicit real fault injection; emits IDs/results, never session tokens."""
import json
from pathlib import Path
import subprocess
import sys
import time
import uuid
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client,check
def compose(*args):
if args and args[0]=='start': args=('up','-d','--no-deps',*args[1:])
result=subprocess.run(['docker','compose',*args],cwd=ROOT,capture_output=True,text=True,timeout=120)
if result.returncode: raise RuntimeError(result.stderr)
if args and args[0]=='restart' and 'broker' in args[1:]:
subprocess.run(['docker','compose','up','-d','--no-deps','--force-recreate','broker-tls'],cwd=ROOT,check=True,capture_output=True,text=True,timeout=30)
return result.stdout
def inside(body,**values):
script="import json,io,time\nfrom uuid import UUID\nfrom messenger.db import Database\nfrom messenger.object_store import ObjectStore\nfrom messenger.jobs import work,replay,broker_client,STREAM\nfrom psycopg.types.json import Jsonb\ndb=Database();db.open();store=ObjectStore()\nv="+repr(values)+'\n'+body+'\nprint(json.dumps(result,default=str))\nstore.close();db.close()'
proc=subprocess.run(['docker','compose','run','--rm','--no-deps','-T','security-audit','python','-'],cwd=ROOT,input=script,capture_output=True,text=True,timeout=120)
if proc.returncode: raise RuntimeError(proc.stderr)
return json.loads(proc.stdout)
def state(aid):
return inside("with db.pool.connection() as c:\n result=c.execute('SELECT a.status,a.staging_key,j.id AS job_id,j.attempt,j.lease_until,o.dispatched_at FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id JOIN job_outbox o ON o.job_id=j.id WHERE a.id=%s',(v[\"aid\"],)).fetchone()",aid=aid)
def wait_for(predicate,seconds=30):
end=time.monotonic()+seconds
while time.monotonic()<end:
result=predicate()
if result: return result
time.sleep(.2)
raise AssertionError('Condition timed out')
def ready(c,actor,att):
return c.wait_ready(actor,att)
def main():
c=Client('https://localhost:8443',str(ROOT/'secrets/trust/ca.crt'));alice,bob,_,chat=c.bootstrap()
evidence={'result':'INCOMPLETE'}
trigger=False
try:
# Durable acceptance while both relay and worker are absent: real COMMIT/publish gap.
compose('stop','worker','relay')
att,raw=c.attachment(alice,chat)
c.message(alice,chat,'',attachments=[att['id']])
c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=bob)
before=state(att['id']);check(before['dispatched_at'] is None,'outbox already published')
compose('restart','api','broker')
wait_for(lambda: subprocess.run(['python3','scripts/cluster.py','wait'],cwd=ROOT,capture_output=True).returncode==0)
c.call('GET','/api/v1/users/me',actor=alice)
compose('start','relay','worker')
meta=ready(c,bob,att)
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==raw,'original changed')
evidence['commit_publish_gap']={'accepted_status':202,'outbox_unpublished':True,'api_broker_restarted':True,'same_job_ready':state(att['id'])['job_id']==before['job_id']}
# Publisher has already confirmed acceptance, broker restart preserves unread work.
compose('stop','worker')
att2,_=c.attachment(alice,chat)
wait_for(lambda: state(att2['id'])['dispatched_at'])
compose('restart','broker')
compose('start','worker')
ready(c,bob,att2)
evidence['broker_persistence']={'unread_job_survived_restart':True}
# Delay ready COMMIT in real PostgreSQL AFTER all S3 PUTs, kill before ack.
compose('stop','worker')
target,_=c.attachment(alice,chat)
inside("with db.pool.connection() as c:\n c.execute(\"CREATE OR REPLACE FUNCTION lab5_pause_ready() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.id='\"+v['aid']+\"'::uuid AND NEW.status='ready' THEN PERFORM pg_sleep(2.5); END IF; RETURN NEW; END $$\")\n c.execute('CREATE TRIGGER lab5_pause BEFORE UPDATE ON attachments FOR EACH ROW EXECUTE FUNCTION lab5_pause_ready()')\nresult=True",aid=target['id'])
trigger=True
compose('start','worker')
victim=compose('ps','-q','worker').strip()
subprocess.run(['docker','update','--restart=no',victim],check=True,capture_output=True,text=True)
def at_commit():
return inside("with db.pool.connection() as c:\n waiting=bool(c.execute(\"SELECT 1 FROM pg_stat_activity WHERE wait_event='PgSleep' AND query LIKE 'UPDATE attachments SET status=%'\").fetchone())\n row=c.execute('SELECT object_key FROM attachments WHERE id=%s',(v['aid'],)).fetchone()\nresult=False\nif waiting:\n obj=store.get(row['object_key']);effect=obj.length>0;obj.close()\n with db.pool.connection() as c:\n still=bool(c.execute(\"SELECT 1 FROM pg_stat_activity WHERE wait_event='PgSleep' AND query LIKE 'UPDATE attachments SET status=%'\").fetchone())\n result={'s3_effect_written':effect} if still and effect else False",aid=target['id'])
# One checkpoint process verifies both S3 effect and still-active COMMIT delay.
# No second container startup is inserted between observation and SIGKILL.
observed=wait_for(at_commit)
compose('kill','-s','SIGKILL','worker')
# unless-stopped can restart a killed worker; stop it to retain the fault boundary.
compose('stop','worker')
crash_state=json.loads(subprocess.check_output(['docker','inspect','--format','{{json .State}}',victim],text=True))
check(crash_state['ExitCode']==137,'Worker SIGKILL was not observed')
inside("with db.pool.connection() as c:\n c.execute('DROP TRIGGER lab5_pause ON attachments');c.execute('DROP FUNCTION lab5_pause_ready()')\nresult=True")
trigger=False
crashed=state(target['id']);check(crashed['attempt']==1 and crashed['status']=='processing','SIGKILL missed the pre-COMMIT window')
print('Waiting for real 90s lease expiry after killed worker.',flush=True)
started=time.monotonic()
wait_for(lambda: state(target['id'])['status']=='queued',110)
compose('start','worker')
ready(c,bob,target)
after=state(target['id'])
evidence['after_put_before_ack']={**observed,'lease_recovery_seconds':round(time.monotonic()-started,3),'attempt_after_recovery':after['attempt'],'same_job':after['job_id']==crashed['job_id'],'crash_exit_code':crash_state['ExitCode']}
# Re-deliver the completed original job. Ready metadata is immutable.
original_meta=c.call('GET','/api/v1/attachments/'+target['id'],actor=alice,schema='Attachment')['json']
duplicate=inside("result=work(db,store,v['job'],1)",job=after['job_id'])
check(duplicate and c.call('GET','/api/v1/attachments/'+target['id'],actor=alice,schema='Attachment')['json']==original_meta,'duplicate changed ready result')
evidence['duplicate']={'ready_noop':True}
# Retry exhaustion with real missing staging (transient storage failure), explicit replay.
compose('stop','worker','relay')
failed,failed_raw=c.attachment(alice,chat)
st=state(failed['id'])
inside("store.delete(v['key']);result=True",key=st['staging_key'])
for attempt in range(5):
inside("with db.pool.connection() as c:\n c.execute('UPDATE attachment_jobs SET next_at=clock_timestamp() WHERE id=%s',(v['job'],))\nresult=work(db,store,v['job'])",job=st['job_id'])
failure=c.call('GET','/api/v1/attachments/'+failed['id'],actor=alice,schema='Attachment')['json']
check(failure['status']=='failed' and failure['error_code']=='retry_exhausted','retry did not terminate')
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=alice,body={'text':'','attachment_ids':[failed['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
inside("store.put(v['key'],io.BytesIO(bytes.fromhex(v['raw'])),v['length'],'image/png')\nreplay(db,v['job'],'restore synthetic staging and retry')\nresult=True",key=st['staging_key'],raw=failed_raw.hex(),length=len(failed_raw),job=st['job_id'])
compose('start','relay','worker')
ready(c,bob,failed)
evidence['retry_replay']={'failed_after':5,'code':'retry_exhausted','explicit_replay_ready':True,'failed_attachment_binding':409}
evidence['result']='PASS'
(ROOT/'evidence/jobs-faults.json').write_text(json.dumps(evidence,indent=2)+'\n')
print('PASS: jobs-faults.json')
finally:
if trigger:
inside("with db.pool.connection() as c:\n c.execute('DROP TRIGGER IF EXISTS lab5_pause ON attachments');c.execute('DROP FUNCTION IF EXISTS lab5_pause_ready()')\nresult=True")
compose('start','relay','worker')
current=compose('ps','-q','worker').strip()
if current: subprocess.run(['docker','update','--restart=unless-stopped',current],check=True,capture_output=True,text=True)
if __name__=='__main__': main()
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env python3
"""Query real backends and reproduce bounded incidents; no secret values saved."""
import json
from pathlib import Path
import subprocess
import sys
import threading
import time
import urllib.parse
import urllib.request
import uuid
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import check
from verify_cluster import Client
from verify_security import backend_get
from verify_jobs import compose,inside,wait_for,state
def get(url):
parsed=urllib.parse.urlsplit(url)
if parsed.scheme!='https' or parsed.hostname!='localhost' or parsed.port not in (9090,3100,3200):
raise ValueError('Only verified local TLS backend endpoints are allowed')
return backend_get(parsed.port,parsed.path+('?' + parsed.query if parsed.query else ''))
def query(expression):
return get('https://localhost:9090/api/v1/query?'+urllib.parse.urlencode({'query':expression}))['data']['result']
def alerts():
return get('https://localhost:9090/api/v1/alerts')['data']['alerts']
def alert_state(name,state):
rows=[a for a in alerts() if a['labels']['alertname']==name]
return any(a['state']==state for a in rows) if state=='firing' else not rows
def collect_names(trace):
names=[]
def walk(value):
if isinstance(value,dict):
if 'spanId' in value and 'name' in value: names.append(value['name'])
for item in value.values(): walk(item)
elif isinstance(value,list):
for item in value: walk(item)
walk(trace)
return names
def save(name,data):
(ROOT/'evidence'/name).write_text(json.dumps(data,indent=2)+'\n')
def main():
c=Client();alice,bob,_,chat=c.bootstrap()
report={'result':'INCOMPLETE'}
lock_process=None
try:
# Controlled retry in the same causal chain.
compose('stop','worker')
response=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=trace.png',202,
actor=alice,raw=(ROOT/'tests/fixtures/sample.png').read_bytes(),headers={'Content-Type':'image/png'},schema='Attachment')
att=response['json'];trace_id=response['headers']['X-Trace-Id']
compose('stop','minio');compose('start','worker')
wait_for(lambda: (lambda s:s['attempt']>=1 and s['status']=='queued')(state(att['id'])),30)
time.sleep(2)
compose('start','minio')
# API re-enters LB after readiness recovers.
wait_for(lambda: subprocess.run(['python3','scripts/cluster.py','wait'],cwd=ROOT,capture_output=True).returncode==0,60)
ready=c.wait_ready(bob,att)
def chain():
try:
trace=get('https://localhost:3200/api/traces/'+trace_id)
names=collect_names(trace)
return trace if names.count('attachments.consume')>=2 and all(n in names for n in ['attachments.publish','attachments.process_objects','s3.put','postgres.query']) else None
except Exception: return None
trace=wait_for(chain,60)
save('upload-trace.json',trace)
logquery='{service_name=~"messenger-.*"} |= "'+trace_id+'"'
def correlated_logs():
try:
result=get('https://localhost:3100/loki/api/v1/query_range?'+urllib.parse.urlencode({'query':logquery,'limit':100,'start':str(time.time_ns()-600_000_000_000)}))
streams=result['data']['result']
services={item['stream'].get('service_name') for item in streams}
return result if {'messenger-api','messenger-worker'}<=services else None
except Exception: return None
logs=wait_for(correlated_logs,60);save('upload-logs.json',logs)
report['trace']={'trace_id':trace_id,'span_names':collect_names(trace),'retry_attempts':state(att['id'])['attempt'],'api_worker_logs_correlated':True}
# Incident 1: worker stopped, queued age is measured by relay.
compose('stop','worker')
queued,_=c.attachment(alice,chat)
wait_for(lambda: alert_state('QueueLagGrowing','firing'),70)
save('queue-alert-firing.json',alerts())
report['queue_incident']={'oldest_age':query('max(queue_oldest_age_seconds)'),'depth':query('max(queue_depth)'),'alert':'firing'}
compose('start','worker');c.wait_ready(bob,queued)
wait_for(lambda: alert_state('QueueLagGrowing','resolved'),30)
save('queue-alert-resolved.json',alerts());report['queue_incident']['after_restore']='resolved'
# Incident 2: sessions table lock affects business auth, readiness remains healthy.
code="from messenger.db import Database;import sys;d=Database();d.open();c=d.pool.getconn();c.execute('SET statement_timeout=0');c.execute('SET idle_in_transaction_session_timeout=0');c.execute('LOCK TABLE sessions IN ACCESS EXCLUSIVE MODE');print('locked',flush=True);sys.stdin.readline();c.rollback();d.pool.putconn(c);d.close()"
lock_process=subprocess.Popen(['docker','compose','exec','-T','api','python','-c',code],cwd=ROOT,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
check(lock_process.stdout.readline().strip()=='locked','DB lock was not acquired')
failures=[]
started=time.monotonic()
while time.monotonic()-started<35:
r=c.call('GET','/api/v1/users/me',503,actor=alice)
failures.append({'status':r['status'],'elapsed':r['elapsed'],'trace_id':r['headers'].get('X-Trace-Id')})
wait_for(lambda: alert_state('HighApiErrorRate','firing'),40)
save('db-alert-firing.json',alerts())
# Release the exact test transaction by explicit rollback, then reap its process.
lock_process.communicate(input='\n',timeout=10)
check(lock_process.returncode==0,'DB lock holder did not exit cleanly')
lock_process=None
for _ in range(300): c.call('GET','/api/v1/users/me',actor=alice)
wait_for(lambda: alert_state('HighApiErrorRate','resolved'),75)
save('db-alert-resolved.json',alerts())
report['db_incident']={'failures':failures,'before':'firing','after':'resolved','pool_waiting':query('sum(db_pool_waiting)')}
# Backend outage must not affect accepted messages or grow queues beyond configuration.
before=json.loads(compose('stats','--no-stream','--format','{{json .}}','collector').strip())
compose('stop','tempo','loki')
count=0;start=time.monotonic()
while time.monotonic()-start<25:
c.message(alice,chat,'telemetry outage '+str(count),key=uuid.uuid4().hex);count+=1
if count%20==0: time.sleep(.1)
during=query('{__name__=~"otelcol_(receiver_accepted_spans|exporter_sent_spans|exporter_send_failed_spans|exporter_queue_size|exporter_queue_capacity|exporter_enqueue_failed_spans).*"}')
after=json.loads(compose('stats','--no-stream','--format','{{json .}}','collector').strip())
compose('start','tempo','loki')
compose('up','-d','--no-deps','--force-recreate','tempo-tls','loki-tls')
report['telemetry_outage']={'successful_messages':count,'seconds':round(time.monotonic()-start,3),'collector_before':before,'collector_after':after,'collector_metrics':during,'queue_limit_batches':256,'collector_limit_mib':256}
# Every provisioned dashboard expression must return a successful Prometheus response.
dashboard=json.loads((ROOT/'infra/observability/grafana/dashboards/messenger.json').read_text())
expressions=[]
for panel in dashboard['panels']:
for target in panel['targets']:
values=query(target['expr']);check(values,'No data for '+panel['title'])
expressions.append({'panel':panel['title'],'expression':target['expr'],'series':len(values)})
report['dashboard_queries']=expressions
report['result']='PASS';save('observability.json',report)
print('PASS: observability.json, traces/logs and firing/resolved alerts',flush=True)
finally:
if lock_process is not None:
if lock_process.stdin and not lock_process.stdin.closed:
lock_process.communicate(input='\n',timeout=10)
else:
lock_process.communicate(timeout=10)
compose('start','worker','minio','tempo','loki')
compose('up','-d','--no-deps','--force-recreate','tempo-tls','loki-tls')
if __name__=='__main__': main()
+182
View File
@@ -0,0 +1,182 @@
#!/usr/bin/env python3
"""Real local lifecycle/ACL/admission checks; secrets stay in memory or ignored files."""
import base64
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
from pathlib import Path
import secrets
import socket
import ssl
import subprocess
import sys
import time
import urllib.parse
import urllib.request
import urllib.error
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
sys.path.insert(0,str(ROOT/'scripts'))
from client import Client,check
from bao_operator import request as bao_request,bootstrap as bao_unseal
CA=ROOT/'secrets/trust/ca.crt'
BASE='https://localhost:8443'
def compose(*args):
return subprocess.run(['docker','compose',*args],cwd=ROOT,check=True,capture_output=True,text=True,timeout=180).stdout
def wait_for(function,seconds=40):
end=time.monotonic()+seconds
while time.monotonic()<end:
try:
value=function()
if value:return value
except Exception:pass
time.sleep(.5)
raise AssertionError('Condition did not recover in bounded time')
def inside(body,**values):
script="import json,hashlib,time,ssl,socket\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom psycopg import sql\nimport psycopg\nimport sys;sys.path.insert(0,'/audit-scripts')\nfrom matrix_audit import VALUES,context,http\nv="+repr(values)+'\n'+body+'\nprint(json.dumps(result,default=str))'
result=subprocess.run(['docker','compose','run','--rm','--no-deps','-T','security-audit','python','-'],cwd=ROOT,
input=script,capture_output=True,text=True,timeout=120)
if result.returncode:raise RuntimeError(result.stderr)
return json.loads(result.stdout)
def status(path='/api/v1/users/me',actor=None):
headers={} if actor is None else {'Authorization':'Bearer '+actor['token']}
req=urllib.request.Request(BASE+path,headers=headers)
try:r=urllib.request.urlopen(req,context=ssl.create_default_context(cafile=str(CA)),timeout=8)
except urllib.error.HTTPError as exc:r=exc
with r:return r.status
def backend_get(port,path):
ctx=ssl.create_default_context(cafile=str(CA));ctx.load_cert_chain(str(ROOT/'secrets/pki/operator/tls.crt'),str(ROOT/'secrets/pki/operator/tls.key'))
with urllib.request.urlopen(urllib.request.Request('https://localhost:'+str(port)+path,headers={'Accept':'application/json'}),context=ctx,timeout=8) as r:return json.load(r)
def save(name,data):
(ROOT/'evidence'/name).write_text(json.dumps(data,indent=2)+'\n')
def main():
c=Client(BASE,str(CA));alice,bob,eve,chat=c.bootstrap()
result={'result':'INCOMPLETE'};sealed=False;worker_stopped=False
try:
# Rehash before applying deliberate login admission pressure.
inside("from argon2 import PasswordHasher\nold=PasswordHasher(time_cost=1,memory_cost=8192,parallelism=1).hash(v['password'])\nwith psycopg.connect(VALUES['api']['DATABASE_URL']) as db:\n db.execute('UPDATE users SET password_hash=%s WHERE id=%s',(old,v['id']))\nresult=True",password=alice['registration']['password'],id=alice['id'])
login=c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+base64.b64encode((alice['registration']['username']+':'+alice['registration']['password']).encode()).decode()},schema='Session')
result['rehash']=inside("from messenger.security import HASHER\nwith psycopg.connect(VALUES['api']['DATABASE_URL']) as db:\n encoded=db.execute('SELECT password_hash FROM users WHERE id=%s',(v['id'],)).fetchone()[0]\nresult={'argon2id':encoded.startswith('$argon2id$'),'current_parameters':not HASHER.check_needs_rehash(encoded)}",id=alice['id'])
check(all(result['rehash'].values()),'Rehash failed')
c.call('GET','/api/v1/chats/'+chat['id'],404,actor=eve)
att,raw=c.attachment(alice,chat);c.wait_ready(bob,att)
for suffix in ('','/content'):c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=eve)
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',404,actor=eve,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':secrets.token_hex(8)})
me=c.call('GET','/api/v1/users/me',actor=alice,headers={'X-User-Id':eve['id']},schema='User')['json'];check(me['id']==alice['id'],'Forged identity')
result['session_hash']=inside("with psycopg.connect(VALUES['api']['DATABASE_URL']) as db:\n found=db.execute('SELECT count(*) FROM sessions WHERE token_hash=%s',(hashlib.sha256(v['token'].encode()).hexdigest(),)).fetchone()[0]\nresult={'sha256_server_session':found==1}",token=alice['token'])
# Shared account budget is checked across both API aliases.
if time.time()%10>7:time.sleep(10-time.time()%10+.1)
basic=base64.b64encode((alice['registration']['username']+':wrong-password-123').encode()).decode()
def attempt(_):
response=c.call('POST','/api/v1/auth/sessions',[401,429],headers={'Authorization':'Basic '+basic})
return {'status':response['status'],'instance':response['headers'].get('X-Instance-Id'),'retry_after':response['headers'].get('Retry-After')}
with ThreadPoolExecutor(max_workers=16) as pool:attempts=list(pool.map(attempt,range(16)))
check(any(a['status']==429 and a['retry_after'] for a in attempts),'No shared rate limit')
check(len({a['instance'] for a in attempts})==2,'Rate test did not hit both replicas')
result['shared_login_limit']={'attempts':attempts,'replicas':2,'per_account':10,'window_seconds':10,'global_kdf':120}
# Operator benchmark runs inside the actual 1 CPU API cgroup.
bench="import json,time,resource;from messenger.security import HASHER\np='synthetic-benchmark-password';h=HASHER.hash(p);values=[]\nfor _ in range(10):\n t=time.perf_counter();HASHER.verify(h,p);values.append(1000*(time.perf_counter()-t))\nprint(json.dumps({'m_kib':19456,'t':2,'p':1,'verify_ms':values,'max_verify_ms':max(values),'peak_kib':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,'local_slots_per_api':2,'replicas':2}))"
result['argon_budget']=json.loads(compose('exec','-T','api','python','-c',bench))
# Exact hostname validation, not a connection failure.
rejected=False
try:
rawsock=socket.create_connection(('localhost',8443),timeout=3)
ssl.create_default_context(cafile=str(CA)).wrap_socket(rawsock,server_hostname='wrong.example')
except ssl.SSLCertVerificationError:rejected=True
check(rejected,'Wrong ingress hostname accepted');result['wrong_hostname_rejected']=True
# Leaf rotation and application-level serial revocation on fresh connections.
before=compose('images','-q','api','lb').split()
subprocess.run(['python3','scripts/pki.py','--rotate','lb'],cwd=ROOT,check=True,capture_output=True,text=True)
old=ROOT/'secrets/operator/old-lb';old.chmod(0o755)
for file in old.iterdir():file.chmod(0o444)
compose('exec','-T','lb','nginx','-s','reload')
wait_for(lambda:status('/health/ready')==200)
code="import json,ssl,socket\nctx=ssl.create_default_context(cafile='/trust/ca.crt');ctx.load_cert_chain('/old-lb/tls.crt','/old-lb/tls.key')\naccepted=False\ntry:\n s=ctx.wrap_socket(socket.create_connection(('api',9443),timeout=3),server_hostname='api');s.sendall(b'GET /health/ready HTTP/1.1\\r\\nHost: api\\r\\nConnection: close\\r\\n\\r\\n');accepted=b'200 OK' in s.recv(4096);s.close()\nexcept (OSError,ssl.SSLError):pass\nprint(json.dumps({'revoked_old_leaf_rejected':not accepted}))"
old_test=subprocess.run(['docker','compose','run','--rm','--no-deps','-T','-v',str(old)+':/old-lb:ro','security-audit','python','-c',code],cwd=ROOT,capture_output=True,text=True,check=True)
leaf=json.loads(old_test.stdout);check(leaf['revoked_old_leaf_rejected'],'Old leaf still authorized')
result['leaf_rotation']={**leaf,'new_leaf_works':True,'image_ids_unchanged':compose('images','-q','api','lb').split()==before}
# Rotate only API DB password; deny old on a NEW connection and recreate consumers of it.
workload=ROOT/'secrets/operator/workloads.json';workload.chmod(0o600);values=json.loads(workload.read_text())
old_url=values['api']['DATABASE_URL'];old_password=urllib.parse.urlsplit(old_url).password
new_password=secrets.token_hex(24);new_url=old_url.replace(':'+old_password+'@',':'+new_password+'@')
rotation=inside("with psycopg.connect(v['old']) as db:\n db.execute(sql.SQL('ALTER ROLE db_api PASSWORD {}').format(sql.Literal(v['new_password'])))\nold_allowed=True\ntry:\n c=psycopg.connect(v['old'],connect_timeout=3);c.close()\nexcept psycopg.Error:old_allowed=False\nwith psycopg.connect(v['new'],connect_timeout=3) as db:\n ok=db.execute('SELECT current_user').fetchone()[0]=='db_api'\nresult={'old_new_connection_denied':not old_allowed,'new_connection_allowed':ok}",old=old_url,new=new_url,new_password=new_password)
values['api']['DATABASE_URL']=new_url;workload.write_text(json.dumps(values));workload.chmod(0o444)
password_file=ROOT/'secrets/db_api_password';password_file.chmod(0o600);password_file.write_text(new_password);password_file.chmod(0o444)
db_roles=ROOT/'secrets/operator/db-roles.json';db_roles.chmod(0o600);roles=json.loads(db_roles.read_text());roles['db_api']=new_password;db_roles.write_text(json.dumps(roles));db_roles.chmod(0o444)
bao_unseal()
compose('up','-d','--no-deps','--force-recreate','--wait','--wait-timeout','90','api')
wait_for(lambda:status(actor=alice)==200)
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==raw,'Rotation lost original')
check(all(rotation.values()),'DB credential rotation failed');result['secret_rotation']={**rotation,'same_session_original_preserved':True,'no_image_rebuild':True}
# Accepted work and session remain durable while OpenBao is sealed.
compose('stop','worker');worker_stopped=True
pending,pending_raw=c.attachment(alice,chat)
c.message(alice,chat,'',attachments=[pending['id']])
bao_request('PUT','sys/seal',{});sealed=True;started=time.monotonic();observed=[]
while time.monotonic()-started<75:
code=status(actor=alice);observed.append({'seconds':round(time.monotonic()-started,2),'status':code})
if code in (502,503,504):break
time.sleep(2)
check(observed[-1]['status'] in (502,503,504),'Sealed Bao did not fail closed')
live=json.loads(compose('exec','-T','api','python','-c',"import urllib.request,json;r=urllib.request.urlopen('http://127.0.0.1:8080/health/live');print(json.dumps({'status':r.status}))"))
check(live['status']==200,'Secret outage broke liveness')
bao_unseal();sealed=False
wait_for(lambda:status(actor=alice)==200)
compose('up','-d','--no-deps','worker');worker_stopped=False
c.wait_ready(bob,pending)
check(c.call('GET','/api/v1/attachments/'+pending['id']+'/content',actor=bob)['bytes']==pending_raw,'Accepted work lost across seal')
result['bao_sealed']={'polls':observed,'cache_budget_seconds_max':60,'liveness':200,'same_accepted_job_session_recovered':True}
# Positive-control telemetry and absence of a secret/body canary.
canary='private-body-canary-'+secrets.token_hex(12)
c.message(alice,chat,canary)
raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
response=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=private.png',202,actor=alice,raw=raw,headers={'Content-Type':'image/png'},schema='Attachment')
traced=response['json'];trace_id=response['headers']['X-Trace-Id'];c.wait_ready(bob,traced)
def find_trace():
value=backend_get(3200,'/api/traces/'+trace_id)
names=[]
def walk(item):
if isinstance(item,dict):
if 'spanId' in item:names.append(item.get('name'))
for v in item.values():walk(v)
elif isinstance(item,list):
for v in item:walk(v)
walk(value)
return value if {'attachments.publish','attachments.consume','s3.put','postgres.query'}<=set(names) else None
trace=wait_for(find_trace,60);save('secure-upload-trace.json',trace)
def logs(query):
args=urllib.parse.urlencode({'query':query,'limit':100,'start':str(time.time_ns()-900_000_000_000)})
return backend_get(3100,'/loki/api/v1/query_range?'+args)
positive=wait_for(lambda: (lambda x:x if {'messenger-api','messenger-worker'}<={s['stream'].get('service_name') for s in x['data']['result']} else None)(logs('{service_name=~"messenger-.*"} |= "'+trace_id+'"')),60)
save('secure-upload-logs.json',positive)
negative=logs('{service_name=~"messenger-.*"} |= "'+canary+'"')
check(not negative['data']['result'],'Message body leaked into telemetry')
result['telemetry_privacy']={'trace_id':trace_id,'api_worker_positive_control':True,'body_canary_matches':0}
# Actual logout invalidates the current server-side session.
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=eve)
c.call('GET','/api/v1/users/me',401,actor=eve)
result['acl_logout']={'outsider_metadata_content_binding':404,'forged_header_ignored':True,'logout':401}
result['result']='PASS';save('security-lifecycle.json',result)
print('PASS: security-lifecycle.json and secure trace/log proof',flush=True)
finally:
if sealed:bao_unseal()
if worker_stopped:compose('up','-d','--no-deps','worker')
if __name__=='__main__':main()