Лаб7: mTLS, Argon2id, OpenBao и исследование отзыва worker
Application / application (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

Майорова Софья, БВТ2301, на 5. Трек1. HTTPS/TLS/ACL,18 API tests,13 pipeline groups,3 compromise runs,clean clone,persistence. Original tests/API contract preserved; residual CVE triage in REPORT/security.
This commit is contained in:
2026-11-20 14:48:26 +03:00
parent 20afc2c790
commit 7353ab97a6
120 changed files with 12575 additions and 103 deletions
+120
View File
@@ -0,0 +1,120 @@
"""Actual rehash/expiry/shared limiter, allowed S3 prefixes and real TLS telemetry."""
import base64
import concurrent.futures
import hashlib
import json
from pathlib import Path
import secrets
import statistics
import sys
import time
from urllib.parse import urlencode
import uuid
sys.path[:0]=['/app/tests','/app/src']
from client import Client
from security_helpers import *
from passwords import HASHER,password_hash,verify
from argon2 import PasswordHasher,Type
from botocore.exceptions import ClientError
c=Client();start=time.time();alice,bob,eve,chat=c.bootstrap()
report={'passwords':{},'prefixes':{},'signals':{}}
pw=alice['registration']['password']
with db() as conn:
stored=conn.execute('SELECT password_hash FROM users WHERE 1=1 AND id=%s',(alice['id'],)).fetchone()['password_hash']
assert stored.startswith('$argon2id$v=19$m=32768,t=2,p=1$') and pw not in stored
rows=conn.execute('SELECT token_hash FROM sessions WHERE 1=1 AND user_id=%s',(alice['id'],)).fetchall()
assert rows and all(len(r['token_hash'])==64 and r['token_hash']!=alice['token'] for r in rows)
salt=secrets.token_bytes(16)
legacy='scrypt$16384$8$1$'+salt.hex()+'$'+hashlib.scrypt(pw.encode(),salt=salt,n=16384,r=8,p=1,dklen=32,maxmem=64*1024*1024).hex()
conn.execute('UPDATE users SET password_hash=%s WHERE 1=1 AND id=%s',(legacy,alice['id']))
basic='Basic '+base64.b64encode((alice['user']['username']+':'+pw).encode()).decode()
c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':basic},schema='Session')
with db() as conn:
assert conn.execute('SELECT password_hash FROM users WHERE 1=1 AND id=%s',(alice['id'],)).fetchone()['password_hash'].startswith('$argon2id$')
weak=PasswordHasher(time_cost=2,memory_cost=19456,parallelism=1,type=Type.ID).hash(pw)
conn.execute('UPDATE users SET password_hash=%s WHERE 1=1 AND id=%s',(weak,alice['id']))
c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':basic},schema='Session')
with db() as conn:
assert conn.execute('SELECT password_hash FROM users WHERE 1=1 AND id=%s',(alice['id'],)).fetchone()['password_hash'].startswith('$argon2id$v=19$m=32768,t=2,p=1$')
conn.execute("UPDATE sessions SET expires_at=clock_timestamp()+INTERVAL '1 second' WHERE 1=1 AND token_hash=%s",(hashlib.sha256(eve['token'].encode()).hexdigest(),))
time.sleep(1.15)
c.call('GET','/api/v1/users/me',401,actor=eve)
report['passwords'].update(argon2id_and_session_hashes=True,legacy_scrypt_rehashed=True,argon2_parameter_rehash=True,real_expiry_401=True)
# No credentials retained in output; requests include nonexistent synthetic login.
bad='Basic '+base64.b64encode(b'no_such_synthetic_user:incorrect-password').decode()
def attempt(_):return c.call('POST','/api/v1/auth/sessions',[401,429],headers={'Authorization':bad})
with concurrent.futures.ThreadPoolExecutor(max_workers=40) as pool:attempts=list(pool.map(attempt,range(100)))
limited=[r for r in attempts if r['status']==429]
assert limited and all(r['headers'].get('Retry-After')=='1' for r in limited)
instances=sorted({r['headers']['X-Instance-Id'] for r in attempts});assert len(instances)==2
report['shared_rate_limit']={'requests':len(attempts),'limited_429':len(limited),'invalid_401':sum(r['status']==401 for r in attempts),'actual_replicas':len(instances),'retry_after_seconds':1,'kdf_slots_per_replica':2}
# Benchmark is not an attack: bounded pure KDF timings at the same operator-container CPU cap.
timings={}
for memory in [19456,32768,65536]:
ph=PasswordHasher(time_cost=2,memory_cost=memory,parallelism=1,type=Type.ID)
samples=[]
for _ in range(10):
t=time.perf_counter();h=ph.hash('synthetic-kdf-budget');ph.verify(h,'synthetic-kdf-budget');samples.append(time.perf_counter()-t)
timings[str(memory)]={'hash_plus_verify_median_ms':statistics.median(samples)*1000,'hash_plus_verify_max_ms':max(samples)*1000,'runs':10}
report['kdf_budget']={'CPU_limit':.5,'timings':timings,'chosen_memory_kib':32768,'max_kdf_memory_mib_per_api':64,'api_memory_limit_mib':256,'note':'Timings include hash+verify at 0.5 CPU; API has 1 CPU and at most two concurrent KDF operations.'}
# A sampled real upload proves API -> outbox -> producer -> consumer -> S3/DB, all transports TLS.
traceid=uuid.uuid4().hex
att=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=security-canary.png',202,
actor=alice,raw=Path('/app/tests/fixtures/sample.png').read_bytes(),headers={'Content-Type':'image/png','traceparent':'00-'+traceid+'-1122334455667788-01'},schema='Attachment')['json']
ready=c.wait_ready(alice,att)
with db() as conn:
row=conn.execute('SELECT staging_key,object_key FROM attachments WHERE 1=1 AND id=%s',(att['id'],)).fetchone()
worker=s3('worker');bucket='messenger-attachments'
assert worker.get_object(Bucket=bucket,Key=row['staging_key'])['Body'].read()==Path('/app/tests/fixtures/sample.png').read_bytes()
assert worker.get_object(Bucket=bucket,Key=row['object_key'])['Body'].read()
allowed='results/audit-'+uuid.uuid4().hex+'/original'
worker.put_object(Bucket=bucket,Key=allowed,Body=b'synthetic-result',IfNoneMatch='*')
def s3deny(operation):
try:operation()
except ClientError as error:assert error.response['ResponseMetadata']['HTTPStatusCode']==403;return True
raise AssertionError('S3 operation unexpectedly allowed')
assert s3deny(lambda:s3('worker').put_object(Bucket=bucket,Key='staging/forbidden',Body=b'x'))
assert s3deny(lambda:s3('worker').delete_object(Bucket=bucket,Key=row['staging_key']))
assert s3deny(lambda:s3('worker').delete_object(Bucket=bucket,Key=allowed))
assert s3deny(lambda:s3('worker').put_object(Bucket=bucket,Key=allowed,Body=b'overwrite'))
assert s3deny(lambda:s3('worker').list_objects_v2(Bucket=bucket))
assert s3deny(lambda:s3('worker').create_bucket(Bucket='unauthorized-bucket'))
assert s3deny(lambda:s3('api').put_object(Bucket=bucket,Key='results/forbidden',Body=b'x'))
assert s3deny(lambda:s3('worker').put_object(Bucket=bucket,Key='results/../staging/traversal',Body=b'x',IfNoneMatch='*'))
report['prefixes']={'worker_read_staging_and_results':True,'worker_create_immutable_result':True,'denied':['worker PUT staging','worker DELETE staging','worker DELETE results','worker unconditional overwrite','worker bucket list','worker create bucket','API PUT results','traversal key']}
deadline=time.monotonic()+90
while True:
try:
_,raw=http('https://tempo:8443/api/traces/'+traceid)
trace=json.loads(raw)
if trace.get('batches',trace.get('resourceSpans')):break
except Exception:pass
assert time.monotonic()<deadline,'Real trace missing';time.sleep(1)
spans=[]
for batch in trace.get('batches',trace.get('resourceSpans',[])):
for scope in batch.get('scopeSpans',[]):spans.extend(scope['spans'])
names={x['name'] for x in spans}
assert {'attachment publish','attachment process','db.transaction'}<=names
assert any(n.startswith('s3.') for n in names)
producer=next(x for x in spans if x['name']=='attachment publish')
consumer=next(x for x in spans if x['name']=='attachment process')
assert consumer['parentSpanId']==producer['spanId']
query='{service_name=~"messenger-.*"} | json | trace_id="'+traceid+'"'
params=urlencode({'query':query,'start':str(int(start*1e9)),'end':str(time.time_ns()),'limit':'100'})
_,raw=http('https://loki:8443/loki/api/v1/query_range?'+params)
logs=json.loads(raw)['data']['result'];assert logs
flat=[json.loads(line) for stream in logs for stamp,line in stream['values']]
assert {'attachment_accepted','job_published','job_processed'}<={r['event'] for r in flat}
serialized=json.dumps(trace)+json.dumps(flat)
for secret in [pw,alice['token'],alice['registration']['username'],'security-canary.png',*SETTINGS.values()]:
assert secret not in serialized,'Secret/business payload in telemetry'
_,raw=http('https://prometheus:8443/api/v1/query?'+urlencode({'query':'up'}))
up=json.loads(raw)['data']['result'];assert len(up)>=2 and all(float(x['value'][1])==1 for x in up)
_,raw=http('https://prometheus:8443/api/v1/query?'+urlencode({'query':'http_server_requests_total'}))
metrics=json.loads(raw)['data']['result'];assert metrics
for r in metrics:
assert not set(r['metric'])&{'user_id','chat_id','message_id','attachment_id','request_id','filename','trace_id'}
report['signals']={'trace_id':traceid,'spans':len(spans),'services_and_job_events_correlated':True,'producer_consumer_parent_match':True,'tls_prometheus_scrape_targets':len(up),'sensitive_canaries_absent':True,'forbidden_metric_labels_absent':True}
# Full sanitized trace is useful evidence; no passwords, tokens, keys, filenames or bodies.
print(json.dumps({'checks':report,'trace':trace,'logs':flat},indent=2))
+16
View File
@@ -0,0 +1,16 @@
"""Reconstruct prior lab6 broad-credential consequences in operator-controlled fixtures.
This is a capability baseline, not an attack against the real lab6 installation."""
import json
import uuid
from security_helpers import *
with db() as conn:
counts={t:conn.execute('SELECT count(*) AS n FROM '+t).fetchone()['n'] for t in ['users','sessions','messages']}
assert bus('operator').config_get('maxmemory')
key='staging/baseline-fixture-'+uuid.uuid4().hex
# Same worker S3 key, but the old trusted-network model has no role/prefix mTLS gate.
# Operator transport emulates that boundary explicitly; it is not a claim of privilege escalation.
client=s3('operator','worker')
client.put_object(Bucket='messenger-attachments',Key=key,Body=b'controlled-synthetic-baseline')
assert client.get_object(Bucket='messenger-attachments',Key=key)['Body'].read()==b'controlled-synthetic-baseline'
client.delete_object(Bucket='messenger-attachments',Key=key)
print(json.dumps({'model':'lab6-style shared full database role and bucket-wide worker S3 key; emulated by explicit operator fixture, NOT live lab6','business_table_row_counts_visible':counts,'bucket_wide_worker_key_can_write_and_delete_staging_without_identity_prefix_gate':True,'fixture_deleted':True,'modeled_broad_broker_CONFIG_allowed':True},indent=2))
+51
View File
@@ -0,0 +1,51 @@
"""Independent local Git clone, empty project volumes and new CA/secrets; disposable project only."""
from pathlib import Path
import subprocess,os,json,time,uuid,shutil
ROOT=Path(__file__).resolve().parents[1]
name='mtusi-lab7-clean-'+uuid.uuid4().hex[:8]
clone=ROOT/'build'/name
version=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip()
subprocess.run(['git','clone','--no-hardlinks',str(ROOT),str(clone)],check=True,stdout=subprocess.DEVNULL)
env=dict(os.environ,COMPOSE_PROJECT_NAME=name,APP_PORT='18444',GRAFANA_PORT='13408',BAO_PORT='18208',
BAO_OPERATOR_URL='https://localhost:18208',BASE_URL='https://localhost:18444',
CA_FILE=str(clone/'pki/lb/ca.crt'),GRAFANA_URL='https://localhost:13408')
started=time.monotonic()
results={}
proof=None
with (ROOT/'evidence/clean-clone.txt').open('w') as out:
def run(label,args,extract=None):
begin=time.monotonic()
proc=subprocess.run(args,cwd=clone,env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
out.write('\n$ '+label+'\n'+proc.stdout);out.flush()
if proc.returncode:raise RuntimeError(label+' failed; see clean-clone log')
results[label]={'pass':True,'seconds':round(time.monotonic()-begin,3)}
if extract:
text=proc.stdout
data=json.loads(text[text.index('{'):])
(clone/'evidence'/extract).write_text(json.dumps(data,indent=2)+'\n')
try:
assert not (clone/'operator').exists() and not (clone/'pki').exists()
run('fresh bootstrap, build, migrations and verified HTTPS ready',['python3','scripts/start.py'])
run('check + public HTTPS smoke + untrusted CA +18 API/image tests',
['make','check','test','test-security','test-student','BASE_URL='+env['BASE_URL'],'CA_FILE='+env['CA_FILE']])
run('internal TLS/identity/raw-port/ACL audit',
['docker','compose','--profile','tools','run','--rm','--no-deps','audit','/app/student-tests/tls_audit.py'],'tls-audit.json')
run('Argon/rehash/expiry/rate limit/S3 ACL/real trace canaries',
['docker','compose','--profile','tools','run','--rm','--no-deps','audit','/app/student-tests/auth_and_signals.py'],'auth-signals.json')
run('full business + historical telemetry + existing Bao store restart',['python3','student-tests/persistence_tls.py'])
run('Grafana HTTPS/mTLS datasources and21 panels',['python3','student-tests/grafana_tls.py'])
run('effective hardening and actual listeners',['python3','student-tests/hardening.py'])
proof={'pass':True,'commit_tested':version,'project':name,'fresh_secrets_pki_and_volumes':True,
'independent_ports':[18444,13408,18208],'results':results,'seconds':round(time.monotonic()-started,3),
'main_lab7_data_reset':False}
finally:
cleanup=subprocess.run(['docker','compose','down','-v','--remove-orphans'],cwd=clone,env=env,
stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
out.write('\n$ cleanup ONLY disposable project '+name+'\n'+cleanup.stdout)
assert cleanup.returncode==0
assert clone.parent==ROOT/'build' and clone.name.startswith('mtusi-lab7-clean-')
shutil.rmtree(clone)
if proof:
proof['only_disposable_project_volumes_deleted']=True
(ROOT/'evidence/clean-clone.json').write_text(json.dumps(proof,indent=2)+'\n')
print('PASS independent clean clone, new secrets and empty volumes; only disposable project removed.')
+74
View File
@@ -0,0 +1,74 @@
"""Track1: actual worker scope, identity revoke/secret rotation and durable job recovery."""
import concurrent.futures
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
import uuid
ROOT=Path(__file__).resolve().parents[1]
sys.path[:0]=[str(ROOT/'tests'),str(ROOT/'scripts')]
from client import Client
from rotate_worker import run as rotate
from bao_operator import call,unseal
def dc(*a):return subprocess.check_output(['docker','compose',*a],cwd=ROOT,text=True)
def audit(script):return json.loads(dc('--profile','tools','run','--rm','--no-deps','audit','/app/student-tests/'+script))
def resource_snapshot():
ids=dc('ps','-q','api','worker','dispatcher').split()
raw=subprocess.check_output(['docker','stats','--no-stream','--format','{{json .}}',*ids],text=True)
return [{key:row[key] for key in ['Name','CPUPerc','MemUsage','MemPerc','PIDs']} for row in map(json.loads,raw.splitlines())]
c=Client();a,b,e,chat=c.bootstrap()
result={'hypothesis':'Service-specific least privilege reduces stolen worker credential scope. Revocation and rollover stop old access while already accepted jobs remain durable.','baseline_model':audit('baseline_model.py')}
# Run the privilege probe IN the existing worker UID/namespace/mounts, not only an operator test client.
code=(ROOT/'student-tests/worker_access.py').read_text()
result['actual_worker_before']=json.loads(dc('exec','-T','worker','python','-c',code))
result['resource_snapshots_before']=resource_snapshot()
dc('stop','worker')
attachments=[c.attachment(a,chat)[0] for _ in range(6)]
fixture=(ROOT/'tests/fixtures/sample.png').read_bytes()
stop=threading.Event();messages=[];latencies=[];errors=[];started=time.monotonic()
def load():
index=0
while not stop.is_set():
try:
r=c.message(a,chat,'revoke-load-'+str(index));messages.append(r['json']['id']);latencies.append(r['elapsed'])
except Exception as error:errors.append(type(error).__name__)
index+=1;stop.wait(.1)
thread=threading.Thread(target=load);thread.start()
try:
image_before=dc('images','-q','worker').strip()
result['rotation']=rotate()
time.sleep(6) # Bound old persistent proxy connections by hard-stop-after5s, do not assume immediate invalidation.
result['old_access']=audit('old_worker_denied.py')
ready=[]
for att in attachments:
value=c.wait_ready(a,att);content=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=a)['bytes']
assert content==fixture;ready.append(value['id'])
assert dc('images','-q','worker').strip()==image_before
result['new_worker_after']=json.loads(dc('exec','-T','worker','python','-c',code))
finally:
stop.set();thread.join(timeout=5)
dc('up','-d','--no-deps','worker')
items=[];cursor=None
while True:
page=c.call('GET','/api/v1/chats/'+chat['id']+'/messages'+('?cursor='+cursor if cursor else ''),actor=a,schema='MessagePage')['json']
items+=page['items'];cursor=page['next_cursor']
if not cursor:break
assert set(messages)<={m['id'] for m in items}
elapsed=time.monotonic()-started
percentile=lambda p:sorted(latencies)[max(0,math.ceil(len(latencies)*p)-1)] if latencies else None
result['workload']={'messages_confirmed':len(messages),'errors':errors,'all_confirmed_messages_found':True,
'queued_images_before_revoke':len(attachments),'same_images_ready_after_rollover':len(ready),'original_bytes_match':True,
'elapsed_seconds':round(elapsed,3),'success_rps':round(len(messages)/elapsed,3),
'p50_success_seconds':percentile(.50),'p95_success_seconds':percentile(.95),'p99_success_seconds':percentile(.99),
'load_profile':'One HTTP writer, 100ms wait after completion (closed loop, nominal ceiling10/s); six queued PNGs, no saturation search.',
'image_unchanged':True,'no_plaintext_or_skip_verify_fallback':True}
result['resource_snapshots_after']=resource_snapshot()
(ROOT/'evidence/worker-compromise.json').write_text(json.dumps(result,indent=2)+'\n')
print('PASS: actual non-root worker scope, old identity/secret denial, same queued jobs ready and confirmed messages preserved.')
if not messages:raise AssertionError('No workload')
+36
View File
@@ -0,0 +1,36 @@
"""Verify provisioned dashboard/datasources over native HTTPS and authenticated operator API."""
import base64
import json
import ssl
from urllib.parse import urlencode
import urllib.request
from pathlib import Path
import os
ROOT=Path(__file__).resolve().parents[1]
settings=json.loads((ROOT/'operator/settings.json').read_text())
context=ssl.create_default_context(cafile=str(ROOT/'pki/grafana/ca.crt'))
op=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=context))
base=os.environ.get('GRAFANA_URL','https://localhost:13407')
def read(path,auth=True):
headers={}
if auth:headers['Authorization']='Basic '+base64.b64encode(('operator:'+settings['grafana']).encode()).decode()
req=urllib.request.Request(base+path,headers=headers)
with op.open(req,timeout=8) as r:return json.load(r)
listing=read('/api/datasources');assert len(listing)==3
sources=[read('/api/datasources/uid/'+s['uid']) for s in listing]
for s in sources:
assert s['url'].startswith('https://') and not s['jsonData'].get('tlsSkipVerify')
assert s['jsonData']['tlsAuth'] and s['secureJsonFields']['tlsClientKey']
dash=read('/api/dashboards/uid/messenger-lab7')
assert len(dash['dashboard']['panels'])>=12
up=read('/api/datasources/proxy/uid/prometheus/api/v1/query?'+urlencode({'query':'up'}))['data']['result']
assert len(up)>=2 and all(float(x['value'][1])==1 for x in up)
try:read('/api/datasources',False)
except urllib.error.HTTPError as e:assert e.code==401
else:raise AssertionError('Unauthenticated admin UI API allowed')
report={'native_https_verified_ca_hostname':True,'anonymous_datasource_api_401':True,'authenticated_operator_api':True,
'tls_mtls_datasources':sorted(s['name'] for s in sources),'dashboard_uid':'messenger-lab7','panels':len(dash['dashboard']['panels']),
'actual_scrape_targets_up':len(up),'loki_trace_link_provisioned':any(s['name']=='Loki' and s['jsonData'].get('derivedFields') for s in sources)}
assert report['loki_trace_link_provisioned']
(ROOT/'evidence/grafana-tls.json').write_text(json.dumps(report,indent=2)+'\n')
print('PASS: native Grafana HTTPS/operator auth, all TLS client datasources, real Prometheus data and trace link configuration.')
+52
View File
@@ -0,0 +1,52 @@
"""Inspect effective container hardening and the actual network namespace listeners."""
import json
import os
from pathlib import Path
import socket
import ssl
import subprocess
ROOT=Path(__file__).resolve().parents[1]
def output(*args):return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True)
def inspect(container):return json.loads(subprocess.check_output(['docker','inspect',container],text=True))[0]
ids=output('ps','-aq').split()
rows=[];listeners={}
for identifier in ids:
data=inspect(identifier);role=data['Config']['Labels']['com.docker.compose.service'];host=data['HostConfig']
assert not host['Privileged'] and host['NetworkMode']!='host'
assert not any('docker.sock' in m['Destination'] for m in data['Mounts'])
assert host['Memory']>0 and host['NanoCpus']>0
assert 'ALL' in host['CapDrop']
assert any(x.startswith('no-new-privileges') for x in host['SecurityOpt'])
if role in ['api','worker','dispatcher']:
assert data['Config']['User']=='10001:10001' and host['ReadonlyRootfs'] and not host.get('CapAdd')
assert not any(m['Destination'].startswith('/operator') for m in data['Mounts'])
for port,bindings in (host['PortBindings'] or {}).items():
assert role in ['lb','bao','grafana']
assert all(b['HostIp']=='127.0.0.1' for b in bindings)
rows.append({'service':role,'user':data['Config']['User'],'read_only':host['ReadonlyRootfs'],
'cap_drop':host['CapDrop'],'cap_add':host.get('CapAdd') or [],'no_new_privileges':True,
'memory_bytes':host['Memory'],'nano_cpus':host['NanoCpus'],'host_ports':host['PortBindings'] or {}})
if role in ['s3','broker','redis','otel-collector','loki','tempo','prometheus','api','lb','bao','grafana'] and data['State']['Running']:
text=subprocess.check_output(['docker','exec',identifier,'cat','/proc/net/tcp'],text=True)
endpoints=[]
for line in text.splitlines()[1:]:
parts=line.split()
if parts[3]!='0A':continue
address,port=parts[1].split(':')
ip=socket.inet_ntoa(bytes.fromhex(address)[::-1]);port=int(port,16)
endpoints.append({'address':ip,'port':port})
key=role+('-'+str(len([r for r in rows if r['service']==role])) if role=='api' else '')
listeners[key]=endpoints
allowed={'api':{8080},'lb':{8443},'s3':{8443},'broker':{8443},'redis':{8443},'otel-collector':{8443,8444,8445},'loki':{8443},'tempo':{8443,8444},'prometheus':{8443},'bao':{8200,8201},'grafana':{3000}}[role]
for e in endpoints:
if e['address']=='0.0.0.0':assert e['port'] in allowed,(role,e)
# Explicit external wrong hostname, over a successful local TCP connection.
ctx=ssl.create_default_context(cafile=str(ROOT/'pki/lb/ca.crt'))
try:
with socket.create_connection(('127.0.0.1',int(os.environ.get('APP_PORT','18443'))),timeout=3) as raw:
ctx.wrap_socket(raw,server_hostname='wrong-hostname.invalid')
except ssl.SSLCertVerificationError:wrong_hostname=True
else:raise AssertionError('Hostname validation off')
(ROOT/'evidence/hardening.json').write_text(json.dumps({'containers':rows,'ipv4_listeners':listeners,
'wrong_external_hostname_rejected':wrong_hostname,'note':'Raw local hops share only their proxy namespace; PostgreSQL is native TLS. DNS on127.0.0.11 is platform-local, not a business listener.'},indent=2)+'\n')
print('PASS effective limits, non-root apps, drop ALL/no-new-privileges/read-only; published loopback TLS only, local raw listeners, wrong hostname rejected.')
+19
View File
@@ -0,0 +1,19 @@
"""Read only historical telemetry via the operator identity and verified TLS."""
import json
import sys
from urllib.parse import urlencode
from security_helpers import http
traceid=sys.argv[1];at=sys.argv[2]
_,raw=http('https://tempo:8443/api/traces/'+traceid)
trace=json.loads(raw)
ids=[]
for batch in trace.get('batches',trace.get('resourceSpans',[])):
for scope in batch.get('scopeSpans',[]):ids.extend(x['spanId'] for x in scope['spans'])
assert ids
query='{service_name=~"messenger-.*"} | json | trace_id="'+traceid+'"'
_,raw=http('https://loki:8443/loki/api/v1/query_range?'+urlencode({'query':query,'start':str(int((float(at)-3600)*1e9)),'end':str(int((float(at)+300)*1e9)),'limit':'100'}))
records=[line for stream in json.loads(raw)['data']['result'] for stamp,line in stream['values']]
assert records
_,raw=http('https://prometheus:8443/api/v1/query?'+urlencode({'query':'sum(http_server_requests_total)','time':at}))
metric=json.loads(raw)['data']['result'];assert metric
print(json.dumps({'trace_spans':sorted(ids),'logs':sorted(records),'fixed_time_metric':metric},sort_keys=True))
+24
View File
@@ -0,0 +1,24 @@
"""Small deterministic PNG helpers; generation happens outside measurement."""
import random
import struct
import zlib
def chunk(name, data):
return struct.pack('!I', len(data)) + name + data + struct.pack('!I', zlib.crc32(name + data) & 0xffffffff)
def png(width, height, noise=False, rgb=True):
channels = 3 if rgb else 1
rand = random.Random(2301)
encoded = zlib.compressobj(1)
parts = []
for _ in range(height):
line = bytes(rand.getrandbits(8) for _ in range(width * channels)) if noise else b'\x7f' * (width * channels)
parts.append(encoded.compress(b'\0' + line))
parts.append(encoded.flush())
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!IIBBBBB', width, height, 8, 2 if rgb else 0, 0, 0, 0)) + chunk(b'IDAT', b''.join(parts)) + chunk(b'IEND', b'')
def bomb():
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('!IIBBBBB', 10000, 4001, 8, 2, 0, 0, 0)) + chunk(b'IDAT', zlib.compress(b'x')) + chunk(b'IEND', b'')
+33
View File
@@ -0,0 +1,33 @@
"""Operator probes with the saved compromised cert and old credentials, on fresh connections."""
import json
from pathlib import Path
from security_helpers import *
from botocore.exceptions import ClientError
old=json.loads(Path('/operator/revoked-worker-settings.json').read_text())
results={}
for host,port,path in [('broker',8443,'/'),('s3',8443,'/messenger-attachments'),('otel-collector',8443,'/v1/traces')]:
try:raw=probe(host,port,'revoked-worker',path)
except (OSError,ssl.SSLError):raw=b''
assert not raw,'Revoked leaf still works at '+host
results[host]='revoked leaf denied on fresh connection'
try:db('worker',old['worker'])
except psycopg.OperationalError as error:assert 'password authentication failed' in str(error)
else:raise AssertionError('Old database password accepted')
results['postgres']='old password denied'
try:
redis.Redis(host='broker',port=8443,username='worker',password=old['broker_worker'],ssl=True,
ssl_ca_certs='/tls/ca.crt',ssl_certfile=str(cert('worker')/'tls.crt'),ssl_keyfile=str(cert('worker')/'tls.key'),
ssl_check_hostname=True,socket_connect_timeout=2,socket_timeout=3).ping()
except redis.AuthenticationError:results['broker_old_password_with_new_certificate']='AUTH rejected'
else:raise AssertionError('Old broker password still works')
try:bao('auth/cert/login','revoked-worker',{'name':'worker'})
except urllib.error.HTTPError as error:assert error.code in (400,403)
else:raise AssertionError('Old leaf still authenticates to Bao')
results['bao']='old exact leaf denied'
# A valid NEW client cert with the OLD S3 key must still fail, proving secret rotation independently.
SETTINGS['s3_worker_key']=old['s3_worker_key'];SETTINGS['s3_worker']=old['s3_worker']
try:s3('worker').head_bucket(Bucket='messenger-attachments')
except ClientError as error:assert error.response['ResponseMetadata']['HTTPStatusCode']==403
else:raise AssertionError('Old S3 credential still works')
results['s3_old_key_with_new_certificate']='403'
print(json.dumps(results,indent=2))
+29
View File
@@ -0,0 +1,29 @@
"""Original public persistence plus real historical signals and existing Bao initialization."""
import json
import os
from pathlib import Path
import subprocess
import time
ROOT=Path(__file__).resolve().parents[1]
proof=json.loads((ROOT/'evidence/auth-signals.json').read_text())
traceid=proof['checks']['signals']['trace_id'];at=str(time.time()-5)
def snap():
value=subprocess.check_output(['docker','compose','--profile','tools','run','--rm','--no-deps','audit','/app/student-tests/history_snapshot.py',traceid,at],cwd=ROOT,text=True)
return json.loads(value)
before=snap()
out=subprocess.run(['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL='+os.environ['BASE_URL'],'CA_FILE='+os.environ['CA_FILE']],cwd=ROOT,capture_output=True,text=True)
(ROOT/'evidence/persistence.txt').write_text(out.stdout+out.stderr)
assert out.returncode==0,out.stdout[-300:]
deadline=time.monotonic()+60
while True:
try:after=snap();break
except Exception:
assert time.monotonic()<deadline;time.sleep(1)
assert set(before['trace_spans'])<=set(after['trace_spans'])
assert set(before['logs'])<=set(after['logs'])
assert before['fixed_time_metric']==after['fixed_time_metric']
result={'public_business_persistence':True,'old_bearer_and_original_attachment_preserved':True,
'same_trace_id':traceid,'old_spans_preserved':len(before['trace_spans']),'old_logs_preserved':len(before['logs']),
'fixed_time_prometheus_metric_preserved':True,'at_epoch':float(at),'bao_restarted_and_operator_unsealed_without_reinit':True}
(ROOT/'evidence/tls-persistence.json').write_text(json.dumps(result,indent=2)+'\n')
print('PASS: original HTTPS persistence and historical Tempo/Loki/Prometheus; Bao existing store survives.')
+188
View File
@@ -0,0 +1,188 @@
"""Real DB/S3/Redis fault injection. Stop production worker/dispatcher first."""
import concurrent.futures
import hashlib
import io
import json
import os
from pathlib import Path
import subprocess
import sys
import time
import uuid
sys.path[:0]=['/app/src',str(Path.cwd()/'tests')]
from PIL import Image
from client import Client
from pipeline import STREAM,GROUP,broker,connect,event,dispatch_once,process,ack
from objects import Objects
from postgres import setting
from admin import replay,version,cleanup
def main():
c=Client();alice,bob,eve,chat=c.bootstrap()
bus=broker(); objects=Objects(setting)
report={'invariants':{},'faults':[]}
def fetch(aid):
with connect() as conn:
a=conn.execute('SELECT * FROM attachments WHERE 1=1 AND id = %s',(aid,)).fetchone()
j=conn.execute('SELECT * FROM attachment_jobs WHERE 1=1 AND id = %s',(a['current_job_id'],)).fetchone()
return a,j
def upload(raw=None,mime='image/png'):
if raw is None: a,_=c.attachment(alice,chat)
else:a=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=research.png',202,actor=alice,raw=raw,headers={'Content-Type':mime},schema='Attachment')['json']
return a,fetch(a['id'])[1]
def run_once(fault=None):
args=[sys.executable,'/app/src/pipeline.py','work','--once']
if fault:args+=['--fault-point',fault]
return subprocess.run(args,capture_output=True,timeout=30).returncode
def drain():
for _ in range(200):
batch=bus.xreadgroup(GROUP,'research-drain',{STREAM:'>'},count=1)
if not batch:break
for mid,data in batch[0][1]:process(json.loads(data['event']));ack(bus,mid)
def expire(job):
with connect() as conn:
conn.execute("UPDATE attachment_jobs SET lease_until = clock_timestamp() - INTERVAL '1 second' WHERE 1=1 AND id = %s",(job['id'],))
def recover(aid):
until=time.monotonic()+20
while time.monotonic()<until:
dispatch_once(bus);drain()
a,j=fetch(aid)
if a['state']=='ready':return a,j
time.sleep(.1)
raise AssertionError('not recovered')
for mid,data in bus.xautoclaim(STREAM,GROUP,'initial-recovery',min_idle_time=0,start_id='0-0',count=100)[1]:
process(json.loads(data['event']));ack(bus,mid)
# COMMIT -> no publisher yet: one queued row, no Redis message, then automatic outbox pass.
a,j=upload()
assert fetch(a['id'])[0]['state']=='queued'
assert c.call('GET','/api/v1/attachments/'+a['id']+'/content',409,actor=bob)
c.message(bob,chat,'queued is linkable',attachments=[a['id']])
dispatch_once(bus);drain();assert fetch(a['id'])[0]['state']=='ready'
report['invariants']['commit_before_publish_recovered']=True
# Broker accepted XADD but publisher died before marking outbox: true exit(77).
a,j=upload()
code=subprocess.run([sys.executable,'/app/src/pipeline.py','dispatch','--once','--fault-point','after_publish'],capture_output=True,timeout=10).returncode
assert code==77
dispatch_once(bus);drain()
assert fetch(a['id'])[0]['state']=='ready'
report['invariants']['publish_before_marker_duplicate_safe']=True
for point in ['before_side_effect','after_original','after_objects','after_commit']:
a,j=upload();dispatch_once(bus)
code=run_once(point);assert code==77,(point,code)
before,job=fetch(a['id'])
if point not in ('after_commit','before_side_effect'):expire(job)
result,job=recover(a['id'])
assert c.call('GET','/api/v1/attachments/'+a['id']+'/content',actor=bob)['bytes']==(Path.cwd()/'tests/fixtures/sample.png').read_bytes()
reclaimed=bus.xautoclaim(STREAM,GROUP,'post-crash-redelivery',min_idle_time=0,start_id='0-0',count=100)[1]
for mid,data in reclaimed:
process(json.loads(data['event']));ack(bus,mid)
assert bus.xpending(STREAM,GROUP)['pending']==0
keys=objects.client.list_objects_v2(Bucket=objects.bucket,Prefix='results/'+a['id']+'/v1/').get('Contents',[])
assert len(keys)==4,(point,len(keys))
report['faults'].append({'point':point,'exit_code':code,'state_at_crash':before['state'],'recovered':result['state'],'attempts':job['attempt'],'result_objects':len(keys)})
report['invariants']['crashes_before_after_side_effect_and_commit']=True
bus.xadd(STREAM,{'event':json.dumps({'not':'a job'})})
assert run_once()==0
assert bus.xlen('rejected-jobs')>=1
report['invariants']['invalid_envelope_observable_dlq']=True
# Duplicate/reorder through broker on a completed job: no extra attempt/effect.
a,j=upload();dispatch_once(bus);drain();before,done=fetch(a['id'])
old=event(j)
for attempt in [2,1,3,1,1]:bus.xadd(STREAM,{'event':json.dumps(dict(old,attempt=attempt))})
drain();after,done2=fetch(a['id'])
assert before['variants']==after['variants'] and done2['attempt']==done['attempt']
report['invariants']['duplicate_and_reorder_no_second_effect']=True
# Race two consumers with the SAME logical job, not just one serial duplicate.
a,j=upload();e=event(j)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: results=list(pool.map(lambda _:process(e),range(2)))
assert fetch(a['id'])[0]['state']=='ready' and sorted(results)==['noop','ready']
report['invariants']['concurrent_duplicate_single_claim']=True
# Pause actual old process after all immutable side effects, advance version and finish v2.
a,j=upload();e=event(j)
directory=Path('/tmp')/('fence-'+uuid.uuid4().hex);directory.mkdir();marker=directory/'paused';release=directory/'release'
code="import sys,json,time;from pathlib import Path;sys.path.insert(0,'/app/src');from pipeline import process\ndef hook(point,job):\n if point=='after_objects':\n Path(sys.argv[2]).write_text('paused')\n while not Path(sys.argv[3]).exists():time.sleep(.05)\nprint(process(json.loads(sys.argv[1]),hook))"
child=subprocess.Popen([sys.executable,'-c',code,json.dumps(e),str(marker),str(release)],stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
try:
deadline=time.monotonic()+20
while not marker.exists():
assert child.poll() is None
assert time.monotonic()<deadline;time.sleep(.05)
new=version(uuid.UUID(a['id']),2);newrow,newjob=fetch(a['id'])
assert process(event(newjob))=='ready'
current,finished=fetch(a['id']);signature=current['variants']
release.write_text('go');stdout,stderr=child.communicate(timeout=10)
assert child.returncode==0 and stdout.strip()=='fenced',(stdout,stderr)
bus.xadd(STREAM,{'event':json.dumps(e)});drain()
final,finished=fetch(a['id'])
assert final['pipeline_version']==2 and final['variants']==signature and final['state']=='ready'
assert all('/v2/' in v['object_key'] for v in final['variants'])
report['invariants']['stale_running_version_fenced']=True
report['invariants']['old_delivery_after_new_ready_no_overwrite']=True
finally:
release.write_text('go')
if child.poll() is None:child.kill();child.wait()
# Transient failures consume a finite budget; failed registry and explicit replay.
a,j=upload()
with connect() as conn:conn.execute('UPDATE attachment_jobs SET max_attempts = 2 WHERE 1=1 AND id = %s',(j['id'],))
# Exact staging copy saved externally; missing source is permanent and observable.
raw=(Path.cwd()/'tests/fixtures/sample.png').read_bytes();objects.delete(j['source_key'])
process(event(j));failed,fj=fetch(a['id']);assert failed['state']=='failed' and failed['error_code']=='source_missing'
objects.put(j['source_key'],io.BytesIO(raw),len(raw),'image/png',hashlib.sha256(raw).hexdigest())
replay(j['id']);fresh,fj=fetch(a['id']);assert process(event(fj))=='ready'
try:replay(j['id']);raise AssertionError('replayed ready')
except ValueError:pass
report['invariants']['failed_registry_explicit_replay_and_ready_refusal']=True
# Real S3 signature failures are transient, with two attempts and measured backoff.
a,j=upload()
with connect() as conn:conn.execute('UPDATE attachment_jobs SET max_attempts = 2 WHERE 1=1 AND id = %s',(j['id'],))
wrong=Path('/tmp/wrong-secret');wrong.write_text('synthetic-invalid-key-not-a-real-secret')
env=dict(os.environ,S3_SECRET_ACCESS_KEY_FILE=str(wrong))
transitions=[];started=time.monotonic()
for _ in range(2):
row,j=fetch(a['id'])
delay=max(0,(j['next_attempt_at']-__import__('datetime').datetime.now(__import__('datetime').timezone.utc)).total_seconds())
time.sleep(delay+.01)
code="import sys,json;sys.path.insert(0,'/app/src');from pipeline import process;print(process(json.loads(sys.argv[1])))"
run=subprocess.run([sys.executable,'-c',code,json.dumps(event(j))],env=env,capture_output=True,timeout=10)
assert run.returncode==0
row,j=fetch(a['id']);transitions.append({'state':j['state'],'attempt':j['attempt'],'error_code':j['error_code']})
assert row['state']=='failed' and row['error_code']=='retry_exhausted' and j['attempt']==2
replay(j['id']);row,j=fetch(a['id']);assert process(event(j))=='ready'
report['retry']={'transitions':transitions,'seconds':round(time.monotonic()-started,3),'replayed_attempt':fetch(a['id'])[1]['attempt']}
report['invariants']['transient_backoff_exhaustion_then_replay']=True
# Real corrupted JPEG whose header is valid: heavy decoder fails safely in worker.
jpg=io.BytesIO();Image.new('RGB',(320,200),'blue').save(jpg,format='JPEG');truncated=jpg.getvalue()[:-100]
a,j=upload(truncated,'image/jpeg');process(event(j));bad,_=fetch(a['id'])
assert bad['state']=='failed' and bad['error_code']=='invalid_image'
report['invariants']['invalid_decode_permanent_failed']=True
# EXIF, alpha, small image and all on-disk variants checked by the real decoder.
transforms=[]
for kind in ['alpha','exif','small']:
out=io.BytesIO()
if kind=='alpha':
Image.new('RGBA',(20,10),(255,0,0,0)).save(out,format='PNG');mime='image/png'
elif kind=='exif':
image=Image.new('RGB',(200,320),'green');exif=Image.Exif();exif[274]=6;image.save(out,format='JPEG',exif=exif);mime='image/jpeg'
else:Image.new('RGB',(5,3),'yellow').save(out,format='PNG');mime='image/png'
a,j=upload(out.getvalue(),mime);assert process(event(j))=='ready'
r=c.call('GET','/api/v1/attachments/'+a['id']+'/content?variant=thumbnail',actor=bob)
with Image.open(io.BytesIO(r['bytes'])) as thumb:
expected=(20,10) if kind=='alpha' else (256,160) if kind=='exif' else (5,3)
assert thumb.size==expected
assert not thumb.getexif()
if kind=='alpha':assert min(thumb.getpixel((0,0)))>=250
transforms.append({'kind':kind,'size':thumb.size,'exif_removed':not bool(thumb.getexif())})
report['transforms']=transforms
pending,pending_job=upload()
dry=cleanup(False);fixed=cleanup(True);repeat=cleanup(True)
assert fetch(pending['id'])[0]['state']=='queued' and objects.head(pending_job['source_key']) is not None
report['invariants']['cleanup_preserves_current_and_fresh_failed']=True
assert repeat['counts']['ready_staging']==0
report['invariants']['ready_staging_cleanup_idempotent']=True
report['cleanup']=[dry,fixed,repeat]
print(json.dumps(report,indent=2))
if __name__=='__main__': main()
+11
View File
@@ -0,0 +1,11 @@
"""Three independently bootstrapped synthetic fixture runs of track1."""
import json
from pathlib import Path
import subprocess
ROOT=Path(__file__).resolve().parents[1]
runs=[]
for repeat in range(3):
subprocess.run(['python3','student-tests/compromise_research.py'],cwd=ROOT,check=True)
row=json.loads((ROOT/'evidence/worker-compromise.json').read_text());row['repeat']=repeat+1;runs.append(row)
(ROOT/'evidence/worker-compromise-runs.json').write_text(json.dumps({'runs':runs},indent=2)+'\n')
print('PASS: all3 controlled worker compromise/rollover runs retained.')
+9
View File
@@ -0,0 +1,9 @@
"""Operator action: rotate worker password and terminate its existing DB sessions."""
import json
from psycopg import sql
from security_helpers import db,SETTINGS
with db() as conn:
conn.execute(sql.SQL('ALTER ROLE db_worker PASSWORD {}').format(sql.Literal(SETTINGS['worker'])))
stopped=conn.execute("SELECT pg_terminate_backend(pid) AS stopped FROM pg_stat_activity WHERE 1=1 AND usename='db_worker' AND pid<>pg_backend_pid()").fetchall()
conn.execute('DROP ROLE IF EXISTS db_baseline')
print(json.dumps({'worker_db_password_rotated':True,'worker_db_sessions_terminated':len(stopped),'unused_baseline_role_removed':True}))
+74
View File
@@ -0,0 +1,74 @@
"""Operator-only archive scan, no Docker socket mounted into the scanner or any app."""
import collections
import datetime
import json
import os
from pathlib import Path
import socket
import subprocess
import time
import sys
ROOT=Path(__file__).resolve().parents[1]
SCANNER='aquasec/trivy:0.67.2@sha256:e2b22eac59c02003d8749f5b8d9bd073b62e30fefaef5b7c8371204e0a4b0c08'
def compact(raw):
findings=[]
for group in raw.get('Results',[]):
for v in group.get('Vulnerabilities',[]):
findings.append({k:v.get(k,'') for k in ['VulnerabilityID','PkgName','InstalledVersion','FixedVersion','Severity']})
return {'artifact':raw.get('ArtifactName'),'artifact_type':raw.get('ArtifactType'),
'severity_counts':dict(collections.Counter(x['Severity'] for x in findings)),'findings':findings}
COLUMNS=['VulnerabilityID','PkgName','InstalledVersion','FixedVersion','Severity']
def save(result):
result['findings_columns']=COLUMNS
for row in result['images']:
if row.get('findings') and isinstance(row['findings'][0],dict):
row['findings']=[[v.get(k,'') for k in COLUMNS] for v in row['findings']]
previous=result.get('previous_image_scans',[])
result['previous_image_scans']=[{k:v for k,v in row.items() if k in ['image','image_id','severity_counts']} for row in previous]
old=result.get('before_application')
if old and old.get('findings') and isinstance(old['findings'][0],dict):
old['findings']=[[v.get(k,'') for k in COLUMNS] for v in old['findings']]
path=ROOT/'evidence/image-scans.json'
temporary=path.with_suffix('.tmp')
temporary.write_text(json.dumps(result,ensure_ascii=False,separators=(',',':'))+'\n')
temporary.replace(path)
def main():
folder=ROOT/'build/scans';folder.mkdir(parents=True,exist_ok=True)
cache=ROOT/'build/trivy-cache';cache.mkdir(exist_ok=True)
cfg=json.loads((ROOT/'compose.yaml').read_text())
images=sorted({x['image'] for x in cfg['services'].values()})
result={'scanner':SCANNER,'date_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),
'method':'Local docker save archives, vuln scanner only, no scanner Docker socket; official GHCR vulnerability DB. Local isolated lab, not a penetration-test certification.','images':[]}
existing=ROOT/'evidence/image-scans.json'
if '--resume' in sys.argv and existing.exists():result=json.loads(existing.read_text())
obsolete=[r for r in result['images'] if r['image'] not in images]
result.setdefault('previous_image_scans',[]).extend(obsolete)
result['images']=[r for r in result['images'] if r['image'] in images]
before=folder/'before.json'
if before.exists():result['before_application']=compact(json.loads(before.read_text()))
for index,image in enumerate(images):
image_id=subprocess.check_output(['docker','image','inspect',image,'--format','{{.Id}}'],text=True).strip()
if any(r['image']==image and r.get('image_id')==image_id for r in result['images']):continue
previous=[r for r in result['images'] if r['image']==image]
result.setdefault('previous_image_scans',[]).extend(previous)
result['images']=[r for r in result['images'] if r['image']!=image]
archive=folder/('image-'+str(index)+'.tar')
subprocess.run(['docker','save','-o',str(archive),image],check=True)
with archive.open('rb') as sync:os.fsync(sync.fileno())
time.sleep(.3)
args=['docker','run','--rm','--memory','512m','--cpus','1']
for host in ['ghcr.io','pkg-containers.githubusercontent.com']:
args+=['--add-host',host+':'+socket.gethostbyname(host)]
args+=['-v',str(folder)+':/scan:ro','-v',str(cache)+':/root/.cache/trivy',SCANNER,
'image','--db-repository','ghcr.io/aquasecurity/trivy-db:2','--scanners','vuln','--input','/scan/'+archive.name,'--format','json']
with open(folder/'current.scan','w') as out,open(folder/'scanner.log','w') as err:
subprocess.run(args,stdout=out,stderr=err,check=True)
row=compact(json.loads((folder/'current.scan').read_text()));row['image']=image;row['image_id']=image_id
result['images'].append(row)
save(result)
print(image.split('@')[0],row['severity_counts'],flush=True)
archive.unlink()
save(result)
print('PASS: all declared unique runtime images scanned; triage still required.',flush=True)
if __name__=='__main__':main()
+60
View File
@@ -0,0 +1,60 @@
"""Bounded fail-closed cache and service token expiry; preserve an existing user session."""
import json
import os
from pathlib import Path
import ssl
import subprocess
import sys
import time
import urllib.error
import urllib.request
ROOT=Path(__file__).resolve().parents[1]
sys.path[:0]=[str(ROOT/'tests'),str(ROOT/'scripts')]
from client import Client
from bao_operator import call,unseal
c=Client();actor=c.user('sealed');root=unseal()
chat=c.call('POST','/api/v1/chats',201,actor=actor,body={'title':'sealed-recovery','member_ids':[actor['id']]},schema='Chat')['json']
processes_before=subprocess.check_output(['docker','compose','ps','-q','worker','dispatcher'],cwd=ROOT,text=True).split()
assert len(processes_before)==2
ctx=ssl.create_default_context(cafile=str(ROOT/'pki/lb/ca.crt'))
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
rows=[];started=time.monotonic()
try:
call('sys/seal',{},root)
for _ in range(34):
req=urllib.request.Request(c.base+'/api/v1/users/me',headers={'Authorization':'Bearer '+actor['token']})
try:
with opener.open(req,timeout=3) as r:status=r.status
except urllib.error.HTTPError as error:status=error.code
rows.append({'elapsed_seconds':round(time.monotonic()-started,3),'status':status})
if status==503 and time.monotonic()-started>22:break
time.sleep(1)
assert any(x['status']==503 for x in rows)
assert all(x['status']==503 for x in rows if x['elapsed_seconds']>23)
finally:
unseal()
recovered=None
for _ in range(60):
try:
c.call('GET','/api/v1/users/me',actor=actor,schema='User');recovered=round(time.monotonic()-started,3);break
except Exception:time.sleep(.5)
assert recovered is not None
processes_after=subprocess.check_output(['docker','compose','ps','-q','worker','dispatcher'],cwd=ROOT,text=True).split()
assert set(processes_before)==set(processes_after), 'Worker/dispatcher must remain alive across sealed transition'
att=c.attachment(actor,chat)[0];c.wait_ready(actor,att)
# Explicit token expiry is measured independently, without printing any token.
code="""import sys,time,json,urllib.error;sys.path.insert(0,'/app/student-tests');from security_helpers import login,bao
a=login('worker');token=a['client_token'];assert bao('secret/data/worker','worker',token=token)
time.sleep(a['lease_duration']+1)
try:bao('secret/data/worker','worker',token=token)
except urllib.error.HTTPError as e:assert e.code==403
else:raise AssertionError('Expired token accepted')
assert login('worker')['client_token']
print(json.dumps({'ttl':a['lease_duration'],'expired_token_403':True,'new_certificate_auth_succeeds':True}))"""
auth=json.loads(subprocess.check_output(['docker','compose','--profile','tools','run','--rm','--no-deps','audit','-c',code],cwd=ROOT,text=True))
result={'sealed_http_observations':rows,'max_secret_cache_seconds':20,'old_bearer_after_unseal':True,
'first_failure_seconds':next(x['elapsed_seconds'] for x in rows if x['status']==503),'recovered_seconds':recovered,
'token_expiry':auth,'no_insecure_or_plaintext_fallback':True,'worker_dispatcher_remained_alive':True,'new_job_ready_after_unseal':True}
(ROOT/'evidence/sealed-and-expiry.json').write_text(json.dumps(result,indent=2)+'\n')
print('PASS: cache expiry fails closed with503; unseal restores same Bearer; old service token403 and certificate re-auth works.')
+58
View File
@@ -0,0 +1,58 @@
"""Operator audit utilities. Values are never included in the JSON report."""
import json
import os
from pathlib import Path
import socket
import ssl
import urllib.error
import urllib.request
import boto3
from botocore.config import Config
import psycopg
from psycopg.rows import dict_row
import redis
SETTINGS=json.loads(Path('/operator/settings.json').read_text())
def cert(role):return Path('/identities')/role
def context(role=None):
ctx=ssl.create_default_context(cafile='/tls/ca.crt')
if role:ctx.load_cert_chain(str(cert(role)/'tls.crt'),str(cert(role)/'tls.key'))
return ctx
def http(url,role='operator',data=None,token=None,method=None):
headers={'Content-Type':'application/json'}
if token:headers['X-Vault-Token']=token
req=urllib.request.Request(url,data=None if data is None else json.dumps(data).encode(),headers=headers,method=method)
op=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=context(role)))
with op.open(req,timeout=5) as r:return r.status,r.read()
def bao(path,role='operator',data=None,token=None,method=None):
code,raw=http('https://bao:8200/v1/'+path,role,data,token,method)
return json.loads(raw) if raw else {}
def login(role):return bao('auth/cert/login',role,{'name':role})['auth']
def db(role='operator',password=None):
username='messenger' if role=='operator' else 'db_'+role
secret=password or SETTINGS['postgres' if role=='operator' else role]
return psycopg.connect(host='postgres',dbname='messenger',user=username,password=secret,
sslmode='verify-full',sslrootcert='/tls/ca.crt',connect_timeout=3,row_factory=dict_row,autocommit=True)
def s3(role='worker',identity=None):
identity=identity or role
return boto3.client('s3',endpoint_url='https://s3:8443',verify='/tls/ca.crt',region_name='us-east-1',
aws_access_key_id=SETTINGS['s3_'+identity+'_key'],aws_secret_access_key=SETTINGS['s3_'+identity],
config=Config(client_cert=(str(cert(role)/'tls.crt'),str(cert(role)/'tls.key')),signature_version='s3v4',
s3={'addressing_style':'path'},connect_timeout=2,read_timeout=3,retries={'total_max_attempts':1},
request_checksum_calculation='when_required',response_checksum_validation='when_required'))
def bus(role='worker'):
return redis.Redis(host='broker',port=8443,username=role,password=SETTINGS['broker_'+role],
ssl=True,ssl_ca_certs='/tls/ca.crt',ssl_certfile=str(cert(role)/'tls.crt'),ssl_keyfile=str(cert(role)/'tls.key'),
ssl_check_hostname=True,socket_connect_timeout=2,socket_timeout=3,decode_responses=True)
def denied(fun):
try:fun()
except Exception as error:return type(error).__name__
raise AssertionError('Operation unexpectedly permitted')
def probe(host,port,role,path='/',method='GET',address=None):
raw=socket.create_connection((address or host,port),timeout=3)
try:
conn=context(role).wrap_socket(raw,server_hostname=host)
with conn:
conn.sendall(b'PING\r\n' if host in ['redis','broker'] else (method+' '+path+' HTTP/1.1\r\nHost: '+host+'\r\nConnection: close\r\n\r\n').encode())
return conn.recv(1024)
finally:raw.close()
+177
View File
@@ -0,0 +1,177 @@
"""Extra black-box tests, without changing the course's public tests."""
import concurrent.futures
from pathlib import Path
import sys
import unittest
from urllib.parse import quote
import uuid
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
from client import Client as PublicClient, LAB
class Client(PublicClient):
def call(self, method, path, *args, headers=None, **kwargs):
headers = dict(headers or {})
if method == 'POST' and path.endswith('/messages'):
headers.setdefault('Idempotency-Key', uuid.uuid4().hex)
return super().call(method, path, *args, headers=headers, **kwargs)
class APIContract(unittest.TestCase):
def setUp(self):
self.client = Client()
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
self.path = '/api/v1/chats/' + self.chat['id']
def test_malformed_json_and_extra_fields(self):
for raw in (b'{', b'[]', b'{"text":"x","text":"y"}', b'{"text":NaN}', b'{"text":"\\ud800"}'):
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=raw, headers={'Content-Type': 'application/json'})
for body in ({'text': 'ok', 'sender_id': self.eve['id']}, {'text': True}, {'text': ' '}, {'text': ''}, {'text': None}):
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body=body)
deep = b'{"text":' + b'[' * 1200 + b'0' + b']' * 1200 + b'}'
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=deep, headers={'Content-Type': 'application/json'})
def test_unicode_limits(self):
result = self.client.message(self.alice, self.chat, '👩' * 4000)['json']
self.assertEqual(result['text'], '👩' * 4000)
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': '👩' * 4001})
def test_unicode_nul_round_trip(self):
import base64
value = 'A\x00B\\u0000👩'
registration = dict(self.alice['registration'], username='nul_' + uuid.uuid4().hex[:20], display_name=value)
user = self.client.call('POST', '/api/v1/users', 201, body=registration, schema='User')['json']
self.assertEqual(user['display_name'], value)
credential = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
self.assertEqual(session['user'], user)
actor = {'id': user['id'], 'token': session['token']}
# Exercise the database path and then the Redis profile cache.
for _ in range(2):
self.assertEqual(self.client.call('GET', '/api/v1/users/me', actor=actor, schema='User')['json'], user)
chat = self.client.call('POST', '/api/v1/chats', 201, actor=actor, body={'title': value, 'member_ids': [actor['id']]}, schema='Chat')['json']
self.assertEqual(chat['title'], value)
self.assertEqual(self.client.call('GET', '/api/v1/chats/' + chat['id'], actor=actor, schema='Chat')['json'], chat)
contents = [value, '\x00' * 4000, '👩' * 3999 + '\x00']
for content in contents:
self.assertEqual(self.client.message(actor, chat, content)['json']['text'], content)
history = self.client.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=actor, schema='MessagePage')['json']
self.assertEqual([message['text'] for message in history['items']], contents)
def test_foreign_chat(self):
for suffix in ('', '/messages'):
self.client.call('GET', self.path + suffix, 404, actor=self.eve)
self.client.call('POST', self.path + '/messages', 404, actor=self.eve, body={'text': 'hidden'})
self.client.call('GET', '/api/v1/chats/' + str(uuid.uuid4()), 404, actor=self.alice)
def test_registration_race(self):
body = dict(self.alice['registration'], username='race_' + uuid.uuid4().hex[:20])
def register(_):
return Client().call('POST', '/api/v1/users', [201, 409], body=body)['status']
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
statuses = list(executor.map(register, range(10)))
self.assertEqual(statuses.count(201), 1)
self.assertEqual(statuses.count(409), 9)
def test_invalid_chat_creation(self):
members = ([self.alice['id'], self.alice['id']], [self.bob['id']], [self.alice['id'], str(uuid.uuid4())], [], [True])
for member_ids in members:
self.client.call('POST', '/api/v1/chats', 400, actor=self.alice, body={'title': 'rollback', 'member_ids': member_ids})
def test_cursor_scope_and_validation(self):
for i in range(3):
self.client.message(self.alice, self.chat, str(i))
cursor = self.client.call('GET', self.path + '/messages?limit=1', actor=self.alice, schema='MessagePage')['json']['next_cursor']
other = self.client.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'other', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
self.client.call('GET', '/api/v1/chats/' + other['id'] + '/messages?cursor=' + quote(cursor), 400, actor=self.alice)
for query in ('limit=0', 'limit=101', 'limit=' + '9' * 5000, 'limit=true', 'limit=1&limit=2', 'cursor=', 'cursor=bad', 'cursor=e30=', 'offset=1'):
self.client.call('GET', self.path + '/messages?' + query, 400, actor=self.alice)
def test_concurrent_messages_and_pagination(self):
def send(i):
return Client().message(self.alice if i % 2 else self.bob, self.chat, 'parallel-' + str(i))['json']
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
sent = list(executor.map(send, range(100)))
found = []
cursor = None
while True:
url = self.path + '/messages?limit=7' + ('&cursor=' + quote(cursor) if cursor else '')
page = self.client.call('GET', url, actor=self.alice, schema='MessagePage')['json']
found.extend(page['items'])
cursor = page['next_cursor']
if cursor is None:
break
self.assertEqual(len(found), 100)
self.assertEqual(len({v['id'] for v in found}), 100)
self.assertEqual({v['id'] for v in found}, {v['id'] for v in sent})
self.assertEqual(found, sorted(found, key=lambda v: (v['created_at'], v['id'])))
def test_idempotency_concurrent_replicas(self):
key = uuid.uuid4().hex
def send(_):
return Client().message(self.alice, self.chat, 'Один раз\x00👩', key=key)
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
replies = list(executor.map(send, range(32)))
self.assertGreaterEqual(len({v['headers']['X-Instance-Id'] for v in replies}), 2)
self.assertTrue(all(v['json'] == replies[0]['json'] for v in replies))
page = self.client.call('GET', self.path + '/messages', actor=self.bob, schema='MessagePage')['json']
self.assertEqual(page['items'], [replies[0]['json']])
self.client.call('POST', self.path + '/messages', 409, actor=self.alice, body={'text': 'different'}, headers={'Idempotency-Key': key})
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=self.alice)
self.client.call('POST', self.path + '/messages', 401, actor=self.alice, body={'text': 'Один раз\x00👩'}, headers={'Idempotency-Key': key})
def test_protocol_error_headers(self):
self.client.call('TRACE', '/api/v1/users/me', 400, actor=self.alice)
def test_idempotency_scope(self):
key = uuid.uuid4().hex
one = self.client.message(self.alice, self.chat, 'same', key=key)['json']
two = self.client.message(self.bob, self.chat, 'same', key=key)['json']
other = self.client.call('POST', '/api/v1/chats', 201, actor=self.alice, body={'title': 'scope', 'member_ids': [self.alice['id']]}, schema='Chat')['json']
three = self.client.message(self.alice, other, 'same', key=key)['json']
self.assertEqual(len({one['id'], two['id'], three['id']}), 3)
def test_idempotency_semantic_body(self):
key = uuid.uuid4().hex
one = self.client.message(self.alice, self.chat, 'semantic', key=key)['json']
two = self.client.call('POST', self.path + '/messages', 201, actor=self.alice, body={'attachment_ids': [], 'text': 'semantic'}, headers={'Idempotency-Key': key}, schema='Message')['json']
self.assertEqual(one, two)
def test_idempotency_invalid_keys(self):
for key in (None, '', 'x' * 129, 'space key', 'bad,key', 'slash/key'):
headers = {} if key is None else {'Idempotency-Key': key}
PublicClient().call('POST', self.path + '/messages', 400, actor=self.alice, body={'text': 'valid'}, headers=headers)
for raw in (b'{"text":true}', b'{"text":"ok","extra":1}', b'{"text":"ok","attachment_ids":false}'):
self.client.call('POST', self.path + '/messages', 400, actor=self.alice, raw=raw, headers={'Content-Type': 'application/json'})
def test_idempotency_conflicting_race(self):
key = uuid.uuid4().hex
def send(i):
return Client().call('POST', self.path + '/messages', [201, 409], actor=self.alice, body={'text': str(i % 2)}, headers={'Idempotency-Key': key}, schema=None)
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
replies = list(executor.map(send, range(32)))
self.assertEqual(sum(v['status'] == 201 for v in replies), 16)
self.assertEqual(sum(v['status'] == 409 for v in replies), 16)
page = self.client.call('GET', self.path + '/messages', actor=self.alice, schema='MessagePage')['json']
self.assertEqual(len(page['items']), 1)
@unittest.skipUnless(LAB >= 2, 'sessions start in lab2')
def test_unicode_password_basic_and_logout(self):
import base64
registration = {'username': 'unicode_' + uuid.uuid4().hex[:16], 'display_name': 'Софья', 'password': '🔐' * 127 + ':'}
self.client.call('POST', '/api/v1/users', 201, body=registration)
encoded = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
headers = {'Authorization': 'Basic ' + encoded}
session = self.client.call('POST', '/api/v1/auth/sessions', 201, headers=headers, schema='Session')['json']
actor = {'id': session['user']['id'], 'token': session['token']}
self.client.call('GET', '/api/v1/users/me', actor=actor)
self.client.call('GET', '/api/v1/users/me', 401, headers=headers)
for authorization in ('Basic !!!', 'Bearer wrong', '', 'Basic Zm9v'):
self.client.call('POST', '/api/v1/auth/sessions', 401, headers={'Authorization': authorization})
self.client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=actor)
self.client.call('GET', '/api/v1/users/me', 401, actor=actor)
if __name__ == '__main__':
unittest.main(verbosity=2)
+52
View File
@@ -0,0 +1,52 @@
"""Independent tests for async image metadata, transformations and access."""
import io
from pathlib import Path
import sys
import unittest
import uuid
from urllib.parse import quote
sys.path[:0] = [str(Path(__file__).resolve().parents[1] / 'tests')]
from client import Client
from images import bomb
class Images(unittest.TestCase):
def setUp(self):
self.c=Client(); self.alice,self.bob,self.eve,self.chat=self.c.bootstrap()
self.path='/api/v1/chats/'+self.chat['id']
self.raw=(Path(__file__).resolve().parents[1]/'tests/fixtures/sample.png').read_bytes()
def test_async_variants_and_replay(self):
queued,_=self.c.attachment(self.alice,self.chat)
self.assertEqual(queued['status'],'queued')
key=uuid.uuid4().hex
one=self.c.message(self.bob,self.chat,'',key=key,attachments=[queued['id']])['json']
self.assertEqual(self.c.message(self.bob,self.chat,'',key=key,attachments=[queued['id']])['json'],one)
ready=self.c.wait_ready(self.alice,queued)
self.assertEqual({v['name'] for v in ready['variants']},{'thumbnail','crop','optimized'})
dimensions={v['name']:(v['width'],v['height']) for v in ready['variants']}
self.assertEqual(dimensions,{'thumbnail':(256,160),'crop':(128,128),'optimized':(320,200)})
for v in ready['variants']:
import hashlib
r=self.c.call('GET','/api/v1/attachments/'+ready['id']+'/content?variant='+v['name'],actor=self.bob)
self.assertEqual(hashlib.sha256(r['bytes']).hexdigest(),v['sha256'])
self.assertEqual(len(r['bytes']),v['size_bytes'])
self.c.call('GET','/api/v1/attachments/'+ready['id']+'/content?variant=absent',404,actor=self.bob)
def test_mime_bytes_pixels_and_filename(self):
path=self.path+'/attachments?filename=test.png'
for raw,mime,status in [(b'not image','image/png',415),(self.raw[:20],'image/png',415),(self.raw,'image/jpeg',415),(bomb(),'image/png',413),(b'x'*(10485760+1),'image/png',413)]:
self.c.call('POST',path,status,actor=self.alice,raw=raw,headers={'Content-Type':mime})
for name in ('../x.png','a\\x.png','a\0.png','a\n.png','a'*256,''):
self.c.call('POST',self.path+'/attachments?filename='+quote(name,safe=''),400,actor=self.alice,raw=self.raw,headers={'Content-Type':'image/png'})
def test_private_and_cross_chat(self):
att,_=self.c.attachment(self.alice,self.chat)
for suffix in ('','/content'):
self.c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=self.eve)
self.c.call('GET','/api/v1/attachments/'+att['id']+suffix,401)
other=self.c.call('POST','/api/v1/chats',201,actor=self.alice,body={'title':'other','member_ids':[self.alice['id']]},schema='Chat')['json']
self.c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=self.alice,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
if __name__=='__main__': unittest.main(verbosity=2)
+92
View File
@@ -0,0 +1,92 @@
"""Full declared matrix, actual negative identities and no plaintext bypass."""
import json
import socket
import sys
from security_helpers import *
from botocore.exceptions import ClientError
report={'matrix':[],'api_replicas':[],'plaintext_rejected':[],'policies':{}}
# Each replica is resolved and tested, not merely the first load-balanced response.
addresses=sorted({x[4][0] for x in socket.getaddrinfo('api',8080,type=socket.SOCK_STREAM)})
assert len(addresses)==2
for ip in addresses:
assert b'200 OK' in probe('api',8080,'lb','/health/ready',address=ip)
errors={}
for role in [None,'foreign-client','outsider','expired-lb','wrong-lb','worker']:
# A response must NOT reach the business HTTP handler.
try:raw=probe('api',8080,role,'/health/ready',address=ip)
except (ssl.SSLError,ConnectionResetError,ConnectionAbortedError) as error:errors[str(role)]=type(error).__name__;continue
assert not raw,role
errors[str(role)]='identity connection closed'
report['api_replicas'].append({'address_alias':'replica'+str(len(report['api_replicas'])+1),'allowed_lb':True,'negative_cases':list(errors)})
cases=[
('s3',8443,'api','/messenger-attachments','HEAD'),
('redis',8443,'api','/','GET'),
('broker',8443,'worker','/','GET'),
('otel-collector',8443,'api','/v1/traces','GET'),
('otel-collector',8443,'worker','/v1/traces','GET'),
('otel-collector',8443,'dispatcher','/v1/traces','GET'),
('otel-collector',8444,'prometheus','/metrics','GET'),
('otel-collector',8445,'prometheus','/metrics','GET'),
('loki',8443,'collector','/ready','GET'),
('loki',8443,'grafana','/ready','GET'),
('tempo',8443,'grafana','/ready','GET'),
('tempo',8444,'collector','/v1/traces','GET'),
('prometheus',8443,'grafana','/-/ready','GET'),
('bao',8200,'api','/v1/sys/seal-status','GET')]
for host,port,role,path,method in cases:
raw=probe(host,port,role,path,method)
assert raw,(host,role)
bad={}
for invalid in [None,'foreign-client','outsider','expired-'+role]+(['api'] if host=='broker' else []):
try:answer=probe(host,port,invalid,path,method)
except (ssl.SSLError,ConnectionResetError,ConnectionAbortedError) as error:bad[str(invalid)]=type(error).__name__;continue
if host=='bao' and invalid=='outsider':
# TLS trusts the issuer; exact-leaf cert auth below provides role authorization.
assert b'200' in answer;bad[invalid]='TLS CA accepted; service-auth denied separately';continue
assert not answer,(host,invalid,answer[:50])
bad[str(invalid)]='identity connection closed'
report['matrix'].append({'endpoint':host+':'+str(port),'allowed_identity':role,'positive_connection':True,'negative_cases':bad})
for role in ['api','worker','dispatcher']:
auth=login(role);token=auth['client_token']
assert 0<auth['lease_duration']<=20
assert bao('secret/data/'+role,role,token=token)['data']['data']
other='api' if role!='api' else 'worker'
for path,method,data in [('secret/data/'+other,None,None),('sys/policies/acl/worker',None,None),('sys/policies/acl/worker','PUT',{'policy':'path "*" { capabilities=["root"] }'})]:
try:bao(path,role,token=token,method=method,data=data)
except urllib.error.HTTPError as error:assert error.code==403
else:raise AssertionError('Bao scope bypass')
report['policies'][role]={'own_kv_read':True,'foreign_kv_and_policy_read_write_403':True,'token_ttl_seconds':auth['lease_duration']}
for role in ['outsider','worker']:
target='worker' if role=='outsider' else 'api'
try:bao('auth/cert/login',role,{'name':target})
except urllib.error.HTTPError as error:assert error.code in (400,403)
else:raise AssertionError('Foreign valid leaf impersonated another service')
for host,ports in {'s3':[8333,8888,9333,9340],'broker':[6379],'redis':[6379],
'otel-collector':[4318,8888,8889],'loki':[3100,9095],'tempo':[3200,4318,9095],'prometheus':[9090]}.items():
for port in ports:
try:socket.create_connection((host,port),timeout=.5).close()
except OSError:report['plaintext_rejected'].append(host+':'+str(port))
else:raise AssertionError('Plaintext bypass '+host+':'+str(port))
with db('worker') as conn:
assert conn.execute("SELECT ssl FROM pg_stat_ssl WHERE 1=1 AND pid=pg_backend_pid()").fetchone()['ssl']
for sql in ['SELECT count(*) FROM users','SELECT count(*) FROM sessions','SELECT count(*) FROM messages','CREATE TABLE breach (id INTEGER)']:
assert denied(lambda sql=sql:conn.execute(sql))=='InsufficientPrivilege'
assert conn.execute('SELECT count(*) FROM attachment_jobs').fetchone()
report['db']={'verify_full_tls':True,'worker_jobs_read_allowed':True,'users_sessions_messages_ddl_denied':True}
assert bus('worker').ping()
assert denied(lambda:bus('worker').get('private:session'))=='NoPermissionError'
assert denied(lambda:bus('worker').config_get('*'))=='NoPermissionError'
report['broker_acl']={'worker_ping':True,'foreign_key_and_config_denied':True}
# Fail closed on an operator's accidental plaintext configuration, before any network call.
import subprocess,os
for envkey,code in [
('S3_ENDPOINT', "from objects import Objects;Objects(lambda name:'unused')"),
('OTEL_EXPORTER_OTLP_ENDPOINT', "import telemetry;telemetry.configure('negative-config')"),
]:
env=dict(os.environ,TELEMETRY_ENABLED='1',PYTHONPATH='/app/src')
env[envkey]='http://plaintext.invalid:8080'
run=subprocess.run([sys.executable,'-c',code],env=env,capture_output=True)
assert run.returncode!=0 and b'must use verified HTTPS' in run.stderr
report['plaintext_configuration_rejected']=True
print(json.dumps(report,indent=2))
+34
View File
@@ -0,0 +1,34 @@
"""Run inside the actual worker: this script obtains only its own service secrets."""
import json
import os
from pathlib import Path
import sys
sys.path.insert(0,'/app/src')
import vault
from postgres import setting
from pipeline import raw_connect,broker
from objects import Objects
from botocore.exceptions import ClientError
report={'uid':os.getuid(),'own_kv':bool(vault.value('DATABASE_URL')),'root_or_unseal_files_present':any(Path(p).exists() for p in ['/operator','/run/secrets/postgres_password','/tls/ca.key'])}
assert report['uid']!=0 and not report['root_or_unseal_files_present']
with raw_connect() as conn:
report['job_rows_visible']=conn.execute('SELECT count(*) AS n FROM attachment_jobs').fetchone()['n']
denied=[]
for table in ['users','sessions','messages']:
try:conn.execute('SELECT count(*) FROM '+table)
except Exception as error:
assert type(error).__name__=='InsufficientPrivilege';denied.append(table)
else:raise AssertionError('Worker read private business table')
for sql in ['UPDATE attachments SET chat_id=chat_id','UPDATE attachment_jobs SET source_key=source_key','CREATE TABLE escaped (id INTEGER)','CREATE TEMP TABLE escaped_temp (id INTEGER)']:
try:conn.execute(sql)
except Exception as error:assert type(error).__name__=='InsufficientPrivilege'
else:raise AssertionError('Worker modified protected schema or ownership/source columns')
conn.execute('UPDATE attachment_jobs SET state=state WHERE 1=1 AND id=(SELECT id FROM attachment_jobs ORDER BY created_at LIMIT 1)')
report['allowed_db_operations']=['SELECT job and attachment metadata','UPDATE allowed job state columns','pipeline INSERT job_events (covered by successful jobs)']
report['denied_db_tables']=denied
report['protected_chat_source_columns_and_ddl_denied']=True
client=broker()
try:client.config_get('*')
except Exception as error:assert type(error).__name__=='NoPermissionError';report['broker_config_denied']=True
else:raise AssertionError('Worker can administer broker')
print(json.dumps(report,indent=2))