This commit is contained in:
2026-11-27 21:55:47 +03:00
parent f6882a77b4
commit b6c71fd96a
67 changed files with 3770 additions and 595 deletions
+185
View File
@@ -0,0 +1,185 @@
"""Operator-only, real network negative tests; no credentials in result files."""
import base64
import hashlib
import json
import resource
from pathlib import Path
import socket
import ssl
import statistics
import sys
import time
import uuid
import boto3
from botocore.exceptions import ClientError
import psycopg
from redis import Redis
from redis.exceptions import ResponseError
import requests
from argon2 import PasswordHasher
S=Path('/audit-secrets')
sys.path.insert(0, '/app')
CA=str(S/'ca.crt')
config=json.loads((S/'operator-private/credentials.json').read_text())
results=[]
def record(name, condition=True, **details):
assert condition, name
results.append({'test':name,'passed':True,**details})
print('PASS: '+name,flush=True)
def http(method,url,role=None,**kw):
client=requests.Session();client.trust_env=False
cert=(str(S/role/'tls.crt'),str(S/role/'tls.key')) if role else None
return client.request(method,url,verify=CA,cert=cert,timeout=8,**kw)
def tls(host,port,identity,body,hostname=None):
ctx=ssl.create_default_context(cafile=CA)
if identity: ctx.load_cert_chain(str(S/identity/'tls.crt'),str(S/identity/'tls.key'))
with socket.create_connection((host,port),timeout=3) as raw:
with ctx.wrap_socket(raw,server_hostname=hostname or host) as conn:
conn.sendall(body)
return conn.recv(8192)
def rejection(host,port,identity,body):
try: response=tls(host,port,identity,body)
except (ssl.SSLError,ConnectionResetError): response=b''
# Timeouts/refused connections are NOT accepted as proof of authorization denial.
return not response
def db(role):
return psycopg.connect(host='postgres',dbname='messenger',user=role,password=config[role]['db'],
sslmode='verify-full',sslrootcert=CA,connect_timeout=3,autocommit=True)
def redis(role,broker=False):
return Redis(host='broker' if broker else 'redis',port=6380,username=role,
password=config[role]['broker' if broker else 'redis'],ssl=True,ssl_ca_certs=CA,
ssl_check_hostname=True,ssl_certfile=str(S/role/'tls.crt') if broker else None,
ssl_keyfile=str(S/role/'tls.key') if broker else None,decode_responses=True,
socket_timeout=3,socket_connect_timeout=3)
def main():
from src.telemetry import extract, trace
start=time.perf_counter()
for _ in range(20):
extract({'traceparent':'00-'+' '*100000+'\n','tracestate':' '*100000+'x'})
record('Oversized HTTP/JSON trace context has bounded parsing cost',time.perf_counter()-start<1)
context=extract({'traceparent':'00-'+'1'*32+'-'+'2'*16+'-01'})
record('Valid trace context remains supported',trace.get_current_span(context).get_span_context().is_valid)
body=b'GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n'
ingest=b'POST /v1/traces HTTP/1.1\r\nHost: otel-collector\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}'
matrix=[('api1',8443,'lb',body),('api2',8443,'lb',body),
('broker',6380,'worker',b'*1\r\n$4\r\nPING\r\n'),('otel-collector',44318,'api',ingest)]
for host,port,allowed,payload in matrix:
record(host+' accepts allowed identity',bool(tls(host,port,allowed,payload)))
for forbidden in [None,'foreign-'+allowed,'outsider','expired-'+allowed]:
record(host+' rejects '+str(forbidden),rejection(host,port,forbidden,payload))
if host.startswith('api') and (S/'old-lb/tls.crt').exists():
record(host+' rejects revoked LB serial',rejection(host,port,'old-lb',payload))
for role in ['worker','dispatcher']:
record('Collector accepts '+role,b'200' in tls('otel-collector',44318,role,ingest))
for host,port in [('lb',8443),('redis',6380),('s3',9443),('grafana',3443),('openbao',8200)]:
ctx=ssl.create_default_context(cafile=CA)
with socket.create_connection((host,port),timeout=3) as raw:
with ctx.wrap_socket(raw,server_hostname=host) as conn:
record(host+' server TLS verified',True,protocol=conn.version())
try: tls(host,port,None,b'GET / HTTP/1.0\r\n\r\n',hostname='wrong.invalid')
except ssl.SSLCertVerificationError: record(host+' rejects wrong hostname')
else: raise AssertionError('hostname accepted')
for host,port,local,role,path in [('prometheus',19090,9090,'grafana','/-/ready'),
('loki',13100,3100,'grafana','/ready'),('tempo',13200,3200,'grafana','/ready'),
('otel-collector',18889,8889,'prometheus','/metrics'),('otel-collector',18888,8888,'prometheus','/metrics'),
('tempo',14318,4318,'otel-collector','/v1/traces')]:
payload=(f'GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n').encode()
record(f'{host}:{port} trusted identity',bool(tls(host,port,role,payload)))
record(f'{host}:{port} rejects outsider',rejection(host,port,'outsider',payload))
for host,port in [('api1',8080),('api2',8080),('broker',6379),('redis',6379),('s3',9000),
('otel-collector',4318),('otel-collector',8888),('otel-collector',8889),
('prometheus',9090),('loki',3100),('loki',9095),('tempo',3200),('tempo',4318),('tempo',9095),('grafana',3000)]:
try:
with socket.create_connection((host,port),timeout=2): pass
except ConnectionRefusedError: record(f'No plaintext bypass {host}:{port}')
else: raise AssertionError('plaintext listener exposed')
for role in ['api','worker','dispatcher','cleanup']:
with db(role) as conn:
record('PostgreSQL TLS '+role,conn.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()[0])
try: conn.execute('CREATE TABLE forbidden_probe(id int)')
except psycopg.errors.InsufficientPrivilege: record('DB no DDL '+role)
else: raise AssertionError('DDL allowed')
if role!='api':
try: conn.execute('SELECT password_hash FROM users LIMIT 1')
except psycopg.errors.InsufficientPrivilege: record('DB password hashes denied '+role)
else: raise AssertionError('password hashes exposed')
auth=http('POST','https://openbao:8200/v1/auth/cert/login',role,json={'name':role})
record('OpenBao cert auth '+role,auth.status_code==200)
token=auth.json()['auth']['client_token'];headers={'X-Vault-Token':token}
record('OpenBao short TTL '+role,0<auth.json()['auth']['lease_duration']<=60)
record('OpenBao own KV '+role,http('GET','https://openbao:8200/v1/secret/data/'+role,role,headers=headers).status_code==200)
other='worker' if role=='api' else 'api'
record('OpenBao other KV denied '+role,http('GET','https://openbao:8200/v1/secret/data/'+other,role,headers=headers).status_code==403)
record('OpenBao policy write denied '+role,http('PUT','https://openbao:8200/v1/sys/policies/acl/forbidden',role,headers=headers,json={'policy':''}).status_code==403)
record('OpenBao outsider denied',http('POST','https://openbao:8200/v1/auth/cert/login','outsider',json={'name':'api'}).status_code==400)
for role,cmd in [('api',lambda c:c.xadd('attachment-jobs',{'job':'forbidden'})),
('worker',lambda c:c.xadd('attachment-jobs',{'job':'forbidden'})),
('dispatcher',lambda c:c.xreadgroup('image-workers','forbidden',{'attachment-jobs':'>'},count=1))]:
client=redis(role,True);record('Broker authenticated '+role,client.ping())
try:cmd(client)
except ResponseError as exc: record('Broker ACL denied '+role,'permissions' in str(exc).lower() or 'noperm' in str(exc).lower())
else:raise AssertionError('broker command allowed')
for role,prefix in [('api','variants'),('worker','staging'),('cleanup','staging')]:
client=boto3.client('s3',endpoint_url='https://s3:9443',verify=CA,
aws_access_key_id=role,aws_secret_access_key=config[role]['s3'],region_name='us-east-1')
try:client.put_object(Bucket='messenger-attachments',Key=prefix+'/forbidden',Body=b'x')
except ClientError as exc:record('S3 denied write prefix '+role,exc.response['Error']['Code']=='AccessDenied')
else:raise AssertionError('S3 write allowed')
# Real rehash via the public API and a synthetic old Argon2id record.
username='rehash_'+uuid.uuid4().hex[:12];password='synthetic-'+uuid.uuid4().hex
old=PasswordHasher(time_cost=1,memory_cost=8192,parallelism=1).hash(password)
user_id=str(uuid.uuid4())
with db('api') as conn:
conn.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)',(user_id,username,'Rehash test',old))
response=http('POST','https://lb:8443/api/v1/auth/sessions',auth=(username,password))
record('Old Argon2 login succeeds',response.status_code==201)
token=response.json()['token']
with db('api') as conn:
encoded=conn.execute('SELECT password_hash FROM users WHERE id=%s',(user_id,)).fetchone()[0]
record('Password rehashed',encoded.startswith('$argon2id$v=19$m=19456,t=2,p=1$'))
client=redis('api');key='session:'+hashlib.sha256(token.encode()).hexdigest()
stored=client.get(key)
record('Session stores digest key, no credential',stored is not None and token not in stored and password not in stored)
client.expire(key,1);time.sleep(1.1)
record('Expired session rejected',http('GET','https://lb:8443/api/v1/users/me',headers={'Authorization':'Bearer '+token}).status_code==401)
# Same account alternates replicas. Eight accepted attempts total, not per replica.
username='missing_'+uuid.uuid4().hex[:12];statuses=[];instances=set()
for _ in range(12):
r=http('POST','https://lb:8443/api/v1/auth/sessions',auth=(username,'synthetic-password'))
statuses.append(r.status_code);instances.add(r.headers.get('X-Instance-Id'))
if r.status_code==429:record('Rate limit carries Retry-After',r.headers.get('Retry-After')=='1')
record('Rate limit shared across replicas',statuses.count(401)==8 and statuses.count(429)==4 and len(instances)==2,instances=len(instances),statuses=statuses)
samples=[];hasher=PasswordHasher(time_cost=2,memory_cost=19456,parallelism=1)
hasher.verify(encoded,password) # One warmup; sequential measurements, no HTTP load.
wall_start=time.perf_counter();cpu_start=time.process_time()
for _ in range(20):
start=time.perf_counter();hasher.verify(encoded,password);samples.append(time.perf_counter()-start)
record('Measured Argon2 budget',True,memory_kib=19456,time_cost=2,parallelism=1,
median_ms=round(statistics.median(samples)*1000,2),p95_ms=round(sorted(samples)[18]*1000,2),
p99_ms=round(max(samples)*1000,2),samples_ms=[round(s*1000,3) for s in samples],
duration_seconds=round(time.perf_counter()-wall_start,3),
cpu_seconds=round(time.process_time()-cpu_start,3),
process_peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
global_limit_per_second=32,account_limit_per_10seconds=8,hash_concurrency_per_api=2)
# Every secret is checked as a value, but never serialized in evidence.
(Path('/evidence')/'internal.json').write_text(json.dumps({'checks':results},indent=2))
print(f'PASS: {len(results)} internal checks')
if __name__=='__main__':main()
+127
View File
@@ -0,0 +1,127 @@
"""Operator-driven lifecycle tests. Synthetic data; volumes are never deleted."""
import hashlib
import json
import sys
import time
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
sys.path[:0]=[str(ROOT),str(ROOT/'tests')]
from scripts import lab7 as op
from client import Client
def main():
evidence=ROOT/'evidence';evidence.mkdir(exist_ok=True)
checks=[]
def ok(name,condition=True,**details):
assert condition,name
checks.append({'test':name,'passed':True,**details});print('PASS: '+name,flush=True)
(evidence/'lifecycle.json').write_text(json.dumps(checks,indent=2),encoding='utf-8')
def audit(code):
return op.compose('run','--rm','--no-deps','-T','audit','-',data=code).stdout
def ready():
try:return c.call('GET','/health/ready',schema='Health')['status']==200
except Exception:return False
def saved():
c.call('GET','/api/v1/users/me',actor=alice,schema='User')
history=c.call('GET',f"/api/v1/chats/{chat['id']}/messages?limit=100",actor=bob,schema='MessagePage')['json']['items']
assert original in history
content=c.call('GET',f"/api/v1/attachments/{attachment['id']}/content",actor=bob)['bytes']
assert content==blob
thumbnail=c.call('GET',f"/api/v1/attachments/{attachment['id']}/content?variant=thumbnail",actor=bob)['bytes']
assert thumbnail==original_thumbnail
c=Client('https://127.0.0.1:8443',str(ROOT/'secrets/ca.crt'),timeout=5)
alice,bob,eve,chat=c.bootstrap()
canary='private-message-'+hashlib.sha256(alice['token'].encode()).hexdigest()
original=c.message(alice,chat,canary)['json']
attachment,blob=c.attachment(alice,chat);c.wait_ready(alice,attachment)
original_thumbnail=c.call('GET',f"/api/v1/attachments/{attachment['id']}/content?variant=thumbnail",actor=bob)['bytes']
foreign=c.call('POST','/api/v1/chats',201,actor=eve,body={'title':'Other chat','member_ids':[eve['id']]},schema='Chat')['json']
c.call('POST',f"/api/v1/chats/{foreign['id']}/messages",404,actor=eve,
body={'text':'','attachment_ids':[attachment['id']]},headers={'Idempotency-Key':'cross-chat-probe'})
ok('Cannot attach another chat file')
c.call('POST','/api/v1/users',413,raw=b'x'*65537,headers={'Content-Type':'application/json'})
ok('Request size is bounded')
ids={name:op.compose('exec','-T',name,'hostname').stdout.strip() for name in ['api1','api2']}
for target in ['api1','api2']:
op.compose('stop',target)
start=time.monotonic()
try:
successes=0;failures=0
while successes<5:
try:
response=c.call('GET','/api/v1/users/me',actor=alice)
assert response['headers']['X-Instance-Id']!=ids[target]
successes+=1
except Exception:
failures+=1;successes=0
assert time.monotonic()-start<10,'failover did not recover within 10s'
saved()
ok('Replica failover '+target,recovery_seconds=round(time.monotonic()-start,2),failed_attempts=failures)
finally:
op.compose('start',target);op.compose('restart',target+'-tls')
time.sleep(12)
# Restart the complete stack, including sealed persistent OpenBao.
op.restart_stack()
op.wait_service(ready,90);saved()
ok('Full restart preserves sessions, messages, original and processed attachment')
old=json.loads((op.PRIVATE/'credentials.json').read_text())['api']['db']
image_before=op.docker('image','inspect','mtusi2026lab7-api:local','--format','{{.Id}}').stdout.strip()
op.rotate_secret();time.sleep(12);op.wait_service(ready,30)
code="""import psycopg
try:
psycopg.connect(host='postgres',dbname='messenger',user='api',password=OLD,sslmode='verify-full',sslrootcert='/audit-secrets/ca.crt',connect_timeout=3)
except psycopg.OperationalError as e:
assert 'password authentication failed' in str(e)
print('old DB password rejected')
else:raise AssertionError('old DB password accepted')
""".replace('password=OLD','password='+repr(old))
audit(code);saved();ok('Working DB secret rotated; old password rejected on new connection')
op.rotate_leaf();op.wait_service(ready,30);saved()
output=op.compose('run','--rm','--no-deps','audit','/audit/internal.py').stdout
(evidence/'internal.txt').write_text(output,encoding='utf-8')
ok('Leaf rotated and old LB identity revoked on both replicas')
image_after=op.docker('image','inspect','mtusi2026lab7-api:local','--format','{{.Id}}').stdout.strip()
ok('Rotations do not rebuild image',image_before==image_after,image=image_after)
# Obtain a real scoped token, let it expire, then demonstrate sealed fail-closed.
auth=op.bao('POST','auth/cert/login',{'name':'api'},role='api')['auth']
started=time.monotonic()
time.sleep(auth['lease_duration']+2)
try:op.bao('GET','secret/data/api',token=auth['client_token'],role='api')
except RuntimeError as exc:ok('Expired OpenBao token denied','HTTP 403' in str(exc))
else:raise AssertionError('expired token accepted')
admin=json.loads((op.PRIVATE/'bao-init.json').read_text())['root_token']
op.bao('PUT','sys/seal',token=admin)
started=time.monotonic()
try:
time.sleep(70)
ok('Sealed OpenBao stops API within bounded secret cache',not ready(),elapsed_seconds=round(time.monotonic()-started,2))
for name in ['worker','dispatcher','cleanup']:
code="import pathlib; x=[p.read_bytes() for p in pathlib.Path('/proc').glob('[0-9]*/cmdline')]; assert not any(b'python\\x00-m\\x00src.' in v and b'src.secure_run' not in v for v in x)"
op.compose('exec','-T',name,'python','-c',code)
ok('Sealed OpenBao stops background consumers too')
finally:
op.unseal()
op.wait_service(ready,45);saved();ok('Unseal recovers without baked-in fallback secret')
# Public API errors and telemetry must not contain actual secrets or canaries.
credentials=json.loads((op.PRIVATE/'credentials.json').read_text())
values=[v for role in credentials.values() for v in role.values()]
values += [alice['token'],alice['registration']['password'],canary]
logs=op.compose('logs','--no-color','--since','30m','api1','api2','worker','dispatcher','cleanup','otel-collector','loki','tempo').stdout
ok('Container logs do not expose credentials or private message',not any(v in logs for v in values))
telemetry_code="import sys; sys.path.insert(0,'/audit'); from telemetry import check; check("+repr(values)+")"
print(audit(telemetry_code),flush=True);ok('Live metrics/logs/traces have no credential leaks; datasource writes denied')
deployed=json.loads(op.compose('config','--format','json').stdout)['services']
for name,spec in deployed.items():
assert spec['read_only'] and 'ALL' in spec['cap_drop'] and 'no-new-privileges:true' in spec['security_opt']
assert spec.get('mem_limit') and spec.get('cpus')
ok('All services have read_only, no-new-privileges, cap_drop and limits')
hardware=json.loads(op.docker('info','--format','{"cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}},"os":{{json .OperatingSystem}},"architecture":{{json .Architecture}}}').stdout)
hardware['app_image']=image_after
hardware['services']={name:{key:spec.get(key) for key in ['image','cpus','mem_limit','user','read_only','cap_drop','cap_add','security_opt']} for name,spec in deployed.items()}
(evidence/'environment.json').write_text(json.dumps(hardware,indent=2),encoding='utf-8')
ok('Complete lifecycle suite')
if __name__=='__main__':main()
+47
View File
@@ -0,0 +1,47 @@
"""Verify live encrypted telemetry paths and inspect content without printing it."""
import json
import time
from pathlib import Path
from internal import http, config, S
def check(needles=()):
deadline=time.monotonic()+30
while True:
bodies=[]
for url,params in [
('https://prometheus:19090/api/v1/query',{'query':'http_requests_total'}),
('https://loki:13100/loki/api/v1/query_range',{'query':'{service_name=~"messenger-.*"}','limit':1000}),
('https://tempo:13200/api/search',{'limit':100})]:
r=http('GET',url,'operator',params=params)
assert r.status_code==200, f'{url}: HTTP {r.status_code}'
bodies.append(r.text)
metrics=json.loads(bodies[0])['data']['result']
logs=json.loads(bodies[1])['data']['result']
traces=json.loads(bodies[2]).get('traces',[])
if (metrics and logs and traces) or time.monotonic()>=deadline: break
time.sleep(1)
assert metrics and logs and traces, f'Signal counts: metrics={len(metrics)}, logs={len(logs)}, traces={len(traces)}'
for trace in traces[:20]:
r=http('GET','https://tempo:13200/api/traces/'+trace['traceID'],'operator')
assert r.status_code==200
bodies.append(r.text)
values=list(needles)+[v for role in config.values() for v in role.values()]
assert not any(value in body for value in values for body in bodies),'Telemetry credential/private-message leak'
for host,port,path in [('loki',13100,'/otlp/v1/logs'),('prometheus',19090,'/api/v1/write'),('tempo',13200,'/anything')]:
assert http('POST',f'https://{host}:{port}{path}','grafana',json={}).status_code==403
password=(S/'grafana-admin/password').read_text()
for name in ['prometheus','loki','tempo']:
path=(f'/api/datasources/uid/{name}/health' if name!='tempo'
else '/api/datasources/proxy/uid/tempo/api/search?limit=1')
response=http('GET','https://grafana:3443'+path,
auth=('admin',password))
assert response.status_code==200, f'Grafana datasource {name}: HTTP {response.status_code}'
result={'metric_series':len(metrics),'log_streams':len(logs),'trace_results':len(traces),
'checked_trace_bodies':min(20,len(traces)),'credential_canaries_absent':True,
'grafana_write_denied':True,'grafana_datasource_health':True}
Path('/evidence/telemetry.json').write_text(json.dumps(result,indent=2))
print('PASS: live metrics/logs/traces; no credential/message leaks; Grafana read-only TLS sources')
if __name__=='__main__':check()