Лабораторная 7: TLS, mTLS и OpenBao
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-11-28 01:28:30 +03:00
parent 20afc2c790
commit 2c2734df60
119 changed files with 8651 additions and 104 deletions
+40
View File
@@ -0,0 +1,40 @@
"""Stop each actual API replica in turn; preserve a session, message and image."""
import json,os,subprocess,sys,time
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'tests'))
from client import Client,Failure,check
c=Client('https://localhost:8443',str(ROOT/'secrets/ca/ca.crt'),timeout=2)
def run(*args):return subprocess.check_output(args,cwd=ROOT,text=True)
results={}
for service in ('api-a','api-b'):
run(sys.executable,'scripts/manage.py','restore')
a,b,_,chat=c.bootstrap()
msg=c.message(a,chat,'preserve across '+service)['json']
att,content=c.attachment(a,chat);c.wait_ready(a,att)
container=run('docker','compose','ps','-q',service).strip()
alias=json.loads(run('docker','inspect',container))[0]['Config']['Hostname']
started=time.monotonic();errors=0;instances=set()
try:
subprocess.run([sys.executable,'scripts/manage.py','stop-one'],cwd=ROOT,env=dict(os.environ,TARGET_INSTANCE_ID=alias),check=True,stdout=subprocess.DEVNULL)
first=None
for i in range(20):
try:
reply=c.message(a,chat,'after-stop-'+service+'-'+str(i))
instances.add(reply['headers']['X-Instance-Id'])
if first is None:first=round(time.monotonic()-started,3)
except Failure:errors+=1
time.sleep(.1)
check(first is not None and first<10,'writes failed to recover in 10 seconds')
check(alias not in instances and len(instances)==1,'stopped API still serving or no survivor')
state=json.loads(run('docker','inspect',container))[0]['State']
check(not state['Running'],'replica was not actually stopped')
messages=c.call('GET','/api/v1/chats/'+chat['id']+'/messages?limit=100',actor=b,schema='MessagePage')['json']['items']
check(msg in messages,'confirmed message lost')
actual=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=b)['bytes']
check(actual==content,'original image changed')
c.call('GET','/api/v1/users/me',actor=a,schema='User')
results[service]={'actual_container_stopped':True,'existing_session_and_message_preserved':True,'original_image_identical':True,'surviving_instances':len(instances),'first_success_seconds':first,'failed_attempts':errors,'successful_writes':20-errors}
finally:run(sys.executable,'scripts/manage.py','restore')
(ROOT/'evidence/failover-each.json').write_text(json.dumps(results,indent=2)+'\n')
print('PASS: each API stopped in turn; messages, session and image preserved')
+133
View File
@@ -0,0 +1,133 @@
"""Operator-only TLS/ACL audit. Run in an isolated operator container."""
import json,socket,ssl,sys,time
from pathlib import Path
import urllib.request,urllib.error
import grpc,pika,psycopg2,boto3,redis
from botocore.exceptions import ClientError
from opentelemetry.proto.collector.trace.v1.trace_service_pb2_grpc import TraceServiceStub
from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
R=Path('/workspace');S=R/'secrets';results={}
def ctx(identity=None,foreign=False):
c=ssl.create_default_context(cafile=str(S/('foreign.crt' if foreign else 'ca/bundle.pem')))
if not foreign:c.verify_flags|=ssl.VERIFY_CRL_CHECK_LEAF
if identity=='foreign':c.load_cert_chain('/tmp/foreign.crt','/tmp/foreign.key')
elif identity:c.load_cert_chain(str(S/'tls'/identity/'server.crt'),str(S/'tls'/identity/'server.key'))
return c
def http(host,port,path,identity=None,method='GET',body=None,token=None):
headers={'Content-Type':'application/json'}
if token:headers['X-Vault-Token']=token
request=urllib.request.Request('https://'+host+':'+str(port)+path,data=json.dumps(body).encode() if body is not None else None,headers=headers,method=method)
try:
with urllib.request.urlopen(request,context=ctx(identity),timeout=8) as response:return response.status,response.read()
except urllib.error.HTTPError as e:return e.code,e.read()
def expect_failure(label,function):
try:function()
except (FileNotFoundError,TypeError,NameError,AttributeError):raise
except Exception:results[label]=True;return
raise AssertionError(label+' unexpectedly accepted')
def api(identity,host='api-a'):
status,_=http(host,8080,'/health/live',identity)
assert status==200
# Foreign leaf is deliberately self-signed, separate from the trusted lab CA.
from cryptography import x509
from cryptography.hazmat.primitives import serialization,hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
import datetime as dt
foreign=rsa.generate_private_key(public_exponent=65537,key_size=2048)
name=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'foreign')]);now=dt.datetime.now(dt.timezone.utc)
cert=x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(foreign.public_key()).serial_number(42).not_valid_before(now-dt.timedelta(minutes=1)).not_valid_after(now+dt.timedelta(days=1)).sign(foreign,hashes.SHA256())
# All test-only writes stay in /tmp, never in the mounted workspace.
Path('/tmp/foreign.crt').write_bytes(cert.public_bytes(serialization.Encoding.PEM))
Path('/tmp/foreign.key').write_bytes(foreign.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()))
def foreign_client(host="api-a"):
c=ctx();c.load_cert_chain('/tmp/foreign.crt','/tmp/foreign.key')
with socket.create_connection((host,8080),timeout=3) as raw:
with c.wrap_socket(raw,server_hostname=host) as sock:
sock.sendall(b'GET /health/live HTTP/1.1\r\nHost: api-a\r\nConnection: close\r\n\r\n')
assert b'200' in sock.recv(1024)
for host in ('api-a','api-b'):
api('nginx',host);results[host+'_correct_lb_identity']=True
for identity in (None,'intruder','expired','worker'):
expect_failure(host+'_reject_'+str(identity),lambda i=identity,h=host:api(i,h))
expect_failure(host+'_foreign_ca',lambda h=host:foreign_client(h))
def wrong_hostname():
with socket.create_connection(('nginx',8443),timeout=3) as raw:
with ctx().wrap_socket(raw,server_hostname='wrong.invalid'):pass
expect_failure('external_wrong_hostname',wrong_hostname)
def collector(identity):
key=cert=None
if identity:
key=Path('/tmp/foreign.key').read_bytes() if identity=='foreign' else (S/'tls'/identity/'server.key').read_bytes()
cert=Path('/tmp/foreign.crt').read_bytes() if identity=='foreign' else (S/'tls'/identity/'server.crt').read_bytes()
creds=grpc.ssl_channel_credentials((S/'ca/ca.crt').read_bytes(),key,cert)
with grpc.secure_channel('otel-collector:4317',creds) as channel:
TraceServiceStub(channel).Export(ExportTraceServiceRequest(),timeout=4)
for identity in ('api-a','api-b','worker','publisher'):collector(identity)
results['collector_distinct_allowed_identities']=True
for identity in (None,'intruder','expired','nginx','foreign'):expect_failure('collector_reject_'+str(identity),lambda i=identity:collector(i))
def broker(identity):
return pika.BlockingConnection(pika.ConnectionParameters(host='rabbitmq',port=5671,credentials=pika.credentials.ExternalCredentials(),ssl_options=pika.SSLOptions(ctx(identity),'rabbitmq'),socket_timeout=3,stack_timeout=5,connection_attempts=1))
for identity in ('publisher','worker'):
connection=broker(identity);ch=connection.channel();ch.queue_declare(queue='attachment.process.v1',durable=True);connection.close()
results['broker_distinct_allowed_identities']=True
for identity in (None,'intruder','api-a','expired','foreign'):expect_failure('broker_reject_'+str(identity),lambda i=identity:broker(i))
connection=broker('worker');ch=connection.channel();ch.confirm_delivery()
expect_failure('worker_cannot_publish',lambda:ch.basic_publish('', 'attachment.process.v1',b'forbidden'))
if connection.is_open:connection.close()
roles=json.loads((S/'operator/roles.json').read_text())
for role in ('api','worker','publisher','cleaner'):
conn=psycopg2.connect(roles[role]['database_url']);cur=conn.cursor();cur.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()');assert cur.fetchone()[0];conn.close()
results['postgres_all_roles_verified_tls']=True
conn=psycopg2.connect(roles['worker']['database_url']);cur=conn.cursor()
cur.execute("SELECT has_table_privilege('worker','attachments','DELETE'), has_table_privilege('publisher','attachment_variants','SELECT')")
assert cur.fetchone()==(False,False)
conn.close();results['historical_broad_grants_removed']=True
conn=psycopg2.connect(roles['worker']['database_url']);cur=conn.cursor()
expect_failure('worker_cannot_read_users',lambda:cur.execute('SELECT password_hash FROM users'))
conn.rollback();conn.close()
clients={role:boto3.client('s3',endpoint_url='https://s3:9000',verify='/run/ca/ca.crt',aws_access_key_id=roles[role]['s3_access_key_id'],aws_secret_access_key=roles[role]['s3_secret_access_key'],region_name='us-east-1') for role in ('api','worker','cleaner')}
bucket='messenger-attachments';staging='attachments/staging/security-probe';final='attachments/final/security-probe'
clients['api'].put_object(Bucket=bucket,Key=staging,Body=b'probe')
assert clients['worker'].get_object(Bucket=bucket,Key=staging)['Body'].read()==b'probe'
clients['worker'].put_object(Bucket=bucket,Key=final,Body=b'probe')
assert clients['api'].get_object(Bucket=bucket,Key=final)['Body'].read()==b'probe'
expect_failure('api_cannot_write_final',lambda:clients['api'].put_object(Bucket=bucket,Key=final,Body=b'forbidden'))
expect_failure('worker_cannot_write_staging',lambda:clients['worker'].put_object(Bucket=bucket,Key=staging,Body=b'forbidden'))
for key in (staging,final):clients['cleaner'].delete_object(Bucket=bucket,Key=key)
results['s3_prefix_acl']=True
r=redis.Redis.from_url(roles['api']['cache_url'],ssl_ca_certs='/run/ca/ca.crt',ssl_certfile=str(S/'tls/api-a/server.crt'),ssl_keyfile=str(S/'tls/api-a/server.key'))
assert r.ping();expect_failure('redis_config_denied',lambda:r.config_get('*'));results['redis_tls_acl']=True
for role,identity in [('api','api-a'),('worker','worker')]:
status,body=http('openbao',8200,'/v1/auth/cert/login',identity,'POST',{'name':role});assert status==200
token=json.loads(body)['auth']['client_token']
assert http('openbao',8200,'/v1/secret/data/'+role,identity,token=token)[0]==200
assert http('openbao',8200,'/v1/secret/data/'+('worker' if role=='api' else 'api'),identity,token=token)[0]==403
assert http('openbao',8200,'/v1/sys/policies/acl/escalate',identity,'PUT',{'policy':'path "*" { capabilities=["sudo"] }'},token)[0]==403
results['openbao_'+role+'_allow_deny']=True
status,_=http('openbao',8200,'/v1/auth/cert/login','intruder','POST',{'name':'api'});assert status in (400,403)
results['openbao_wrong_identity_denied']=True
for host,port,path,legit in [('prometheus',9090,'/-/ready','grafana'),('loki',3100,'/ready','grafana'),('tempo',3200,'/ready','grafana')]:
for attempt in range(30):
if http(host,port,path,legit)[0]==200:break
time.sleep(1)
else:raise AssertionError(host+' not ready')
expect_failure(host+'_intruder_denied',lambda h=host,p=port,u=path:http(h,p,u,'intruder'))
# An allowed writer cannot use Loki's read API.
assert http('loki',3100,'/loki/api/v1/labels','collector')[0]==403
results['loki_writer_read_denied']=True
assert http('loki',3100,'/loki/api/v1/push','grafana','POST',{'streams':[]})[0]==403
results['grafana_log_ingest_denied']=True
for host,port in [('rabbitmq',5672),('rabbitmq',15692),('rabbitmq',15672),('rabbitmq',25672),('rabbitmq',4369),('otel-collector',43170),('loki',13100),('tempo',13200),('prometheus',19090)]:
expect_failure(host+'_'+str(port)+'_plaintext_loopback_only',lambda h=host,p=port:socket.create_connection((h,p),timeout=2))
print(json.dumps(results,indent=2))
+100
View File
@@ -0,0 +1,100 @@
"""Operator lifecycle checks: rotation, revocation, sealed Bao and token expiry."""
import json,ssl,subprocess,sys,time,urllib.request,urllib.error
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
sys.path[:0]=[str(ROOT/'scripts'),str(ROOT/'tests')]
import bao
from client import Client,check
c=Client('https://localhost:8443',str(ROOT/'secrets/ca/ca.crt'))
a,b,_,chat=c.bootstrap();results={}
def images():
names=['mtusi-lab7-'+x+'-1' for x in ('api-a','api-b','worker')]
rows=json.loads(subprocess.check_output(['docker','inspect',*names],text=True))
return {r['Name']:r['Image'] for r in rows}
def ready():
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca/ca.crt'))
try:
with urllib.request.urlopen('https://localhost:8443/health/ready',context=ctx,timeout=2) as response:return response.status==200
except (OSError,urllib.error.URLError):return False
def wait(function,seconds=80):
deadline=time.monotonic()+seconds
while time.monotonic()<deadline:
if function():return
time.sleep(1)
raise AssertionError('lifecycle deadline')
before=images()
subprocess.run([sys.executable,'scripts/rotate.py','worker-secret'],cwd=ROOT,check=True)
# Verify fresh connections with retired and replacement credentials inside the operator namespace.
code="""
import json,sys,psycopg2
v=json.load(sys.stdin)
try:psycopg2.connect(v['old'])
except psycopg2.OperationalError:pass
else:raise AssertionError('retired DB credential accepted')
conn=psycopg2.connect(v['new']);conn.close();print('PASS')
"""
old=(ROOT/'secrets/operator/previous-worker-dsn').read_text()
new=json.loads((ROOT/'secrets/operator/roles.json').read_text())['worker']['database_url']
subprocess.run(['docker','compose','--profile','operator','run','--rm','--no-deps','migrate','python','-c',code],cwd=ROOT,input=json.dumps({'old':old,'new':new}),text=True,check=True,stdout=subprocess.DEVNULL)
time.sleep(5)
att,_=c.attachment(a,chat);c.wait_ready(b,att)
results['worker_secret_rotation']={'retired_password_denied_new_connection':True,'new_password_works':True,'attachment_ready':True}
subprocess.run([sys.executable,'scripts/rotate.py','api-leaf'],cwd=ROOT,check=True)
time.sleep(5)
wait(ready)
# The old API client certificate was allowed at Collector before revocation.
code="""
from pathlib import Path
import grpc
from opentelemetry.proto.collector.trace.v1.trace_service_pb2_grpc import TraceServiceStub
from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
root=Path('/workspace/secrets')
def probe(folder):
creds=grpc.ssl_channel_credentials((root/'ca/ca.crt').read_bytes(),(folder/'server.key').read_bytes(),(folder/'server.crt').read_bytes())
with grpc.secure_channel('otel-collector:4317',creds) as channel:TraceServiceStub(channel).Export(ExportTraceServiceRequest(),timeout=4)
try:probe(root/'operator/previous-api-a')
except grpc.RpcError:pass
else:raise AssertionError('revoked leaf accepted')
probe(root/'tls/api-a')
print('PASS')
"""
subprocess.run(['docker','compose','--profile','operator','run','--rm','--no-deps','-v',str(ROOT)+':/workspace:ro','migrate','python','-c',code],cwd=ROOT,check=True,stdout=subprocess.DEVNULL)
check(images()==before,'rotation rebuilt/replaced images')
results['leaf_rotation']={'revoked_old_leaf_denied_new_connection':True,'replacement_accepted':True,'images_unchanged':True,'existing_collector_connection_max_age_seconds':60}
# A real service token with 60s TTL is deliberately left without renewal.
def login_api():
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca/ca.crt'))
ctx.load_cert_chain(str(ROOT/'secrets/tls/api-a/server.crt'),str(ROOT/'secrets/tls/api-a/server.key'))
request=urllib.request.Request('https://localhost:18200/v1/auth/cert/login',data=b'{"name":"api"}',headers={'Content-Type':'application/json'})
with urllib.request.urlopen(request,context=ctx,timeout=5) as response:return json.load(response)['auth'],ctx
probe_token,context=login_api();started=time.monotonic()
try:
bao.call('sys/seal',{},bao.root_token())
wait(lambda:not ready(),seconds=75)
unavailable_after=round(time.monotonic()-started,2)
subprocess.run(['docker','compose','restart','api-a'],cwd=ROOT,check=True,stdout=subprocess.DEVNULL)
time.sleep(5)
data=json.loads(subprocess.check_output(['docker','inspect','mtusi-lab7-api-a-1'],text=True))[0]
# A newly restarted API has no usable Bao token and must not open its listener.
probe="import socket; s=socket.socket(); s.settimeout(1); raise SystemExit(0 if s.connect_ex(('127.0.0.1',8080)) else 1)"
subprocess.run(['docker','compose','exec','-T','api-a','python','-c',probe],cwd=ROOT,check=True)
subprocess.run(['docker','compose','restart','openbao'],cwd=ROOT,check=True,stdout=subprocess.DEVNULL)
time.sleep(3)
check(bao.call('sys/seal-status')['sealed'],'OpenBao restart must require operator unseal')
while time.monotonic()-started<65:time.sleep(1)
finally:
bao.unseal()
wait(ready)
request=urllib.request.Request('https://localhost:18200/v1/secret/data/api',headers={'X-Vault-Token':probe_token['client_token']})
try:urllib.request.urlopen(request,context=context,timeout=5)
except urllib.error.HTTPError as error:check(error.code==403,'unexpected expiry result')
else:raise AssertionError('expired service token accepted')
c.call('GET','/api/v1/users/me',actor=a,schema='User')
results['sealed_expiry']={'api_failed_closed_after_seconds':unavailable_after,'restart_while_sealed_opened_no_listener':True,'unrenewed_service_token_expired':True,'recovered_after_operator_unseal':True,'existing_bearer_session_preserved':True,'openbao_restart_preserved_scoped_configuration':True}
(ROOT/'secrets/operator/previous-worker-dsn').unlink(missing_ok=True)
(ROOT/'evidence/lifecycle.json').write_text(json.dumps(results,indent=2)+'\n')
print('PASS secret/leaf rotation, revocation, expiry, sealed/restart/recovery')
+55
View File
@@ -0,0 +1,55 @@
"""Verify lab6 signals after adding lab7 trust boundaries."""
import base64,json,sys,time,uuid,urllib.parse,urllib.request
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path[:0]=[str(ROOT/'scripts'),str(ROOT/'tests')]
from local_https import get
from client import Client,check
import ssl
c=Client('https://localhost:8443',str(ROOT/'secrets/ca/ca.crt'));a,b,_,chat=c.bootstrap()
reply=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png',202,actor=a,raw=(ROOT/'tests/fixtures/sample.png').read_bytes(),headers={'Content-Type':'image/png','traceparent':'00-'+uuid.uuid4().hex+'-1234567890abcdef-01','tracestate':'lab=lab7'},schema='Attachment')
c.wait_ready(b,reply['json']);tid=reply['headers']['X-Trace-Id']
def wait(fn):
for _ in range(45):
try:
value=fn()
if value:return value
except OSError:pass
time.sleep(1)
raise AssertionError('Telemetry not available')
def spans():
data=get('tempo','/api/traces/'+tid);found=[]
def walk(item):
if isinstance(item,dict):
if 'spanId' in item and 'name' in item:found.append(item)
for value in item.values():walk(value)
elif isinstance(item,list):
for value in item:walk(value)
walk(data)
names={s['name'] for s in found}
return found if {'attachment.publish','attachment.consume','s3.put','postgresql.transaction'}<=names else None
found=wait(spans)
for span in found:
if span['name'] in ('attachment.publish','attachment.consume'):check(span.get('traceState')=='lab=lab7','lost tracestate')
query=urllib.parse.urlencode({'query':'{service_name=~"messenger-.*"} |= "'+tid+'"','since':'1h','limit':1000})
def logs():
rows=get('loki','/loki/api/v1/query_range?'+query)['data']['result']
return rows if {'messenger-api','messenger-worker','messenger-publisher'}<={r['stream']['service_name'] for r in rows} else None
wait(logs)
q=urllib.parse.urlencode({'query':'messenger_http_duration_seconds_bucket'})
wait(lambda:get('prometheus','/api/v1/query?'+q)['data']['result'])
health=get('prometheus','/api/v1/query?'+urllib.parse.urlencode({'query':'up'}))['data']['result']
check(all(row['value'][1]=='1' for row in health),'scrape TLS failed')
# Unique canary and session token must be absent from persisted logs/traces.
canary='PRIVATE_'+uuid.uuid4().hex
c.message(a,chat,canary);time.sleep(5)
for secret in (canary,a['token']):
q=urllib.parse.urlencode({'query':'{service_name=~"messenger-.*"} |= "'+secret+'"','since':'1h','limit':10})
check(not get('loki','/loki/api/v1/query_range?'+q)['data']['result'],'sensitive data in logs')
password=(ROOT/'secrets/operator/grafana_password').read_text().strip()
auth='Basic '+base64.b64encode(('admin:'+password).encode()).decode()
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca/ca.crt'))
request=urllib.request.Request('https://localhost:17400/api/dashboards/uid/messenger',headers={'Authorization':auth})
with urllib.request.urlopen(request,context=ctx,timeout=10) as response:dashboard=json.load(response)
check(len(dashboard['dashboard']['panels'])==14,'provisioning missing')
(ROOT/'evidence/observability-tls.json').write_text(json.dumps({'trace_id':tid,'span_names':[s['name'] for s in found],'all_three_log_services':True,'prometheus_scrapes_tls':True,'grafana_panels':14,'body_token_absent_from_logs':True},indent=2)+'\n')
print('PASS TLS metrics/logs/traces and Grafana provisioning')
+26
View File
@@ -0,0 +1,26 @@
"""Revoking KV permission must stop cached API despite renew-self permission."""
import ssl,sys,time,urllib.request
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
import bao
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca/ca.crt'))
def ready():
try:
with urllib.request.urlopen('https://localhost:8443/health/ready',context=ctx,timeout=2) as r:return r.status==200
except OSError:return False
assert ready(),'start with healthy APIs'
started=time.monotonic()
try:
bao.call('sys/policies/acl/api',{'policy':'path "auth/token/renew-self" { capabilities=["update"] }'},bao.root_token(),method='PUT')
while ready() and time.monotonic()-started<12:time.sleep(.5)
assert not ready(),'API kept running after KV read permission revoked'
elapsed=round(time.monotonic()-started,2)
finally:
bao.call('sys/policies/acl/api',{'policy':(ROOT/'infra/openbao/policies/api.hcl').read_text()},bao.root_token(),method='PUT')
for _ in range(40):
if ready():break
time.sleep(1)
else:raise AssertionError('API did not recover after policy restored')
import json
(ROOT/'evidence/policy-revocation.json').write_text(json.dumps({'kv_policy_revoked_api_stopped_seconds':elapsed,'renew_self_did_not_extend_cache':True,'recovered_after_policy_restore':True},indent=2)+'\n')
print('PASS: KV policy denial stops cached APIs and restore recovers')
+20
View File
@@ -0,0 +1,20 @@
"""Regression: malformed Content-Length must be rejected before any body read."""
import sys
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/"src"))
from email.message import Message
from types import SimpleNamespace
from unittest.mock import Mock
from messenger.tls_proxy import HttpForwarder
for lengths in (['-1'],['abc'],['5','6']):
handler=object.__new__(HttpForwarder)
handler.headers=Message()
for value in lengths:handler.headers.add_header('Content-Length',value)
handler.server=SimpleNamespace(identity='collector',rule={'target':1,'http':{'collector':[['POST','/otlp/']]}})
handler.command='POST';handler.path='/otlp/v1/logs'
handler.rfile=SimpleNamespace(read=Mock(return_value=b''))
handler.send_error=Mock()
handler.forward()
assert handler.send_error.called,'malformed length was accepted'
handler.rfile.read.assert_not_called()
print('PASS: negative, nonnumeric and duplicate Content-Length rejected before reading')
+63
View File
@@ -0,0 +1,63 @@
"""Verified HTTPS ACL, session expiry, legacy rehash, global login budget and KDF cost."""
import base64,hashlib,json,statistics,subprocess,sys,time,uuid
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'))
from client import Client,check
c=Client('https://localhost:8443',str(ROOT/'secrets/ca/ca.crt'));a,b,e,chat=c.bootstrap();results={}
att,original=c.attachment(a,chat);att=c.wait_ready(b,att)
path='/api/v1/attachments/'+att['id']
for endpoint in (path,path+'/content'):c.call('GET',endpoint,404,actor=e)
c.call('GET',path,404,actor=e,headers={'X-User-Id':a['id']})
check(c.call('GET','/api/v1/users/me',actor=a,headers={'X-User-Id':e['id']},schema='User')['json']['id']==a['id'],'identity spoof')
other=c.call('POST','/api/v1/chats',201,actor=e,body={'title':'Own chat','member_ids':[e['id']]},schema='Chat')['json']
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=e,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
results['attachment_acl_and_identity_spoof']=True
# Legacy hash is generated in the runtime, with the password passed via stdin.
code="""
import json,sys,time,statistics
from messenger import security
from messenger.config import Config
from messenger.db import Database
v=json.load(sys.stdin);db=Database(Config.from_env());db.open()
with db.cursor() as cur:
cur.execute('UPDATE users SET password_hash=%s WHERE id=%s',(security.legacy_hash_password(v['password']),v['id']))
samples=[]
for _ in range(12):
start=time.perf_counter();security.hash_password('synthetic-benchmark-password');samples.append((time.perf_counter()-start)*1000)
print(json.dumps({'argon2_memory_kib':19456,'iterations':2,'parallelism':1,'samples':len(samples),'median_ms':statistics.median(samples),'max_ms':max(samples),'max_concurrent_per_api':2}))
db.close()
"""
result=subprocess.run(['docker','compose','exec','-T','api-a','python','-c',code],cwd=ROOT,input=json.dumps({'id':a['id'],'password':a['registration']['password']}),text=True,capture_output=True,check=True)
results['kdf_budget']=json.loads(result.stdout)
credential=base64.b64encode((a['registration']['username']+':'+a['registration']['password']).encode()).decode()
c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')
code="""
import sys
from messenger.config import Config
from messenger.db import Database
db=Database(Config.from_env());db.open()
with db.cursor() as cur:
cur.execute('SELECT password_hash FROM users WHERE id=%s',(sys.argv[1],));assert cur.fetchone()['password_hash'].startswith('$argon2id$v=19$m=19456,t=2,p=1$')
print('PASS')
"""
subprocess.run(['docker','compose','exec','-T','api-a','python','-c',code,a['id']],cwd=ROOT,check=True,stdout=subprocess.DEVNULL)
results['legacy_rehash']=True
# Force expiry of a real session; Redis must not override PostgreSQL expiry.
digest=hashlib.sha256(b['token'].encode()).hexdigest()
sql="UPDATE sessions SET expires_at=now()-interval '1 second' WHERE token_hash='"+digest+"';"
subprocess.run(['docker','compose','exec','-T','postgres','psql','-U','messenger','-d','messenger'],cwd=ROOT,input=sql,text=True,check=True,stdout=subprocess.DEVNULL)
c.call('GET','/api/v1/users/me',401,actor=b)
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=a);c.call('GET','/api/v1/users/me',401,actor=a)
results['session_expiry_logout']=True
time.sleep(11)
instances=set();limited=0
for _ in range(38):
reply=c.call('POST','/api/v1/auth/sessions',[401,429],headers={'Authorization':'Basic '+base64.b64encode(b'unknown-user:wrong-password').decode()})
instances.add(reply['headers']['X-Instance-Id'])
if reply['status']==429:
check(reply['headers'].get('Retry-After')=='10','missing Retry-After');limited+=1
check(len(instances)==2 and limited>=8,'rate budget not shared across two replicas')
results['global_login_rate_limit']={'replicas':len(instances),'limited_requests':limited,'requests':38,'limit':'30 per 10 seconds'}
(ROOT/'evidence/public-security.json').write_text(json.dumps(results,indent=2)+'\n')
time.sleep(11) # Leave the shared budget usable for subsequent independent checks.
print('PASS ACL, rehash, expiry/logout, shared login budget and Argon2 benchmark')
+27
View File
@@ -0,0 +1,27 @@
"""Regression: reconcile lost KV write responses without rolling the DB back."""
import json,sys,tempfile
from pathlib import Path
from unittest.mock import patch
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
import rotate
for unreadable in (False,True):
with tempfile.TemporaryDirectory() as folder:
ops=Path(folder);roles={'worker':{'database_url':'postgresql://worker:old@postgres/messenger'}}
(ops/'roles.json').write_text(json.dumps(roles));written={};calls=[]
def request(path,data=None,token=None):
if data is not None:
written.update(data['data']);raise TimeoutError()
if unreadable:raise TimeoutError()
return {'data':{'data':written}}
with patch.object(rotate,'OPS',ops),patch.object(rotate.bao,'root_token',return_value='test'),patch.object(rotate.bao,'call',side_effect=request),patch.object(rotate.subprocess,'run',side_effect=lambda *a,**kw:calls.append(kw['input'])):
if unreadable:
try:rotate.worker_secret()
except RuntimeError:pass
else:raise AssertionError('ambiguous failure hidden')
pending=json.loads((ops/'worker-rotation-pending.json').read_text())
with patch.object(rotate.bao,'call',return_value={}):rotate.worker_secret()
assert pending['password'] in calls[-1],'retry changed target password'
else:rotate.worker_secret()
assert all("PASSWORD 'old'" not in sql for sql in calls),'unsafe rollback after committed KV write'
assert not (ops/'worker-rotation-pending.json').exists()
print('PASS: committed-timeout reconciled; unknown outcome resumes saved target')