Реализовать лабораторную 7: mTLS, OpenBao и защита worker

This commit is contained in:
wpyatzy
2026-12-04 20:35:40 +03:00
parent 20afc2c790
commit 1b865eac83
146 changed files with 9552 additions and 87 deletions
+32
View File
@@ -0,0 +1,32 @@
"""Real cert-auth allow/deny checks; prints statuses, never credentials."""
import json
from pathlib import Path
import ssl
import urllib.error
import urllib.request
root=Path(__file__).resolve().parents[1]
results=[]
for role in ('api','worker','publisher','observer','janitor'):
context=ssl.create_default_context(cafile=str(root/'.secrets/ca.crt'))
context.load_cert_chain(str(root/'.secrets/roles'/role/'service.pem'))
def call(path,payload=None,token=None):
data=json.dumps(payload).encode() if payload is not None else None
headers={'Content-Type':'application/json'}
if token:headers['X-Vault-Token']=token
req=urllib.request.Request('https://localhost:8207/v1/'+path,data=data,headers=headers)
try:
with urllib.request.urlopen(req,context=context,timeout=5) as r:return r.status,json.load(r)
except urllib.error.HTTPError as e:return e.code,{}
status,login=call('auth/cert/login',{'name':role});assert status==200
token=login['auth']['client_token']
own,_=call('secret/data/'+role,token=token);assert own==200
other,_=call('secret/data/'+('worker' if role=='api' else 'api'),token=token);assert other==403
admin,_=call('sys/policies/acl/escalate',{'policy':'path "*" { capabilities=["sudo"] }'},token);assert admin==403
results.append({'role':role,'login':status,'own_path':own,'other_path':other,'policy_write':admin,'ttl_seconds':login['auth']['lease_duration']})
# The same CA does not permit API to authenticate as worker.
context=ssl.create_default_context(cafile=str(root/'.secrets/ca.crt'))
context.load_cert_chain(str(root/'.secrets/roles/api/service.pem'))
wrong,_=call('auth/cert/login',{'name':'worker'});assert wrong in (400,403)
context=ssl.create_default_context(cafile=str(root/'.secrets/ca.crt'))
missing,_=call('auth/cert/login',{'name':'worker'});assert missing in (400,403)
print(json.dumps({'status':'PASS','checks':results,'wrong_role_login':wrong,'missing_cert_login':missing},indent=2))
+38
View File
@@ -0,0 +1,38 @@
"""Track 1, three isolated incident-response repetitions; all accepted originals survive."""
import hashlib,json,subprocess,sys,time
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path[:0]=[str(ROOT/'scripts'),str(ROOT/'tests')]
from client import Client
from pki import PRIVATE
from rotate_worker import rotate
def run(*args):return subprocess.check_output(args,text=True,stderr=subprocess.DEVNULL)
def result(text):return json.loads(text[text.index('{'):])
def compose(*args):return run('./scripts/compose.sh',*args)
run('.venv/bin/python','scripts/wait_ready.py')
run('./scripts/operator.sh','python','scripts/provision.py','clear-rate')
c=Client(ca_file=str(PRIVATE/'ca.crt'),timeout=20);alice,bob,eve,chat=c.bootstrap();rows=[]
for repeat in range(1,4):
run('./scripts/operator.sh','python','scripts/seed_security.py')
broad=result(run('./scripts/operator.sh','python','tests/worker_privileges.py'))
limited=result(subprocess.check_output(['./scripts/compose.sh','exec','-T','worker','python','-','--worker'],input=(ROOT/'tests/worker_privileges.py').read_text(),text=True,stderr=subprocess.DEVNULL))
image_before=run('docker','inspect','--format','{{.Image}}',compose('ps','-q','worker').strip()).strip()
compose('stop','-t','5','worker');accepted=[c.attachment(alice,chat) for _ in range(3)]
assert all(c.call('GET','/api/v1/attachments/'+a['id'],actor=alice,schema='Attachment')['json']['status']=='queued' for a,_ in accepted)
start=time.monotonic();response=rotate();transient=0
for a,payload in accepted:
deadline=time.monotonic()+120
while time.monotonic()<deadline:
out=c.call('GET','/api/v1/attachments/'+a['id'],[200,503],actor=alice,schema='Attachment')
if out['status']==503:transient+=1
elif out['json']['status']=='ready':break
else:assert out['json']['status']!='failed'
time.sleep(.5)
else:raise AssertionError('accepted task did not recover')
original=c.call('GET','/api/v1/attachments/'+a['id']+'/content',actor=bob)['bytes']
assert hashlib.sha256(original).hexdigest()==a['sha256'] and original==payload
image_after=run('docker','inspect','--format','{{.Image}}',compose('ps','-q','worker').strip()).strip();assert image_before==image_after
rows.append({'repeat':repeat,'broad':broad['operations'],'least_privilege':limited['operations'],'accepted':len(accepted),'preserved_ready':len(accepted),'recovery_seconds':round(time.monotonic()-start,3),'image_unchanged':True,'transient_503':transient,**response})
print('Completed incident repetition '+str(repeat),file=sys.stderr,flush=True)
(ROOT/'evidence/compromise-research.json').write_text(json.dumps({'status':'PASS','track':1,'repeats':rows},indent=2))
print('PASS: 3 incident repetitions, 9 accepted jobs preserved, worker identity and 3 secrets rotated')
+14
View File
@@ -0,0 +1,14 @@
"""Trusted operator proves passwords are enforced behind the TLS proxy for every DB role."""
import json,os
import psycopg
from psycopg.conninfo import conninfo_to_dict,make_conninfo
base=conninfo_to_dict(os.environ['DATABASE_URL']);credentials=json.loads(os.environ['ROLE_CREDENTIALS']);rows=[]
for role in ['api','worker','publisher','observer','janitor']:
info={**base,'user':'messenger_'+role,'password':credentials[role]['db_password']}
with psycopg.connect(make_conninfo(**info),connect_timeout=3) as c:assert c.execute('SELECT current_user').fetchone()[0]=='messenger_'+role
try:psycopg.connect(make_conninfo(**{**info,'password':'synthetic_wrong_password'}),connect_timeout=3);raise AssertionError('wrong DB password accepted')
except psycopg.OperationalError as e:assert 'password authentication failed' in str(e)
rows.append({'role':role,'correct_password':True,'wrong_password_denied':True})
try:psycopg.connect(make_conninfo(**{**base,'password':credentials['worker']['db_password']}),connect_timeout=3);raise AssertionError('worker escalated to admin')
except psycopg.OperationalError as e:assert 'password authentication failed' in str(e)
print(json.dumps({'status':'PASS','rows':rows,'worker_password_cannot_authenticate_admin':True,'tcp_auth':'scram-sha-256'},indent=2))
+21
View File
@@ -0,0 +1,21 @@
"""Run unchanged public failover until two distinct real API containers were stopped."""
import json,ssl,subprocess,sys,urllib.request
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];ca=ROOT/'.secrets/ca.crt';actions=ROOT/'evidence/failover-actions.jsonl'
seen=set();ctx=ssl.create_default_context(cafile=str(ca))
for attempt in range(1,7):
subprocess.run(['./scripts/compose.sh','up','-d','api'],check=True,stdout=subprocess.DEVNULL)
subprocess.run(['.venv/bin/python','scripts/wait_ready.py'],check=True,stdout=subprocess.DEVNULL)
# Offset round robin on alternating attempts; no affinity/test modifications.
if attempt%2==0:
with urllib.request.urlopen('https://localhost:8443/health/ready',context=ctx,timeout=5) as r:assert r.status==200
previous=len(actions.read_text().splitlines()) if actions.exists() else 0
with (ROOT/f'evidence/failover-each-{attempt}.txt').open('w') as f:
subprocess.run(['make','test-failover','ACTION_SCRIPT=scripts/stop-one.sh','CA_FILE='+str(ca)],check=True,stdout=f)
rows=[json.loads(x) for x in actions.read_text().splitlines()][previous:];assert len(rows)==1
seen.add(rows[0]['container_name'])
if len(seen)>=2:break
else:raise AssertionError('Two distinct API containers were not tested')
subprocess.run(['./scripts/compose.sh','up','-d','api'],check=True,stdout=subprocess.DEVNULL)
subprocess.run(['.venv/bin/python','scripts/wait_ready.py'],check=True,stdout=subprocess.DEVNULL)
print(json.dumps({'status':'PASS','distinct_stopped_containers':sorted(seen),'runs':attempt},indent=2))
+27
View File
@@ -0,0 +1,27 @@
"""Sanitized Docker policy and secret-boundary audit, host operator only."""
import json,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
ids=subprocess.check_output(['./scripts/compose.sh','ps','-q'],text=True).split()
rows=[]
for item in json.loads(subprocess.check_output(['docker','inspect',*ids],text=True)):
h=item['HostConfig'];c=item['Config'];role=c['Labels']['com.docker.compose.service']
assert not h['Privileged'] and h['NetworkMode']!='host'
assert h['NanoCpus']>0 and h['Memory']>0
assert 'ALL' in (h['CapDrop'] or [])
assert any('no-new-privileges' in s for s in h['SecurityOpt'])
assert not any('docker.sock' in m['Source'] for m in item['Mounts'])
if role!='db-engine':assert h['ReadonlyRootfs'] and c['User'].split(':')[0] not in ('','0')
if role in ['api','worker','publisher','observer','janitor']:
assert all(not e.startswith(('DATABASE_URL=','S3_SECRET_ACCESS_KEY=','BROKER_URL=','CACHE_URL=')) for e in c['Env'])
sources=[m['Source'] for m in item['Mounts']]
assert not any('bao-operator' in s or 'operator-env' in s or s.endswith('ca.key') for s in sources)
assert sum('/.secrets/roles/' in s for s in sources)==1
if role=='db-engine':
proc=subprocess.check_output(['docker','exec',item['Id'],'cat','/proc/1/status'],text=True)
uid=int(next(x for x in proc.splitlines() if x.startswith('Uid:')).split()[1]);assert uid==70
if role=='api':assert not h['PortBindings']
for mappings in (h['PortBindings'] or {}).values():
for p in mappings or []:assert p['HostIp']=='127.0.0.1'
rows.append({'service':role,'non_root':c['User'] not in ('','0','0:0'),'read_only':h['ReadonlyRootfs'],'drop_all':True,'no_new_privileges':True,'cpu_limit':h['NanoCpus']/1e9,'memory_mib':h['Memory']//1048576})
print(json.dumps({'status':'PASS','containers':rows,'stateful_exception':'Postgres entrypoint root with only CHOWN,DAC_OVERRIDE,FOWNER,SETUID,SETGID; postgres daemon drops to UID 70'},indent=2))
+37
View File
@@ -0,0 +1,37 @@
"""Concurrent shared-key requests through LB, real instance headers and history."""
from concurrent.futures import ThreadPoolExecutor
import json
import threading
import uuid
from client import Client, arguments, check, run
def main():
args = arguments(__doc__)
c = Client(args.base_url,args.ca_file)
alice, bob, eve, chat = c.bootstrap()
key = uuid.uuid4().hex
barrier = threading.Barrier(16)
def worker(_):
local = Client(args.base_url,args.ca_file)
barrier.wait()
return local.message(alice, chat, ' concurrent body ', key=key)
with ThreadPoolExecutor(max_workers=16) as pool:
responses = list(pool.map(worker, range(16)))
ids = {r['json']['id'] for r in responses}
instances = {r['headers']['X-Instance-Id'] for r in responses}
check(len(ids) == 1, 'concurrent duplicate messages')
check(len(instances) >= 2, 'concurrent requests did not reach two replicas')
path = '/api/v1/chats/' + chat['id'] + '/messages'
c.call('POST', path, 409, actor=alice, body={'text': 'concurrent body'}, headers={'Idempotency-Key': key})
again = c.call('POST', path, 201, actor=alice, body={'attachment_ids': [], 'text': ' concurrent body '}, headers={'Idempotency-Key': key}, schema='Message')
check(again['json'] == responses[0]['json'], 'semantic replay differs')
page = c.call('GET', path, actor=bob, schema='MessagePage')['json']
check(len(page['items']) == 1, 'history contains duplicate effects')
c.message(bob, chat, 'other user', key=key)
print(json.dumps({'parallel_requests': 16, 'observed_instances': sorted(instances), 'unique_messages': len(ids), 'conflict': 409, 'semantic_replay': True, 'user_scope': True}))
if __name__ == '__main__':
run(main)
+51
View File
@@ -0,0 +1,51 @@
"""Actual variant geometry, orientation, alpha, encoder metadata and hashes."""
import hashlib
import io
import json
from pathlib import Path
import sys
from PIL import Image
sys.path.insert(0,str(Path(__file__).resolve().parent))
from client import Client,check
def main():
c=Client('https://lb:8443',ca_file='/run/trust/ca.crt');alice,bob,eve,chat=c.bootstrap();rows=[]
cases=[]
cases.append(('small_alpha',Image.new('RGBA',(80,40),(0,0,0,0)),'PNG',{},(80,40)))
cases.append(('exif_orientation',Image.new('RGB',(400,100),'red'),'JPEG',{'exif':Image.Exif()},(64,256)))
cases[-1][3]['exif'][274]=6
center=Image.new('RGB',(400,100),'red');center.paste('blue',(150,0,250,100))
cases.append(('center_crop',center,'PNG',{},(256,64)))
cases.append(('large_fit',Image.new('RGB',(1600,800),'green'),'PNG',{},(256,128)))
for name,image,fmt,options,expected in cases:
data=io.BytesIO();image.save(data,fmt,**options);payload=data.getvalue()
mime='image/png' if fmt=='PNG' else 'image/jpeg'
att=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename='+name,202,actor=alice,
raw=payload,headers={'Content-Type':mime},schema='Attachment')['json']
ready=c.wait_ready(alice,att)
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==payload,'original changed')
dimensions={}
for variant in ready['variants']:
result=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+variant['name'],actor=bob)
check(hashlib.sha256(result['bytes']).hexdigest()==variant['sha256'],'false checksum')
check(len(result['bytes'])==variant['size_bytes'],'false variant size')
with Image.open(io.BytesIO(result['bytes'])) as output:
check(not output.getexif(),'EXIF leaked')
check(output.size==(variant['width'],variant['height']),'false dimensions')
dimensions[variant['name']]=output.size
check(output.format==('WEBP' if variant['name']=='optimized' else 'JPEG'),'wrong encoder')
if variant['name']=='thumbnail':
check(output.size==expected,'thumbnail orientation/scale incorrect')
if name=='small_alpha':check(min(output.getpixel((10,10)))>245,'alpha not composited on white')
if variant['name']=='crop':
check(output.size==(128,128),'crop dimensions wrong')
if name=='center_crop':check(output.getpixel((64,64))[2]>240,'crop not centered')
if variant['name']=='optimized':
check(max(output.size)<=1280,'optimized too large')
if name=='large_fit':check(output.size==(1280,640),'optimized ratio wrong')
rows.append(dict(case=name,status='PASS',dimensions=dimensions,original_sha256=hashlib.sha256(payload).hexdigest()))
print(json.dumps({'status':'PASS','rows':rows},indent=2))
if __name__=='__main__':main()
+45
View File
@@ -0,0 +1,45 @@
"""Host operator: renewal, expired worker leaf, sealed Bao, automatic recovery."""
import json,subprocess,sys,time
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
sys.path[:0]=[str(ROOT/'scripts'),str(ROOT/'tests')]
from pki import PRIVATE,issue
from bao_operator import call
from client import Client
def compose(*args):return subprocess.check_output(['./scripts/compose.sh',*args],text=True,stderr=subprocess.DEVNULL)
def status(role):return json.loads(compose('exec','-T',role,'cat','/tmp/agent-status.json'))
def until(fn,timeout=90):
start=time.monotonic()
while time.monotonic()-start<timeout:
if fn():return round(time.monotonic()-start,3)
time.sleep(1)
raise AssertionError('bounded lifecycle transition timed out')
c=Client(ca_file=str(PRIVATE/'ca.crt'),timeout=10)
# Existing agent should have renewed at least once; wait if fresh start.
until(lambda:status('worker')['renewals']>=1)
renew=status('worker');assert renew['child_running']
alice,bob,eve,chat=c.bootstrap()
leaf=PRIVATE/'roles/worker';saved={n:(leaf/n).read_bytes() for n in ('service.crt','service.key','service.pem')}
try:
issue('worker',replace=True,expired=True)
expired_stop=until(lambda:not status('worker')['child_running'],35)
att,payload=c.attachment(alice,chat)
assert c.call('GET','/api/v1/attachments/'+att['id'],actor=alice,schema='Attachment')['json']['status']=='queued'
finally:
for n,data in saved.items():(leaf/n).write_bytes(data)
start=time.monotonic();c.wait_ready(alice,att,wait_seconds=90);expiry_recovery=round(time.monotonic()-start,3)
assert c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==payload
try:
call('sys/seal',{})
sealed_stop=until(lambda:not status('worker')['child_running'] and not status('api')['child_running'],40)
blocked=status('worker');assert blocked['blocked_events']>0
finally:
creds=json.loads((PRIVATE/'bao-operator.json').read_text());call('sys/unseal',{'key':creds['keys'][0]},token=False)
start=time.monotonic()
def ready():
try:return c.call('GET','/health/ready',schema='Health')['status']==200
except Exception:return False
until(ready,120);sealed_recovery=round(time.monotonic()-start,3)
c.message(alice,chat,'after operator unseal')
print(json.dumps({'status':'PASS','renewal_status':renew,'expired_leaf_stop_seconds':expired_stop,'expiry_task_preserved':True,'expiry_recovery_seconds':expiry_recovery,'sealed_stop_seconds':sealed_stop,'sealed_recovery_seconds':sealed_recovery,'plaintext_fallback':False},indent=2))
+107
View File
@@ -0,0 +1,107 @@
"""Host-side backend queries and genuine trace/log correlation. No tokens saved."""
import base64
import ssl
import json
import os
from pathlib import Path
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from client import Client,check
ROOT=Path(__file__).resolve().parents[1]
TLS=ssl.create_default_context(cafile=str(ROOT/'.secrets/ca.crt'))
TLS.load_cert_chain(str(ROOT/'.secrets/roles/operator/service.pem'))
def get(url,headers=None):
with urllib.request.urlopen(urllib.request.Request(url,headers=headers or {}),context=TLS,timeout=8) as response:
return json.load(response)
def prom(expr):
return get('https://localhost:9097/api/v1/query?'+urllib.parse.urlencode({'query':expr}))['data']['result']
def logs(trace_id=None,service='messenger-api'):
query='{service_name="'+service+'"}'
if trace_id:query+=' |= "'+trace_id+'"'
return get('https://localhost:3107/loki/api/v1/query_range?'+urllib.parse.urlencode({'query':query,'since':'15m','limit':1000}))['data']['result']
def trace_data(trace_id):
return get('https://localhost:3207/api/traces/'+trace_id)
def flatten(data):
rows=[]
for batch in data.get('batches',data.get('resourceSpans',[])):
attrs={a['key']:a['value'].get('stringValue',a['value'].get('intValue')) for a in batch.get('resource',{}).get('attributes',[])}
for scope in batch.get('scopeSpans',batch.get('instrumentationLibrarySpans',[])):
for s in scope.get('spans',[]):rows.append({**s,'service':attrs.get('service.name')})
return rows
def wait_for(call,predicate=lambda x:bool(x),timeout=60):
deadline=time.monotonic()+timeout;last=None
while time.monotonic()<deadline:
try:
last=call()
if predicate(last):return last
except (OSError,ValueError,KeyError):pass
time.sleep(1)
raise AssertionError('telemetry expectation timed out')
def main():
wait_for(lambda:prom('up'),lambda rows:len(rows)>=2 and all(r['value'][1]=='1' for r in rows))
c=Client('https://localhost:8443',ca_file=str(ROOT/'.secrets/ca.crt'));alice,bob,eve,chat=c.bootstrap()
trace_id=uuid.uuid4().hex;parent=uuid.uuid4().hex[:16]
carrier='00-'+trace_id+'-'+parent+'-01'
payload=(ROOT/'tests/fixtures/sample.png').read_bytes()
att=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=probe.png',202,actor=alice,
raw=payload,headers={'Content-Type':'image/png','traceparent':carrier},schema='Attachment')['json']
c.wait_ready(alice,att)
data=wait_for(lambda:trace_data(trace_id),lambda x: any(s['name']=='queue.process' for s in flatten(x)))
rows=flatten(data)
required={'queue.publish','queue.process','s3.put_object','db.transaction'}
check(required<={r['name'] for r in rows},'incomplete upload -> broker -> worker -> S3/DB trace')
api=next(r for r in rows if r['service']=='messenger-api' and r['kind'] in ('SPAN_KIND_SERVER',2))
producer=next(r for r in rows if r['name']=='queue.publish')
consumer=next(r for r in rows if r['name']=='queue.process')
# Tempo JSON may serialize IDs as base64 or hex depending on version.
check(producer['parentSpanId'] in {s['spanId'] for s in rows if s['service']=='messenger-api'},'producer not parented to acceptance trace')
check(consumer['parentSpanId']==producer['spanId'],'consumer not parented to producer')
api_logs=wait_for(lambda:logs(trace_id))
worker_logs=wait_for(lambda:logs(trace_id,'messenger-worker'))
check(api_logs and worker_logs,'missing correlated logs')
queries=['sum(messenger_http_requests_total{service_name="messenger-api"})',
'sum(messenger_jobs_total{service_name="messenger-worker",outcome="ready"})',
'sum(messenger_http_duration_seconds_bucket{service_name="messenger-api",le="0.5"})',
'max(messenger_queue_depth{service_name="messenger-observer"})',
'max(messenger_db_pool_used{service_name="messenger-api"})']
observations={q:wait_for(lambda q=q:prom(q)) for q in queries}
secret_values=[alice['token'],bob['token'],eve['token'],alice['registration']['password'],bob['registration']['password'],eve['registration']['password']]
text=json.dumps([data,api_logs,worker_logs])
check(not any(secret in text for secret in secret_values),'credential in telemetry')
secrets=dict(line.split('=',1) for line in (ROOT/'.env').read_text().splitlines() if '=' in line)
credentials=base64.b64encode(('admin:'+secrets['GRAFANA_PASSWORD']).encode()).decode()
uid=json.loads((ROOT/'infra/grafana/dashboards/messenger.json').read_text())['uid']
dashboard=wait_for(lambda:get('https://localhost:3007/api/dashboards/uid/'+uid,{'Authorization':'Basic '+credentials}))
check(len(dashboard['dashboard']['panels'])>=15,'provisioned dashboard missing')
proxied={}
for name,path in [('prometheus','/api/v1/query?query=up'),('loki','/loki/api/v1/labels'),('tempo','/api/search?limit=1')]:
wait_for(lambda name=name,path=path:get('https://localhost:3007/api/datasources/proxy/uid/'+name+path,{'Authorization':'Basic '+credentials}))
proxied[name]='PASS via Grafana mTLS client'
(ROOT/'evidence/correlated-trace.json').write_text(json.dumps(data,indent=2))
(ROOT/'evidence/correlated-logs.json').write_text(json.dumps({'api':api_logs,'worker':worker_logs},indent=2))
result={'status':'PASS','trace_id':trace_id,'attachment_id':att['id'],
'span_count':len(rows),'services':sorted({r['service'] for r in rows}),
'producer_parent_api':True,'consumer_parent_producer':True,'api_and_worker_logs':True,
'metric_queries':observations,'dashboard_uid':dashboard['dashboard']['uid'],'dashboard_panels':len(dashboard['dashboard']['panels']),
'known_credentials_absent':True,'grafana_proxied_backends':proxied}
print(json.dumps(result,indent=2))
if __name__=='__main__':main()
+25
View File
@@ -0,0 +1,25 @@
"""Trusted incident responder proves stolen worker identity/credentials no longer work."""
import json,os,socket,ssl,struct,urllib.request,urllib.error
from pathlib import Path
import psycopg,redis,boto3
from botocore.config import Config
from botocore.exceptions import ClientError
old=json.loads(Path('/run/old-worker/values.json').read_text())
ctx=ssl.create_default_context(cafile='/run/trust/ca.crt');ctx.load_cert_chain('/run/old-worker/service.pem')
try:
with socket.create_connection(('db',15432),timeout=3) as raw:
with ctx.wrap_socket(raw,server_hostname='db') as s:
s.sendall(struct.pack('!II',8,80877103));assert not s.recv(16),'revoked TLS accepted'
except (OSError,ssl.SSLError):pass
req=urllib.request.Request('https://openbao:8200/v1/auth/cert/login',data=b'{"name":"worker"}',headers={'Content-Type':'application/json'})
try:urllib.request.urlopen(req,context=ctx,timeout=5);raise AssertionError('revoked Bao auth accepted')
except urllib.error.HTTPError as e:assert e.code in (400,403)
try:psycopg.connect(old['DATABASE_URL'],connect_timeout=3);raise AssertionError('old DB password accepted')
except psycopg.OperationalError as e:assert 'password authentication failed' in str(e)
try:redis.Redis.from_url(old['BROKER_URL']).ping();raise AssertionError('old broker password accepted')
except redis.AuthenticationError:pass
s=boto3.client('s3',endpoint_url='http://127.0.0.1:19000',aws_access_key_id=old['S3_ACCESS_KEY_ID'],aws_secret_access_key=old['S3_SECRET_ACCESS_KEY'],region_name='us-east-1',config=Config(signature_version='s3v4',s3={'addressing_style':'path'},retries={'max_attempts':0}))
try:s.get_object(Bucket='messenger-attachments',Key='staging/security-probe');raise AssertionError('old S3 password accepted')
except ClientError as e:assert e.response['ResponseMetadata']['HTTPStatusCode']==403
s.close()
print(json.dumps({'status':'PASS','revoked_tls':True,'revoked_bao_login':True,'old_db_password_denied':True,'old_broker_password_denied':True,'old_s3_password_denied':True}))
+64
View File
@@ -0,0 +1,64 @@
"""Trusted operator checks externally visible controls and stored representations."""
import base64
import hashlib
import json
import statistics
import time
import uuid
from argon2 import PasswordHasher
from client import Client,check
from app import store
import redis
import os
store.pool.open(wait=True)
def reset():
with store.connect() as conn:conn.execute('DELETE FROM login_limits')
def basic(name,password):return {'Authorization':'Basic '+base64.b64encode((name+':'+password).encode()).decode()}
reset();c=Client('https://lb:8443',ca_file='/run/trust/ca.crt',timeout=20)
alice,bob,eve,chat=c.bootstrap();rows=[]
# Seed only this synthetic user's old parameter hash; no public test modification.
password=alice['registration']['password']
old=PasswordHasher(memory_cost=19456,time_cost=2,parallelism=1).hash(password)
with store.connect() as conn:conn.execute('UPDATE users SET password_hash=%s WHERE id=%s',(old,alice['id']))
result=c.call('POST','/api/v1/auth/sessions',201,headers=basic(alice['user']['username'],password),schema='Session')['json']
with store.connect() as conn:
new=conn.execute('SELECT password_hash FROM users WHERE id=%s',(alice['id'],)).fetchone()[0]
tokens=[r[0] for r in conn.execute('SELECT token FROM sessions WHERE user_id=%s',(alice['id'],))]
assert '$argon2id$' in new and 'm=65536,t=3,p=2' in new and new!=old
assert hashlib.sha256(result['token'].encode()).hexdigest() in tokens and all(result['token']!=v and len(v)==64 for v in tokens)
rows+=['Argon2id old hash rehashed on successful login','DB stores SHA-256 token hashes only']
r=redis.Redis.from_url(os.environ['CACHE_URL'],decode_responses=True)
c.call('GET','/api/v1/users/me',actor=result)
for key in r.scan_iter('session:*'):
val=r.get(key) or '';assert result['token'] not in key+val and password not in key+val
rows.append('cache keys and values do not contain raw session tokens/passwords')
with store.connect() as conn:conn.execute("UPDATE sessions SET expires_at=now()-interval '1 second' WHERE token=%s",(hashlib.sha256(result['token'].encode()).hexdigest(),))
for _ in range(4):c.call('GET','/api/v1/users/me',401,actor=result)
rows.append('expired session rejected across replicas even after cache warmup')
c.call('POST','/api/v1/auth/sessions',413,raw=b'x'*65537,headers={'Content-Type':'application/json'})
rows.append('64 KiB body limit returns 413')
# Hold both global slots from distinct operator connections, prove cross-replica budget.
a=store.pool.getconn();b=store.pool.getconn()
try:
a.execute('SELECT pg_advisory_xact_lock(202707,0)');b.execute('SELECT pg_advisory_xact_lock(202707,1)')
for _ in range(4):
out=c.call('POST','/api/v1/auth/sessions',429,headers=basic(alice['user']['username'],password));assert out['headers'].get('Retry-After')
finally:a.rollback();b.rollback();store.pool.putconn(a);store.pool.putconn(b)
rows.append('two shared Argon2 slots enforce 429 with Retry-After')
reset()
remaining=60-time.time()%60
if remaining<30:time.sleep(remaining+1)
codes=[];instances=set();fake='unknown_'+uuid.uuid4().hex[:12]
for _ in range(12):
out=c.call('POST','/api/v1/auth/sessions',[401,429],headers=basic(fake,'wrong_password_123'))
codes.append(out['status']);instances.add(out['headers']['X-Instance-Id'])
if out['status']==429:assert out['headers'].get('Retry-After')
assert codes.count(401)==10 and codes.count(429)==2 and len(instances)>=2
rows.append('shared login limit: 10 x 401, then 2 x 429 across >=2 replicas')
# Latency of actual Argon2 settings on this operator container, not max throughput.
h=PasswordHasher(memory_cost=65536,time_cost=3,parallelism=2);lat=[]
for _ in range(5):
start=time.monotonic();h.hash('synthetic_benchmark_password');lat.append(round((time.monotonic()-start)*1000,2))
reset();r.close();store.pool.close()
print(json.dumps({'status':'PASS','checks':rows,'login_codes':codes,'replicas':len(instances),'argon2':{'memory_kib':65536,'time_cost':3,'parallelism':2,'samples_ms':lat,'median_ms':statistics.median(lat),'max_global_inflight':2,'global_attempts_per_minute':120}},indent=2))
+24
View File
@@ -0,0 +1,24 @@
"""Trusted operator checks all stored session representations and all ready originals."""
import hashlib,json,os,re
import redis
from app import store,object_store
store.pool.open(wait=True);r=redis.Redis.from_url(os.environ['CACHE_URL'],decode_responses=True)
try:
with store.connect() as c:
counts={table:c.execute('SELECT count(*) FROM '+table).fetchone()[0] for table in ['users','sessions','chats','messages','attachments','jobs']}
assert c.execute("SELECT count(*) FROM sessions WHERE token !~ '^[0-9a-f]{64}$'").fetchone()[0]==0
assert c.execute("SELECT count(*) FROM users WHERE password_hash NOT LIKE '$argon2id$%'").fetchone()[0]==0
originals=c.execute("SELECT object_key,sha256,size_bytes FROM attachments WHERE state='ready'").fetchall()
states=dict(c.execute('SELECT state,count(*) FROM jobs GROUP BY state').fetchall())
keys=0
for key in r.scan_iter('session:*'):
assert re.fullmatch(r'session:[0-9a-f]{64}',key)
payload=json.loads(r.get(key));assert 'token' not in payload and re.fullmatch(r'[0-9a-f]{64}',payload['token_hash']);keys+=1
for key,expected,size in originals:
obj=object_store.client.get_object(Bucket=object_store.bucket,Key=key)
try:data=obj['Body'].read(10485761)
finally:obj['Body'].close()
assert len(data)==size and hashlib.sha256(data).hexdigest()==expected
assert not states.get('queued',0) and not states.get('processing',0),states
print(json.dumps({'status':'PASS','dataset_counts':counts,'job_states':states,'cache_hash_entries_checked':keys,'all_db_session_tokens_hashed':True,'all_passwords_argon2id':True,'ready_originals_checked':len(originals),'all_original_bytes_match_protected_sha256':True},indent=2))
finally:r.close();store.pool.close();object_store.close()
+43
View File
@@ -0,0 +1,43 @@
"""Run only in trusted operator with /run/probes mounted, never in app/worker."""
import json
from pathlib import Path
import socket
import ssl
import struct
TRUST='/run/trust/ca.crt';PROBES=Path('/run/probes')
HTTP=b'GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n'
H2=b'PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n'+bytes.fromhex('000000040000000000')
ENDPOINTS=[('db',15432,'api',struct.pack('!II',8,80877103),False),('s3',19000,'worker',HTTP,False),('broker',16379,'worker',b'*1\r\n$4\r\nPING\r\n',False),('cache',16380,'api',b'*1\r\n$4\r\nPING\r\n',False),('collector',14317,'worker',H2,True),('collector',18889,'prometheus',HTTP,False),('collector',18888,'prometheus',HTTP,False),('prometheus',19090,'grafana',HTTP,False),('loki',13100,'collector',HTTP,False),('tempo',13200,'grafana',HTTP,False),('tempo',14317,'collector',H2,True)]
for addr in sorted({i[4][0] for i in socket.getaddrinfo('api',8444,type=socket.SOCK_STREAM)}):ENDPOINTS.append((addr,8444,'lb',b'GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n',False))
def probe(host,port,identity,payload,h2=False,wrong_name=False):
ctx=ssl.create_default_context(cafile=TRUST)
if identity:ctx.load_cert_chain(str(PROBES/identity/'service.pem'))
if h2:ctx.set_alpn_protocols(['h2'])
name='api' if port==8444 else host
try:
with socket.create_connection((host,port),timeout=4) as raw:
with ctx.wrap_socket(raw,server_hostname='invalid.example' if wrong_name else name) as s:
s.settimeout(4);s.sendall(payload);return bool(s.recv(4096))
except (OSError,ssl.SSLError):return False
rows=[]
for host,port,role,payload,h2 in ENDPOINTS:
accepted=probe(host,port,role,payload,h2)
assert accepted,(host,port,'allowed identity rejected')
negatives={label:not probe(host,port,identity,payload,h2) for label,identity in [('missing_cert',None),('foreign_CA','foreign-'+role),('expired','expired-'+role),('wrong_role','unauthorized')]}
negatives['wrong_server_SAN']=not probe(host,port,role,payload,h2,True)
assert all(negatives.values()),(host,port,negatives)
assert probe(host,port,role,payload,h2),(host,port,'positive control after negatives failed')
rows.append({'peer':'api' if port==8444 else host,'address':host,'port':port,'allowed_identity':role,'allowed':True,**negatives})
closed=[]
for host,ports in [('db',[5432]),('s3',[9000,9001]),('broker',[6379]),('cache',[6379]),('collector',[4317,8888,8889]),('prometheus',[9090]),('loki',[3100,9095]),('tempo',[3200,4317,9095]),('grafana',[3000])]:
for port in ports:
try:s=socket.create_connection((host,port),timeout=1);s.close();raise AssertionError((host,port,'plaintext reachable'))
except (ConnectionRefusedError,TimeoutError):closed.append(f'{host}:{port}')
for host,port,*_ in ENDPOINTS:
if port==8444:
try:s=socket.create_connection((host,8080),timeout=1);s.close();raise AssertionError('API bypass')
except (ConnectionRefusedError,TimeoutError):closed.append(f'{host}:8080')
print(json.dumps({'status':'PASS','rows':rows,'plaintext_closed':closed},indent=2))
+130
View File
@@ -0,0 +1,130 @@
"""Contract boundaries and object authorization; runs in Compose ops network."""
import hashlib
import ssl
import http.client
import io
import json
from pathlib import Path
import socket
import struct
import sys
import time
from urllib.parse import quote, urlsplit
import uuid
import zlib
from PIL import Image
sys.path.insert(0,str(Path(__file__).resolve().parent))
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
from client import Client, check, run
def main():
c=Client('https://lb:8443',ca_file='/run/trust/ca.crt',timeout=20)
alice,bob,eve,chat=c.bootstrap()
path='/api/v1/chats/'+chat['id']+'/attachments'
fixture=(Path(__file__).parent/'fixtures/sample.png').read_bytes()
cases=[]
def bad(label,status,data=fixture,mime='image/png',filename='test.png',actor=None):
c.call('POST',path+'?filename='+quote(filename,safe=''),status,actor=actor or alice,raw=data,headers={'Content-Type':mime})
cases.append({'case':label,'status':status})
bad('corrupt_png',415,b'not an image')
bad('truncated_png',415,fixture[:50])
bad('mime_spoof',415,mime='image/jpeg')
bad('unsupported_mime',415,mime='application/octet-stream')
bad('empty_payload',415,b'')
for filename in ('../secret.png','a\\b.png','x\x00.png','x\n.png','x\u202e.png','x'*256):
bad('unsafe_filename',400,filename=filename)
bad('foreign_chat_upload',404,actor=eve)
c.call('POST',path+'?filename=x.png',401,raw=fixture,headers={'Content-Type':'image/png'})
cases.append({'case':'unauthenticated_upload','status':401})
# Oversized dimensions are rejected using headers before a full raster decode.
data=bytearray(fixture)
data[16:24]=struct.pack('>II',10000,4001)
data[29:33]=struct.pack('>I',zlib.crc32(data[12:29])&0xffffffff)
bad('over_40_million_pixels',413,bytes(data))
# No large allocation or body transfer: reject declared size before reading.
parsed=urlsplit(c.base)
conn=http.client.HTTPSConnection(parsed.hostname,parsed.port,context=ssl.create_default_context(cafile='/run/trust/ca.crt'),timeout=10)
conn.putrequest('POST',path+'?filename=big.png')
for k,v in {'Authorization':'Bearer '+alice['token'],'Content-Type':'image/png','Content-Length':str(10485761)}.items():
conn.putheader(k,v)
conn.endheaders()
response=conn.getresponse()
check(response.status==413,'oversized content-length accepted')
response.read();conn.close()
cases.append({'case':'oversized_content_length_before_body','status':413})
# True streamed overflow, no Content-Length; response is read after the last
# chunk, even if the peer stopped accepting bytes once it knew the limit.
conn=http.client.HTTPSConnection(parsed.hostname,parsed.port,context=ssl.create_default_context(cafile='/run/trust/ca.crt'),timeout=15)
conn.putrequest('POST',path+'?filename=chunked.png')
conn.putheader('Authorization','Bearer '+alice['token'])
conn.putheader('Content-Type','image/png')
conn.putheader('Transfer-Encoding','chunked')
conn.endheaders()
try:
block=b'x'*65536
for _ in range(161):
conn.send(b'10000\r\n'+block+b'\r\n')
conn.send(b'0\r\n\r\n')
except (BrokenPipeError,ConnectionResetError):
pass
response=conn.getresponse()
check(response.status==413,'streamed byte limit not enforced')
response.read();conn.close()
cases.append({'case':'chunked_oversize','status':413})
att,content=c.attachment(alice,chat)
# Another member can reference an attachment; ownership is not required.
msg=c.message(bob,chat,'',attachments=[att['id']])['json']
check(msg['attachment_ids']==[att['id']],'member could not link attachment')
for suffix in ('','/content'):
c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=eve)
c.wait_ready(alice,att)
c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=unknown',404,actor=alice)
cases.append({'case':'foreign_attachment_metadata_and_bytes','status':404})
other=c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'other','member_ids':[alice['id']]},schema='Chat')['json']
other_path='/api/v1/chats/'+other['id']+'/messages'
for aid in (att['id'],str(uuid.uuid4())):
c.call('POST',other_path,404,actor=alice,body={'text':'','attachment_ids':[aid]},headers={'Idempotency-Key':uuid.uuid4().hex})
cases.append({'case':'cross_chat_and_unknown_attachment','status':404})
message_path='/api/v1/chats/'+chat['id']+'/messages'
for ids in ([att['id'],att['id']],['bad-id'],[str(uuid.uuid4()) for _ in range(11)]):
c.call('POST',message_path,400,actor=alice,body={'text':'','attachment_ids':ids},headers={'Idempotency-Key':uuid.uuid4().hex})
key=uuid.uuid4().hex
first=c.message(alice,chat,'',key=key,attachments=[att['id']])['json']
second=c.message(alice,chat,'',key=key,attachments=[att['id']])['json']
check(first==second,'attachment message replay changed')
c.call('POST',message_path,409,actor=alice,body={'text':'different','attachment_ids':[att['id']]},headers={'Idempotency-Key':key})
cases.append({'case':'attachment_idempotency_and_conflict','status':'201/409'})
# Full JPEG validation, including truncated entropy-coded body.
stream=io.BytesIO()
Image.new('RGB',(320,200),'blue').save(stream,'JPEG')
jpeg=stream.getvalue()
uploaded=c.call('POST',path+'?filename=photo.jpg',202,actor=alice,raw=jpeg,headers={'Content-Type':'image/jpeg'},schema='Attachment')['json']
c.wait_ready(alice,uploaded)
downloaded=c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content',actor=bob)
check(downloaded['bytes']==jpeg,'JPEG original changed')
bad('truncated_jpeg',415,jpeg[:-20],mime='image/jpeg')
# A disconnect before receiving all bytes creates neither intent nor object.
from app import store,object_store
store.pool.open(wait=True,timeout=15)
try:
def counts():
with store.connect() as db:
n=db.execute('SELECT count(*) FROM attachments').fetchone()[0]
return n,len(object_store.client.list_objects_v2(Bucket=object_store.bucket,Prefix='staging/').get('Contents',[]))
before=counts()
conn=http.client.HTTPSConnection(parsed.hostname,parsed.port,context=ssl.create_default_context(cafile='/run/trust/ca.crt'),timeout=5)
conn.putrequest('POST',path+'?filename=interrupted.png')
conn.putheader('Authorization','Bearer '+alice['token'])
conn.putheader('Content-Type','image/png')
conn.putheader('Content-Length',str(len(fixture)))
conn.endheaders();conn.send(fixture[:50]);conn.close()
time.sleep(1)
check(counts()==before,'aborted upload persisted partial data')
cases.append({'case':'interrupted_http_body','metadata_or_object_added':False})
finally:
store.pool.close();object_store.close()
print(json.dumps({'status':'PASS','cases':cases,'count':len(cases)},ensure_ascii=False,indent=2))
if __name__=='__main__':
run(main)
+46
View File
@@ -0,0 +1,46 @@
"""Same harmless capability probes for broad baseline and scoped worker."""
import json
import os
import sys
import uuid
if '--worker' in sys.argv:
from service import BaoClient
os.environ.update(BaoClient().get())
import psycopg
import redis
import boto3
from botocore.config import Config
from botocore.exceptions import ClientError
from psycopg.errors import InsufficientPrivilege
from redis.exceptions import NoPermissionError
b='messenger-attachments';rows={}
if '--worker' in sys.argv:
from psycopg.conninfo import conninfo_to_dict,make_conninfo
stolen=conninfo_to_dict(os.environ['DATABASE_URL']);stolen['user']='messenger'
try:psycopg.connect(make_conninfo(**stolen));raise AssertionError('worker escalated to DB administrator')
except psycopg.OperationalError as e:assert 'password authentication failed' in str(e)
db=psycopg.connect(os.environ['DATABASE_URL'])
for name,statement in [('db_jobs_read','SELECT id FROM jobs LIMIT 1'),('db_users_read','SELECT password_hash FROM users LIMIT 1'),('db_sessions_read','SELECT token FROM sessions LIMIT 1'),('db_original_metadata_write','UPDATE attachments SET sha256=sha256 WHERE false'),('db_jobs_delete','DELETE FROM jobs WHERE false'),('db_ddl','CREATE TABLE public.probe_'+uuid.uuid4().hex+'(id int)')]:
try:db.execute(statement);rows[name]=True
except InsufficientPrivilege:rows[name]=False
finally:db.rollback()
db.close()
s=boto3.client('s3',endpoint_url='http://127.0.0.1:19000',aws_access_key_id=os.environ['S3_ACCESS_KEY_ID'],aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY'],region_name='us-east-1',config=Config(signature_version='s3v4',s3={'addressing_style':'path'},retries={'max_attempts':0}))
def get(key):
r=s.get_object(Bucket=b,Key=key);r['Body'].read();r['Body'].close()
for name,call in [('s3_staging_read',lambda:get('staging/security-probe')),('s3_results_write',lambda:s.put_object(Bucket=b,Key='results/security-probe',Body=b'probe')),('s3_private_read',lambda:get('private/security-probe')),('s3_list_all',lambda:s.list_objects_v2(Bucket=b)),('s3_staging_delete',lambda:s.delete_object(Bucket=b,Key='staging/security-delete-probe'))]:
try:call();rows[name]=True
except ClientError as e:
assert e.response['ResponseMetadata']['HTTPStatusCode']==403,(name,e.response['Error']['Code']);rows[name]=False
s.close();r=redis.Redis.from_url(os.environ['BROKER_URL'])
for name,call in [('queue_ping',r.ping),('queue_inject',lambda:r.xadd('attachments.v1',{'probe':'invalid-envelope'})),('queue_other_stream',lambda:r.xpending('private.queue','probe'))]:
try:call();rows[name]=True
except NoPermissionError:rows[name]=False
except redis.ResponseError as e:
assert 'NOGROUP' in str(e);rows[name]=True
r.close()
if '--worker' in sys.argv:
expected={'db_jobs_read','s3_staging_read','s3_results_write','queue_ping'}
assert {k for k,v in rows.items() if v}==expected,rows
else:assert all(rows.values()),rows
print(json.dumps({'status':'PASS','mode':'worker' if '--worker' in sys.argv else 'broad_baseline','operations':rows},indent=2))