forked from mtusi2026/mtusi2026lab7
Лабораторная 7
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
"""Read stored signals through internal backend APIs; no public admin ports."""
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import base64
|
||||
import ssl
|
||||
from pipeline_helpers import *
|
||||
|
||||
|
||||
def backend(url, text=False):
|
||||
# Query via Grafana proxy: observation must work even while worker is stopped.
|
||||
target=urllib.parse.urlsplit(url)
|
||||
sources={'prometheus:9090':'prometheus','loki:3100':'loki','tempo:3200':'tempo'}
|
||||
check(target.netloc in sources,'unknown telemetry backend')
|
||||
password=(ROOT/'secrets/grafana_admin_password').read_text().strip()
|
||||
base=os.environ.get('GRAFANA_URL','https://localhost:13007').rstrip('/')
|
||||
address=base+'/api/datasources/proxy/uid/'+sources[target.netloc]+target.path
|
||||
if target.query:address+='?'+target.query
|
||||
auth=base64.b64encode(('admin:'+password).encode()).decode()
|
||||
request=urllib.request.Request(address,headers={'Accept':'application/json','Authorization':'Basic '+auth})
|
||||
try:
|
||||
with urllib.request.urlopen(request,timeout=8,context=ssl.create_default_context(cafile=str(ROOT/"secrets/public/ca.crt"))) as response:output=response.read().decode()
|
||||
return output if text else json.loads(output)
|
||||
except (urllib.error.URLError,OSError,ValueError):
|
||||
raise Failure('telemetry backend not ready: '+sources[target.netloc]) from None
|
||||
|
||||
|
||||
def prom(expr):
|
||||
result=backend('https://prometheus:9090/api/v1/query?'+urllib.parse.urlencode({'query':expr}))
|
||||
check(result['status']=='success','Prometheus query failed')
|
||||
return result['data']['result']
|
||||
|
||||
|
||||
def number(expr, default=0):
|
||||
values=prom(expr)
|
||||
return float(values[0]['value'][1]) if values else default
|
||||
|
||||
|
||||
def trace_data(trace_id):
|
||||
return backend('https://tempo:3200/api/traces/'+trace_id)
|
||||
|
||||
|
||||
def spans(value):
|
||||
found=[]
|
||||
if isinstance(value,dict):
|
||||
if 'spanId' in value and 'name' in value:found.append(value)
|
||||
for child in value.values():found.extend(spans(child))
|
||||
elif isinstance(value,list):
|
||||
for child in value:found.extend(spans(child))
|
||||
return found
|
||||
|
||||
|
||||
def logs(trace_id=None, service=None):
|
||||
selector='{service_name="'+service+'"}' if service else '{service_name=~"messenger-api|messenger-worker|messenger-dispatcher"}'
|
||||
query=selector+' | json'
|
||||
if trace_id:query+=' | trace_id="'+trace_id+'"'
|
||||
data=backend('https://loki:3100/loki/api/v1/query_range?'+urllib.parse.urlencode({'query':query,'start':str(time.time_ns()-900_000_000_000),'limit':'1000'}))
|
||||
return [json.loads(row[1]) for stream in data['data']['result'] for row in stream['values']]
|
||||
|
||||
|
||||
def alert(name):
|
||||
result=backend('https://prometheus:9090/api/v1/alerts')
|
||||
matches=[a for a in result['data']['alerts'] if a['labels'].get('alertname')==name]
|
||||
return matches[0]['state'] if matches else 'resolved'
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Local synthetic tests; credentials stay in memory and never enter evidence."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, check, run
|
||||
|
||||
|
||||
def compose(*args, data=None):
|
||||
result = subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
|
||||
input=data, capture_output=True, text=True)
|
||||
check(result.returncode == 0, 'compose command failed: ' + ' '.join(args[:3]))
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def psql(sql):
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-XAtq', '-v', 'ON_ERROR_STOP=1',
|
||||
'-U', 'messenger', '-d', 'messenger', data=sql)
|
||||
|
||||
|
||||
def wait_for(test, message, timeout=100):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = test()
|
||||
if value:
|
||||
return value
|
||||
except Failure:
|
||||
pass
|
||||
time.sleep(.3)
|
||||
raise Failure(message)
|
||||
|
||||
|
||||
def ready(client):
|
||||
wait_for(lambda: client.call('GET', '/health/ready', schema='Health'), 'API not ready')
|
||||
|
||||
|
||||
def upload(client, actor, chat, raw=None):
|
||||
if raw is None:
|
||||
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
result = client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=test.png',
|
||||
202, actor=actor, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
check(result['status'] == 'queued', '202 must contain queued snapshot')
|
||||
return result
|
||||
|
||||
|
||||
def state(client, actor, attachment):
|
||||
return client.call('GET', '/api/v1/attachments/' + attachment['id'], actor=actor, schema='Attachment')['json']
|
||||
|
||||
|
||||
def wait_state(client, actor, attachment, wanted='ready', timeout=100):
|
||||
def poll():
|
||||
result = state(client, actor, attachment)
|
||||
if wanted == 'ready':
|
||||
check(result['status'] != 'failed', 'job unexpectedly failed')
|
||||
return result if result['status'] == wanted else None
|
||||
return wait_for(poll, 'attachment did not become ' + wanted, timeout)
|
||||
|
||||
|
||||
def fault(point):
|
||||
check(point in ('dispatcher_before_publish','dispatcher_after_publish','worker_after_claim','worker_after_objects','worker_before_ack'),'unknown fault point')
|
||||
psql("INSERT INTO pipeline_faults(point) VALUES('"+point+"') ON CONFLICT(point) DO UPDATE SET armed=true,hit_at=NULL;")
|
||||
|
||||
|
||||
def hit(point):
|
||||
wait_for(lambda: psql("SELECT hit_at IS NOT NULL FROM pipeline_faults WHERE point='" + point + "';") == 't',
|
||||
'fault not reached: ' + point)
|
||||
|
||||
|
||||
def dump_evidence(name, value):
|
||||
(ROOT / 'evidence').mkdir(exist_ok=True)
|
||||
(ROOT / 'evidence' / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
|
||||
|
||||
|
||||
def start_only(service):
|
||||
# Compose start can also start dependencies; fault tests need exactly this container.
|
||||
container = compose('ps', '--all', '-q', service)
|
||||
result = subprocess.run(['docker', 'start', container], capture_output=True, text=True)
|
||||
check(result.returncode == 0, 'cannot start container ' + service)
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Operator TLS/policy audit inside an ephemeral container; outputs no credentials."""
|
||||
import http.client,json,socket,ssl
|
||||
from pathlib import Path
|
||||
BASE=Path('/audit');results={}
|
||||
def context(role):
|
||||
c=ssl.create_default_context(cafile=str(BASE/'public/ca.crt'))
|
||||
if role:c.load_cert_chain(BASE/'tls'/role/'cert.crt',BASE/'tls'/role/'key.key')
|
||||
return c
|
||||
def probe(host,port,role,path='/',payload=None):
|
||||
c=context(role)
|
||||
with socket.create_connection((host,port),timeout=3) as raw:
|
||||
with c.wrap_socket(raw,server_hostname=host) as s:
|
||||
s.sendall(payload or f'GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n'.encode())
|
||||
return s.recv(512)
|
||||
def denied(host,port,role,path='/',payload=None):
|
||||
try:
|
||||
response=probe(host,port,role,path,payload)
|
||||
return not response or response.startswith(b'HTTP/1.1 403') or response.startswith(b'HTTP/1.0 403')
|
||||
except (OSError,ssl.SSLError):return True
|
||||
def check(value,label):
|
||||
if not value:raise AssertionError(label)
|
||||
results[label]='PASS'
|
||||
for host,port,role,path,raw in [('api1',8080,'lb','/health/ready',None),('api2',8080,'lb','/health/ready',None),('broker',6379,'worker','/',b'*1\r\n$4\r\nPING\r\n'),('otel-collector',4318,'worker','/',None)]:
|
||||
check(bool(probe(host,port,role,path,raw)),host+'_authorized_identity')
|
||||
check(denied(host,port,None,path,raw),host+'_no_certificate_denied')
|
||||
check(denied(host,port,'foreign',path,raw),host+'_foreign_CA_denied')
|
||||
check(denied(host,port,'outsider',path,raw),host+'_trusted_wrong_SAN_denied')
|
||||
for role in ['api1','api2','dispatcher']:
|
||||
check(bool(probe('otel-collector',4318,role)),role+'_collector_mTLS')
|
||||
check(bool(probe('broker',6379,'dispatcher',payload=b'*1\r\n$4\r\nPING\r\n')),'dispatcher_broker_mTLS')
|
||||
check(denied('broker',6379,'worker',payload=b'*5\r\n$4\r\nXADD\r\n$18\r\nattachment.jobs.v1\r\n$1\r\n*\r\n$3\r\njob\r\n$2\r\n{}\r\n'),'worker_cannot_publish_job_stream')
|
||||
# TLS matrix positive probes and role denials for each dependency path.
|
||||
for host,port,role,path in [('redis',6379,'api1','/'),('s3',9000,'worker','/'),('prometheus',9090,'grafana','/-/ready'),('loki',3100,'grafana','/ready'),('tempo',3200,'grafana','/ready')]:
|
||||
payload=b'*1\r\n$4\r\nPING\r\n' if host=='redis' else None
|
||||
check(bool(probe(host,port,role,path,payload)),host+'_verified_TLS')
|
||||
check(denied(host,port,'outsider',path,payload),host+'_outsider_denied')
|
||||
# Closed local hops cannot be reached through the container network.
|
||||
for host,port in [('broker',16379),('redis',16379),('s3',19000),('otel-collector',14318),('prometheus',19090),('loki',13100),('tempo',13200)]:
|
||||
try: socket.create_connection((host,port),timeout=1).close();closed=False
|
||||
except OSError:closed=True
|
||||
check(closed,host+'_plaintext_bypass_closed')
|
||||
# Actual cert login + scoped policy, not just reading policy text.
|
||||
c=http.client.HTTPSConnection('openbao',8200,context=context('worker'),timeout=5)
|
||||
c.request('POST','/v1/auth/cert/login',json.dumps({'name':'worker'}),{'Content-Type':'application/json'});r=c.getresponse();auth=json.loads(r.read());check(r.status==200,'bao_cert_login')
|
||||
token=auth['auth']['client_token'];headers={'X-Vault-Token':token,'Content-Type':'application/json'}
|
||||
for method,path,status in [('GET','secret/worker',200),('GET','secret/api1',403),('PUT','sys/policies/acl/injected',403)]:
|
||||
c.request(method,'/v1/'+path,'{}' if method=='PUT' else None,headers);r=c.getresponse();r.read();check(r.status==status,'bao_'+path.replace('/','_')+'_policy')
|
||||
check(auth['auth']['lease_duration']<=120,'bao_bounded_token_TTL')
|
||||
print(json.dumps({'status':'PASS','checks':results},indent=2))
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Two diagnosed incidents + bounded telemetry outage, using stored observations."""
|
||||
import concurrent.futures
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from obs_helpers import *
|
||||
|
||||
|
||||
def send_load(client,actor,chat,seconds,workers=2):
|
||||
deadline=time.monotonic()+seconds
|
||||
path='/api/v1/chats/'+chat['id']+'/messages'
|
||||
def task(_):
|
||||
c=Client(client.base,timeout=8);ok=failed=0;durations=[]
|
||||
while time.monotonic()<deadline:
|
||||
begin=time.monotonic()
|
||||
try:
|
||||
c.call('POST',path,201,actor=actor,body={'text':'synthetic load'},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
ok+=1;durations.append(time.monotonic()-begin)
|
||||
except Failure:failed+=1
|
||||
return ok,failed,durations
|
||||
start=time.monotonic()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:rows=list(pool.map(task,range(workers)))
|
||||
elapsed=time.monotonic()-start
|
||||
durations=sorted(d for r in rows for d in r[2]);count=sum(r[0] for r in rows)
|
||||
def percentile(fraction):
|
||||
import math
|
||||
return round(durations[max(0,math.ceil(len(durations)*fraction)-1)]*1000,3) if durations else None
|
||||
return dict(seconds=round(elapsed,3),workers=workers,successful_requests=count,failed_requests=sum(r[1] for r in rows),
|
||||
successful_rps=round(count/elapsed,3),latency_ms_successes={k:percentile(f) for k,f in [('p50',.5),('p95',.95),('p99',.99)]})
|
||||
|
||||
|
||||
def collector_stats():
|
||||
container=compose('ps','-q','otel-collector')
|
||||
r=subprocess.run(['docker','stats','--no-stream','--format','{{json .}}',container],capture_output=True,text=True,check=True)
|
||||
value=json.loads(r.stdout)
|
||||
return {'memory':value['MemUsage'],'cpu':value['CPUPerc']}
|
||||
|
||||
|
||||
def main():
|
||||
client=Client(timeout=8);actor,_,_,chat=client.bootstrap()
|
||||
output={'warmup_load':send_load(client,actor,chat,5)}
|
||||
try:
|
||||
# 1. Queue lag: no worker; HTTP remains usable; stored heartbeat reveals cause.
|
||||
compose('stop','worker');began=time.monotonic()
|
||||
pending=[upload(client,actor,chat) for _ in range(3)]
|
||||
wait_for(lambda:alert('MessengerQueueLag')=='firing','queue lag alert did not fire',60)
|
||||
queue=dict(firing=True,detected_seconds=round(time.monotonic()-began,3),
|
||||
depth=number('max(messenger_queue_depth)'),oldest_age_seconds=number('max(messenger_queue_oldest_age_seconds)'),
|
||||
worker_busy=number('max(messenger_worker_busy)'),
|
||||
worker_heartbeat_age_seconds=number('max(time()-messenger_process_last_observed_seconds{service_name="messenger-worker"})'))
|
||||
check(queue['depth']>=3 and queue['oldest_age_seconds']>10,'queue metrics do not explain lag')
|
||||
check(queue['worker_heartbeat_age_seconds']>10,'worker absence not observable')
|
||||
client.message(actor,chat,'messages continue with worker stopped')
|
||||
start_only('worker')
|
||||
for item in pending:wait_state(client,actor,item)
|
||||
wait_for(lambda:alert('MessengerQueueLag')=='resolved','queue alert did not resolve',40)
|
||||
queue.update(resolved=True,depth_after=number('max(messenger_queue_depth)'))
|
||||
output['worker_stopped']=queue
|
||||
print('PASS: queue lag firing -> resolved, heartbeat stale, backlog drained',flush=True)
|
||||
|
||||
# 2. PostgreSQL unavailable; identify dependency spans, not generic slow handler.
|
||||
compose('stop','postgres');begin=time.monotonic();error_trace=None;errors=0
|
||||
while time.monotonic()-begin<50:
|
||||
response=client.call('POST','/api/v1/chats/'+chat['id']+'/messages',503,actor=actor,
|
||||
body={'text':'synthetic outage'},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
error_trace=response['headers']['X-Trace-Id'];errors+=1
|
||||
if alert('MessengerHighErrorRate')=='firing' and time.monotonic()-begin>=15:break
|
||||
check(alert('MessengerHighErrorRate')=='firing','5xx alert did not fire')
|
||||
database=dict(firing=True,detected_seconds=round(time.monotonic()-begin,3),failed_requests=errors,
|
||||
error_ratio=number('messenger:api_error_ratio:rate1m'),
|
||||
db_available=number('min_over_time(messenger_db_available[1m])'),
|
||||
pool_waiting_peak=number('max(max_over_time(messenger_db_pool_waiting[1m]))'),trace_id=error_trace)
|
||||
data=wait_for(lambda:trace_data(error_trace),'DB failure trace not stored',25)
|
||||
children=[s for s in spans(data) if s['name'].startswith('db.')]
|
||||
check(children,'no DB child span explains HTTP failure')
|
||||
check(any(s.get('status',{}).get('code') in (2,'STATUS_CODE_ERROR') for s in children),'DB spans lack error status')
|
||||
check(database['db_available']==0,'DB availability signal did not show outage')
|
||||
dump_evidence('db-incident-trace.json',data)
|
||||
compose('start','postgres');ready(client)
|
||||
# Real recovered traffic, no time-series manipulation.
|
||||
deadline=time.monotonic()+90
|
||||
while alert('MessengerHighErrorRate')!='resolved' and time.monotonic()<deadline:
|
||||
for _ in range(10):client.message(actor,chat,'healthy recovery')
|
||||
time.sleep(.5)
|
||||
check(alert('MessengerHighErrorRate')=='resolved','5xx alert did not resolve')
|
||||
database.update(resolved=True,db_available_after=number('messenger_db_available'))
|
||||
output['postgres_stopped']=database
|
||||
print('PASS: DB error spans + 5xx alert firing -> resolved',flush=True)
|
||||
|
||||
# 3. A telemetry backend down: business writes still work; buffers are finite.
|
||||
before_failed=number('sum(otelcol_exporter_send_failed_spans_total{exporter="otlphttp/tempo"})')
|
||||
before_stats=collector_stats()
|
||||
since=datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
compose('stop','tempo')
|
||||
result=send_load(client,actor,chat,20)
|
||||
check(result['successful_requests']>0 and result['failed_requests']==0,'telemetry backend broke business API')
|
||||
# wait beyond bounded retry deadline so final drops can be observed.
|
||||
time.sleep(8)
|
||||
failed=number('sum(otelcol_exporter_send_failed_spans_total{exporter="otlphttp/tempo"})')-before_failed
|
||||
queued=number('max(max_over_time(otelcol_exporter_queue_size{exporter="otlphttp/tempo"}[1m]))')
|
||||
check(failed>0,'Collector failures not observable')
|
||||
check(queued<=32,'Collector exceeded configured buffer')
|
||||
after_stats=collector_stats()
|
||||
raw_logs=compose('logs','--no-log-prefix','--since',since,'otel-collector')
|
||||
dropped=0
|
||||
for line in raw_logs.splitlines():
|
||||
try:record=json.loads(line)
|
||||
except ValueError:continue
|
||||
if record.get('otelcol.signal')=='traces':dropped+=int(record.get('dropped_items',0))
|
||||
check(dropped>0,'actual dropped trace records not counted')
|
||||
output['tempo_stopped']=dict(workload=result,collector_before=before_stats,collector_during=after_stats,
|
||||
failed_span_send_records_delta=failed,max_queue_batches=queued,queue_limit_batches=32,
|
||||
dropped_spans_from_collector_logs=dropped,business_api_preserved=True)
|
||||
compose('start','tempo')
|
||||
wait_for(lambda:backend('https://tempo:3200/ready',text=True),'Tempo did not recover',40)
|
||||
probe=client.call('GET','/api/v1/users/me',actor=actor)
|
||||
wait_for(lambda:trace_data(probe['headers']['X-Trace-Id']),'traces did not resume',40)
|
||||
output['tempo_stopped']['export_resumed']=True
|
||||
print('PASS: telemetry backend outage preserves writes, queues bounded, dropped spans counted',flush=True)
|
||||
dump_evidence('incidents-grade4.json',output)
|
||||
finally:
|
||||
compose('start','postgres','worker','tempo');ready(client)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Operator lifecycle checks: fresh-connection revocation, secret rotation, sealed lease.
|
||||
Runs sequentially; restores OpenBao and worker in finally. No secret output.
|
||||
"""
|
||||
import json,os,subprocess,time,ssl,urllib.error
|
||||
from pipeline_helpers import *
|
||||
|
||||
def operator(script,*args):
|
||||
p=subprocess.run(['python3',str(ROOT/'scripts'/script),*args],cwd=ROOT,capture_output=True,text=True)
|
||||
check(p.returncode==0,'operator action failed: '+script)
|
||||
|
||||
def main():
|
||||
c=Client(timeout=10);actor,_,_,chat=c.bootstrap()
|
||||
images={s:compose('images','-q',s) for s in ['api1','worker','nginx']}
|
||||
old=json.loads((ROOT/'secrets/operator/service-secrets.json').read_text())['worker']['DATABASE_URL']
|
||||
operator('rotate-db-secret.py')
|
||||
# libpq rejects the previous password on a NEW TLS connection.
|
||||
from urllib.parse import urlsplit
|
||||
u=urlsplit(old)
|
||||
p=subprocess.run(['docker','compose','--env-file','.env','exec','-T','-e','PGPASSWORD','-e','PGSSLMODE=verify-full','-e','PGSSLROOTCERT=/run/ca/ca.crt','postgres','psql','-XAt','-h','postgres','-U','worker','-d','messenger','-c','SELECT 1'],cwd=ROOT,capture_output=True,text=True,env=dict(os.environ,PGPASSWORD=u.password))
|
||||
check(p.returncode!=0 and 'password authentication failed' in p.stderr,'old secret still authenticates')
|
||||
item=upload(c,actor,chat);wait_state(c,actor,item)
|
||||
operator('rotate-leaf.py','worker')
|
||||
code='''
|
||||
import socket,ssl
|
||||
c=ssl.create_default_context(cafile='/audit/public/ca.crt');c.load_cert_chain('/old/cert.crt','/old/key.key')
|
||||
try:
|
||||
with socket.create_connection(('broker',6379),timeout=3) as raw:
|
||||
with c.wrap_socket(raw,server_hostname='broker') as s:
|
||||
s.sendall(b'*1\\r\\n$4\\r\\nPING\\r\\n');data=s.recv(512)
|
||||
assert not data,'revoked certificate accepted'
|
||||
except (OSError,ssl.SSLError):pass
|
||||
print('PASS')
|
||||
'''
|
||||
p=subprocess.run(['docker','compose','--env-file','.env','run','--rm','--no-deps','-v',str(ROOT/'secrets/operator/previous-leaf/worker')+':/old:ro','--entrypoint','python3','audit','-c',code],cwd=ROOT,capture_output=True,text=True)
|
||||
check(p.returncode==0,'revoked leaf passed fresh connection')
|
||||
item=upload(c,actor,chat);wait_state(c,actor,item)
|
||||
# API rejects an expired secret lease while remaining available for /health/live.
|
||||
started=time.monotonic()
|
||||
try:
|
||||
operator('bao-operator.py','seal')
|
||||
def expired():
|
||||
try:return c.call('GET','/api/v1/users/me',503,actor=actor)
|
||||
except Failure:return None
|
||||
wait_for(expired,'API used credentials beyond bounded sealed lease',90)
|
||||
elapsed=time.monotonic()-started
|
||||
c.call('GET','/health/live',schema='Health')
|
||||
finally:
|
||||
operator('bao-operator.py','unseal')
|
||||
compose('start','worker','dispatcher','cleanup')
|
||||
ready(c)
|
||||
c.call('GET','/api/v1/users/me',actor=actor,schema='User')
|
||||
item=upload(c,actor,chat);wait_state(c,actor,item,timeout=120)
|
||||
check(all(compose('images','-q',s)==image for s,image in images.items()),'rotation rebuilt images')
|
||||
result={'status':'PASS','old_DB_password_new_connection':'rejected','new_DB_password':'working','leaf_rotation':'worker','old_leaf_new_connection':'rejected','images_unchanged':True,'sealed_lease_rejected_seconds':round(elapsed,3),'unsealed_recovery':True,'original_session_preserved':True}
|
||||
dump_evidence('lifecycle-grade4.json',result);print('PASS: DB rotation, leaf revocation and sealed/expired secret lease')
|
||||
if __name__=='__main__':run(main)
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Grade 4: real stored signals, W3C chain with retry, dashboard and privacy."""
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from obs_helpers import *
|
||||
|
||||
|
||||
def normalized_id(value):
|
||||
if not value:return ''
|
||||
if all(c in '0123456789abcdef' for c in value.lower()) and len(value) in (16,32):return value.lower()
|
||||
return base64.b64decode(value).hex()
|
||||
|
||||
|
||||
def main():
|
||||
client=Client(timeout=30)
|
||||
actor,_,_,chat=client.bootstrap()
|
||||
marker='PRIVATE-BODY-'+uuid.uuid4().hex
|
||||
client.message(actor,chat,marker)
|
||||
trace_id=uuid.uuid4().hex
|
||||
raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
try:
|
||||
compose('stop','worker')
|
||||
response=client.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=private-canary.png',202,
|
||||
actor=actor,raw=raw,headers={'Content-Type':'image/png','traceparent':'00-'+trace_id+'-0123456789abcdef-01','tracestate':'lab=synthetic'},schema='Attachment')
|
||||
item=response['json'];request_id=response['headers']['X-Request-Id']
|
||||
check(response['headers']['X-Trace-Id']==trace_id,'incoming W3C traceparent not honored')
|
||||
compose('stop','s3');start_only('worker')
|
||||
wait_for(lambda: psql("SELECT attempts>=1 AND state='queued' FROM attachment_jobs WHERE id='"+item['id']+"';")=='t','retry not observed',35)
|
||||
compose('start','s3');ready(client)
|
||||
wait_state(client,actor,item)
|
||||
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'original changed')
|
||||
def linked():
|
||||
data=trace_data(trace_id);found=spans(data)
|
||||
names={s['name'] for s in found}
|
||||
consumers=[s for s in found if s['name']=='attachment.consume']
|
||||
if len(consumers)>=2 and {'attachment.publish','image.process','s3.put','db.update','db.commit'}.issubset(names):return data
|
||||
return None
|
||||
data=wait_for(linked,'complete upload/publish/retry/consume/result trace missing',60)
|
||||
found=spans(data)
|
||||
publishers={normalized_id(s['spanId']) for s in found if s['name']=='attachment.publish'}
|
||||
consumers=[s for s in found if s['name']=='attachment.consume']
|
||||
check(all(normalized_id(s.get('parentSpanId','')) in publishers for s in consumers),'consumer parent is not producer')
|
||||
correlated=wait_for(lambda: [entry for entry in logs(trace_id) if entry.get('event')=='job.completed' and entry.get('outcome')=='success'], 'worker log missing',40)
|
||||
all_logs=logs(trace_id)
|
||||
events={entry['event'] for entry in all_logs}
|
||||
check({'http.request','job.published','job.started','job.completed'}.issubset(events),'API/publisher/worker logs not correlated')
|
||||
check(any(e.get('request_id')==request_id and e['event']=='http.request' for e in all_logs),'request id correlation missing')
|
||||
check(correlated[0]['request_id']==request_id,'worker lost originating request id')
|
||||
encoded=json.dumps(data)+json.dumps(all_logs)+json.dumps(logs(service='messenger-api'))
|
||||
for secret in (marker,actor['token'],actor['registration']['password'],'private-canary.png'):
|
||||
check(secret not in encoded,'sensitive payload/header/filename entered telemetry')
|
||||
# Actual stored metric names, not assumptions from SDK naming.
|
||||
expressions={
|
||||
'http_requests':'sum(messenger_http_requests_total)',
|
||||
'http_histogram':'sum(messenger_http_duration_seconds_count)',
|
||||
'jobs_success':'sum(messenger_jobs_processed_total{outcome="success"})',
|
||||
'jobs_retry':'sum(messenger_jobs_processed_total{outcome="retry"})',
|
||||
'ready_histogram':'sum(messenger_time_to_ready_seconds_count)',
|
||||
'queue':'max(messenger_queue_depth)',
|
||||
'pool':'max(messenger_db_pool_capacity)',
|
||||
'worker_capacity':'max(messenger_worker_capacity)',
|
||||
'memory':'max(messenger_container_memory_bytes)',
|
||||
}
|
||||
values={}
|
||||
for name,expression in expressions.items():
|
||||
wait_for(lambda: prom(expression),'missing metric '+name,20)
|
||||
values[name]=number(expression)
|
||||
check(values['jobs_success']>0 and values['jobs_retry']>0,'worker outcomes absent')
|
||||
metric_rows=prom('{__name__=~"messenger_.*"}')
|
||||
forbidden={'user_id','chat_id','message_id','attachment_id','request_id','filename','url','path','job_id'}
|
||||
check(not any(forbidden.intersection(row['metric']) for row in metric_rows),'high-cardinality metric labels')
|
||||
password=(ROOT/'secrets/grafana_admin_password').read_text().strip()
|
||||
code='''
|
||||
import base64,json,sys,urllib.request
|
||||
p=sys.stdin.read().strip();req=urllib.request.Request('https://grafana:3000/api/dashboards/uid/mtusi-messenger',headers={'Authorization':'Basic '+base64.b64encode(('admin:'+p).encode()).decode()})
|
||||
with urllib.request.urlopen(req,timeout=10) as r:d=json.load(r)
|
||||
print(json.dumps({'title':d['dashboard']['title'],'panels':len(d['dashboard']['panels'])}))
|
||||
'''
|
||||
dashboard=json.loads(compose('exec','-T','worker','python3','-c',code,data=password))
|
||||
check(dashboard['panels']>=18,'provisioned dashboard missing')
|
||||
dump_evidence('trace-example.json',data)
|
||||
dump_evidence('correlated-logs.json',all_logs)
|
||||
output=dict(status='PASS',trace_id=trace_id,request_id=request_id,consumer_attempt_spans=len(consumers),
|
||||
events=sorted(events),metrics=values,dashboard=dashboard,privacy='PASS',low_cardinality='PASS')
|
||||
dump_evidence('observability-grade4.json',output)
|
||||
print('PASS:',json.dumps(output))
|
||||
finally:
|
||||
compose('start','s3','worker');ready(client)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Grade 4: durable acceptance, outbox, crashes, lease, retries, explicit replay."""
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from pipeline_helpers import *
|
||||
|
||||
|
||||
def main():
|
||||
client = Client(timeout=30)
|
||||
ready(client)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
raw = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
results = {}
|
||||
try:
|
||||
# Worker absent: no resize in API, accepted job survives real restarts.
|
||||
compose('stop', 'worker')
|
||||
attachment = upload(client, actor, chat)
|
||||
client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', 409, actor=actor)
|
||||
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=actor,
|
||||
body={'text': '', 'attachment_ids': [attachment['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')
|
||||
services = ('api1', 'api2', 'broker')
|
||||
def starts():
|
||||
values = {}
|
||||
for service in services:
|
||||
container = compose('ps', '-q', service)
|
||||
data = subprocess.run(['docker', 'inspect', container], capture_output=True, text=True, check=True)
|
||||
values[service] = json.loads(data.stdout)[0]['State']['StartedAt']
|
||||
return values
|
||||
before = starts()
|
||||
compose('restart', *services)
|
||||
ready(client)
|
||||
after = starts()
|
||||
check(all(before[s] != after[s] for s in services), 'actual restart not observed')
|
||||
check(state(client, actor, attachment)['status'] == 'queued', 'worker stopped but state changed')
|
||||
start_only('worker')
|
||||
result = wait_state(client, actor, attachment)
|
||||
check({v['name'] for v in result['variants']} == {'thumbnail', 'crop', 'optimized'}, 'missing grade4 variants')
|
||||
check(client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=actor)['bytes'] == raw, 'original changed')
|
||||
wait_for(lambda: psql("SELECT staging_deleted_at IS NOT NULL FROM attachment_jobs WHERE id='" + attachment['id'] + "';") == 't', 'staging not cleaned')
|
||||
results['stopped_worker_and_restart'] = dict(status='PASS', before=before, after=after)
|
||||
|
||||
# Committed outbox remains when dispatcher dies before XADD.
|
||||
compose('stop', 'dispatcher')
|
||||
fault('dispatcher_before_publish')
|
||||
item = upload(client, actor, chat)
|
||||
check(psql("SELECT count(*) FROM attachment_outbox WHERE job_id='" + item['id'] + "';") == '1', 'outbox absent')
|
||||
compose('start', 'dispatcher')
|
||||
hit('dispatcher_before_publish')
|
||||
wait_state(client, actor, item)
|
||||
results['commit_publish_gap'] = 'PASS: actual dispatcher exit 86 and automatic restart'
|
||||
|
||||
# Crash after S3 objects, before final PG COMMIT; reclaim expired processing.
|
||||
fault('worker_after_objects')
|
||||
item = upload(client, actor, chat)
|
||||
hit('worker_after_objects')
|
||||
check(psql("SELECT state FROM attachment_jobs WHERE id='" + item['id'] + "';") == 'processing', 'crash did not leave processing')
|
||||
started = time.monotonic()
|
||||
result = wait_state(client, actor, item, timeout=110)
|
||||
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == '2', 'expired lease not recovered')
|
||||
check(len(result['variants']) == 3, 'duplicate variant metadata')
|
||||
results['crash_after_objects'] = dict(status='PASS', recovery_seconds=round(time.monotonic()-started, 3), attempts=2)
|
||||
|
||||
# COMMIT ready then death before ack: ready must never regress/reprocess.
|
||||
fault('worker_before_ack')
|
||||
item = upload(client, actor, chat)
|
||||
hit('worker_before_ack')
|
||||
result = wait_state(client, actor, item)
|
||||
attempts = psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';")
|
||||
duplicate = dict(schema_version=1, job_id=item['id'], type='attachment.process.v1', attachment_id=item['id'],
|
||||
pipeline_version=1, attempt=1, created_at=item['created_at'])
|
||||
# Use broker password only inside the container, never in evidence.
|
||||
duplicate_id = compose('exec', '-T', 'broker', 'sh', '-ec',
|
||||
'redis-cli -p 16379 --user operator --no-auth-warning -a "$(cat /run/secrets/broker_operator)" XADD attachment.jobs.v1 "*" job "$1"',
|
||||
'sh', json.dumps(duplicate))
|
||||
wait_for(lambda: compose('exec', '-T', 'broker', 'sh', '-ec',
|
||||
'redis-cli -p 16379 --user operator --raw --no-auth-warning -a "$(cat /run/secrets/broker_operator)" XRANGE attachment.jobs.v1 "$1" "$1"',
|
||||
'sh', duplicate_id) == '', 'ready duplicate was not acknowledged')
|
||||
check(state(client, actor, item) == result, 'ready duplicate changed result')
|
||||
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == attempts, 'ready duplicate processed again')
|
||||
results['commit_before_ack_and_duplicate'] = 'PASS'
|
||||
|
||||
# Temporary S3 failure: attempt budget/backoff, failed registry, audited replay.
|
||||
compose('stop', 'worker')
|
||||
item = upload(client, actor, chat)
|
||||
psql("UPDATE attachment_jobs SET max_attempts=2 WHERE id='" + item['id'] + "';")
|
||||
compose('stop', 's3')
|
||||
start_only('worker')
|
||||
check(compose('ps', '--status', 'running', '-q', 's3') == '', 'fault test unexpectedly restarted S3')
|
||||
wait_for(lambda: psql("SELECT state FROM attachment_jobs WHERE id='" + item['id'] + "';") == 'failed', 'temporary errors did not exhaust retries', 100)
|
||||
compose('start', 's3')
|
||||
ready(client)
|
||||
failed = state(client, actor, item)
|
||||
check(failed['error_code'] == 'retry_exhausted', 'unsafe or missing final error')
|
||||
client.call('GET', '/api/v1/attachments/' + item['id'] + '/content', 409, actor=actor)
|
||||
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=actor,
|
||||
body={'text':'failed', 'attachment_ids':[item['id']]}, headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
registry = compose('exec', '-T', 'dispatcher', '/messenger', 'failed-jobs')
|
||||
check(item['id'] in registry, 'failed registry missing job')
|
||||
compose('exec', '-T', 'dispatcher', '/messenger', 'replay', item['id'])
|
||||
wait_state(client, actor, item)
|
||||
check(psql("SELECT count(*) FROM attachment_replays WHERE job_id='" + item['id'] + "';") == '1', 'replay audit missing')
|
||||
proc = subprocess.run(['docker','compose','--env-file','.env','exec','-T','dispatcher','/messenger','replay',item['id']], cwd=ROOT, capture_output=True)
|
||||
check(proc.returncode != 0, 'ready replay must be refused')
|
||||
results['retry_failed_registry_replay'] = dict(status='PASS', exhausted_attempts=2, error_code='retry_exhausted', replay_audit_rows=1, ready_replay_rejected=True)
|
||||
|
||||
# Permanent invalid staging: no endless retries, safe machine error.
|
||||
compose('stop', 'worker')
|
||||
item = upload(client, actor, chat)
|
||||
original_key = uuid.uuid4().hex
|
||||
original_body = {'text':'accepted while queued', 'attachment_ids':[item['id']]}
|
||||
original_message = client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
|
||||
actor=actor, body=original_body, headers={'Idempotency-Key':original_key}, schema='Message')['json']
|
||||
# Integrity metadata mismatch represents invalid durable source.
|
||||
psql("UPDATE attachments SET sha256=repeat('0',64) WHERE id='" + item['id'] + "';")
|
||||
start_only('worker')
|
||||
failed = wait_state(client, actor, item, 'failed')
|
||||
check(failed['error_code'] == 'invalid_image', 'permanent invalid source must fail safely')
|
||||
check(psql("SELECT attempts FROM attachment_jobs WHERE id='" + item['id'] + "';") == '1', 'permanent error retried')
|
||||
repeated = client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201,
|
||||
actor=actor, body=original_body, headers={'Idempotency-Key':original_key}, schema='Message')['json']
|
||||
check(repeated == original_message, 'committed message replay changed after attachment failed')
|
||||
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409,
|
||||
actor=actor, body=original_body, headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
results['permanent_error'] = 'PASS'
|
||||
results['message_replay_after_attachment_failure'] = 'PASS'
|
||||
results['crash_points'] = json.loads(psql("SELECT json_agg(json_build_object('point',point,'armed',armed,'hit_at',hit_at) ORDER BY point) FROM pipeline_faults WHERE hit_at IS NOT NULL;"))
|
||||
dump_evidence('pipeline-grade4.json', results)
|
||||
print('PASS:', json.dumps(results))
|
||||
finally:
|
||||
compose('start', 's3', 'broker', 'dispatcher', 'worker', 'api1', 'api2')
|
||||
psql('DELETE FROM pipeline_faults;')
|
||||
ready(client)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Public persistence/failover hooks plus actual container restart evidence."""
|
||||
import json
|
||||
import datetime
|
||||
import subprocess
|
||||
import uuid
|
||||
from pipeline_helpers import *
|
||||
|
||||
|
||||
def snapshots():
|
||||
services=('postgres','redis','s3','broker','api1','api2','dispatcher','worker','cleanup','nginx','otel-collector','prometheus','loki','tempo','grafana','openbao')
|
||||
result={}
|
||||
for service in services:
|
||||
container=compose('ps','-q',service)
|
||||
info=subprocess.run(['docker','inspect',container],capture_output=True,text=True,check=True)
|
||||
data=json.loads(info.stdout)[0]
|
||||
result[service]=dict(id=data['Id'],started_at=data['State']['StartedAt'])
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
client=Client();ready(client)
|
||||
before=snapshots()
|
||||
base=client.base
|
||||
command=['make','test-persistence','ACTION_SCRIPT=scripts/restart.sh','BASE_URL='+base,'CA_FILE='+str(ROOT/'secrets/public/ca.crt')]
|
||||
result=subprocess.run(command,cwd=ROOT,capture_output=True,text=True)
|
||||
check(result.returncode==0,'public persistence failed: '+result.stdout[-500:])
|
||||
after=snapshots()
|
||||
check(all(before[s]['started_at']!=after[s]['started_at'] for s in before),'hook did not restart all required services')
|
||||
|
||||
output={'persistence':dict(status='PASS',before=before,after=after),'failover':[]}
|
||||
public=subprocess.run(['make','test-failover','ACTION_SCRIPT=scripts/stop-one.sh','BASE_URL='+base,'CA_FILE='+str(ROOT/'secrets/public/ca.crt')],cwd=ROOT,capture_output=True,text=True)
|
||||
check(public.returncode==0,'public failover failed: '+public.stdout[-500:])
|
||||
output['public_failover']=dict(status='PASS',output=public.stdout.strip())
|
||||
try:
|
||||
compose('start','api1','api2');ready(client)
|
||||
actor,_,_,chat=client.bootstrap()
|
||||
item=upload(client,actor,chat);wait_state(client,actor,item)
|
||||
raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
path='/api/v1/chats/'+chat['id']+'/messages'
|
||||
for target in ('api-1','api-2'):
|
||||
compose('start','api1','api2');ready(client)
|
||||
seen=set()
|
||||
wait_for(lambda: (seen.add(client.call('GET','/health/ready')['headers']['X-Instance-Id']) or len(seen)==2),'two replicas not visible')
|
||||
process=subprocess.Popen([str(ROOT/'scripts/stop-one.sh')],cwd=ROOT,
|
||||
env=dict(os.environ,TARGET_INSTANCE_ID=target),stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
began=time.monotonic();deadline=began+8;first=None;confirmed=set();failures=0
|
||||
key=uuid.uuid4().hex
|
||||
while time.monotonic()<deadline:
|
||||
try:
|
||||
response=client.call('POST',path,201,actor=actor,body={'text':key},headers={'Idempotency-Key':key},schema='Message')
|
||||
confirmed.add(response['json']['id'])
|
||||
if process.poll() is not None and response['headers']['X-Instance-Id']!=target and first is None:
|
||||
first=time.monotonic()-began
|
||||
key=uuid.uuid4().hex
|
||||
except Failure:
|
||||
failures+=1
|
||||
time.sleep(.1)
|
||||
check(process.wait(timeout=10)==0,'stop hook failed')
|
||||
check(first is not None and first<=10,'surviving API did not recover within 10 seconds')
|
||||
service={'api-1':'api1','api-2':'api2'}[target]
|
||||
check(not compose('ps','--status','running','-q',service),'target was not actually stopped')
|
||||
page=client.call('GET',path+'?limit=100',actor=actor,schema='MessagePage')['json']
|
||||
visible={m['id'] for m in page['items']}
|
||||
# At most 80 requests per case: walk pages to include both cases.
|
||||
while page['next_cursor']:
|
||||
from urllib.parse import quote
|
||||
page=client.call('GET',path+'?limit=100&cursor='+quote(page['next_cursor']),actor=actor,schema='MessagePage')['json']
|
||||
visible.update(m['id'] for m in page['items'])
|
||||
check(confirmed.issubset(visible),'confirmed messages lost')
|
||||
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'original lost on API failover')
|
||||
output['failover'].append(dict(status='PASS',stopped_service=service,confirmed_messages=len(confirmed),
|
||||
transient_failures=failures,first_survivor_seconds=round(first,3),original_preserved=True))
|
||||
finally:
|
||||
compose('start','api1','api2');ready(client)
|
||||
saved=ROOT/'evidence/observability-grade4.json'
|
||||
if saved.exists():
|
||||
from obs_helpers import trace_data, logs, number
|
||||
trace_id=json.loads(saved.read_text())['trace_id']
|
||||
wait_for(lambda:trace_data(trace_id),'stored trace lost after telemetry restart',60)
|
||||
wait_for(lambda:logs(trace_id),'stored logs lost after telemetry restart',60)
|
||||
check(number('sum(messenger_http_requests_total)')>0,'metrics unavailable after restart')
|
||||
stamp=datetime.datetime.fromisoformat(after['prometheus']['started_at'].replace('Z','+00:00')).timestamp()-10
|
||||
historical=number('sum(messenger_http_requests_total @ '+str(stamp)+')')
|
||||
check(historical>0,'historical metrics lost after Prometheus restart')
|
||||
output['metric_history_before_restart']={'unix_time':stamp,'http_counter_sum':historical}
|
||||
output['telemetry_history_preserved']=True
|
||||
dump_evidence('resilience.json',output)
|
||||
print('PASS: all core/telemetry/OpenBao services restarted, same token/data/original preserved; both API failures covered')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""HTTPS ACL, Argon migration, shared rate limit and session revocation."""
|
||||
import base64,hashlib,json,os,ssl,time,uuid
|
||||
from pipeline_helpers import *
|
||||
|
||||
def basic(u,p):return {'Authorization':'Basic '+base64.b64encode((u+':'+p).encode()).decode()}
|
||||
def main():
|
||||
c=Client();actor,_,outsider,chat=c.bootstrap();raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
item=upload(c,actor,chat);wait_state(c,actor,item)
|
||||
c.call('GET','/api/v1/attachments/'+item['id'],404,actor=outsider)
|
||||
c.call('GET','/api/v1/attachments/'+item['id']+'/content',404,actor=outsider)
|
||||
c.call('GET','/api/v1/users/me',actor=outsider,headers={'X-User-Id':actor['id']},schema='User')
|
||||
own=c.call('GET','/api/v1/users/me',actor=outsider,headers={'X-User-Id':actor['id']},schema='User')['json']
|
||||
check(own['id']==outsider['id'],'spoofed identity accepted')
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=forbidden.png',404,actor=outsider,raw=raw,headers={'Content-Type':'image/png'})
|
||||
stored=psql("SELECT password_hash FROM users WHERE id='"+actor['id']+"';")
|
||||
check(stored.startswith('$argon2id$v=19$m=19456,t=2,p=1$'),'Argon2id parameters missing')
|
||||
# Actual legacy scrypt row, followed by real Basic login and persisted rehash.
|
||||
reg=actor['registration'];salt=os.urandom(16)
|
||||
digest=hashlib.scrypt(reg['password'].encode(),salt=salt,n=32768,r=8,p=1,dklen=32,maxmem=64*1024*1024)
|
||||
enc=lambda b:base64.b64encode(b).decode().rstrip('=')
|
||||
legacy='scrypt$32768$8$1$'+enc(salt)+'$'+enc(digest)
|
||||
psql("UPDATE users SET password_hash='"+legacy+"' WHERE id='"+actor['id']+"';")
|
||||
began=time.monotonic();c.call('POST','/api/v1/auth/sessions',201,headers=basic(reg['username'],reg['password']))
|
||||
rehash_ms=(time.monotonic()-began)*1000
|
||||
check(psql("SELECT password_hash LIKE '$argon2id$%' FROM users WHERE id='"+actor['id']+"';")=='t','successful login did not rehash legacy')
|
||||
# Only a hash of the bearer token is a session key.
|
||||
expected='session:'+hashlib.sha256(actor['token'].encode()).hexdigest()
|
||||
check(actor['token'] not in stored,'password storage leaked bearer')
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=actor)
|
||||
c.call('GET','/api/v1/users/me',401,actor=actor)
|
||||
# Actual Redis expiry on the existing session; operator shortens only this synthetic key.
|
||||
key='session:'+hashlib.sha256(outsider['token'].encode()).hexdigest()
|
||||
compose('exec','-T','redis','sh','-ec','redis-cli -p 16379 --user operator --no-auth-warning -a "$(cat /run/secrets/redis_operator)" EXPIRE "$1" 1','sh',key)
|
||||
time.sleep(2)
|
||||
c.call('GET','/api/v1/users/me',401,actor=outsider)
|
||||
# A repeated username shares its budget across both LB backends.
|
||||
identity='limit_'+uuid.uuid4().hex[:12];seen=set();throttled=[]
|
||||
for i in range(16):
|
||||
r=c.call('POST','/api/v1/auth/sessions',[401,429],headers=basic(identity,'wrong'))
|
||||
seen.add(r['headers']['X-Instance-Id'])
|
||||
if r['status']==429:
|
||||
check(int(r['headers']['Retry-After'])>0,'Retry-After missing');throttled.append(i)
|
||||
check(len(seen)==2 and throttled and throttled[0]==10,'rate budget is not shared across replicas')
|
||||
# The CA is trusted, but this hostname must still be rejected.
|
||||
try:
|
||||
import socket
|
||||
with socket.create_connection(('localhost',8443),timeout=3) as sock:
|
||||
ssl.create_default_context(cafile=str(ROOT/'secrets/public/ca.crt')).wrap_socket(sock,server_hostname='wrong.invalid')
|
||||
raise Failure('wrong hostname accepted')
|
||||
except ssl.SSLCertVerificationError:pass
|
||||
result={'status':'PASS','argon2id':'m=19456KiB,t=2,p=1','legacy_rehash_ms':round(rehash_ms,3),'outsider_metadata_content_upload':'denied','spoofed_header':'ignored','logout':'401','session_expiry':'401','shared_rate_limit_first_429_attempt':throttled[0]+1,'api_instances':sorted(seen),'hostname_mismatch':'rejected'}
|
||||
dump_evidence('security-grade4.json',result);print('PASS: HTTPS ACL, real legacy rehash, logout and shared rate limit')
|
||||
if __name__=='__main__':run(main)
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Operator internal TLS/policy and runtime hardening audit; no Config.Env dump."""
|
||||
import subprocess
|
||||
from pipeline_helpers import *
|
||||
|
||||
|
||||
def main():
|
||||
result = json.loads(compose('run', '--rm', '--no-deps', 'audit'))
|
||||
check(result['status'] == 'PASS', 'TLS matrix audit failed')
|
||||
controls = {}
|
||||
for service in ['api1', 'api2', 'worker', 'dispatcher', 'cleanup', 'otel-collector', 'prometheus', 'loki', 'tempo', 'grafana', 'nginx']:
|
||||
container = compose('ps', '-q', service)
|
||||
info = json.loads(subprocess.check_output(['docker', 'inspect', container], text=True))[0]
|
||||
h = info['HostConfig']
|
||||
check(not h['Privileged'] and h['NetworkMode'] != 'host', 'unsafe container privilege')
|
||||
check(h['ReadonlyRootfs'] and 'ALL' in h['CapDrop'], 'missing read_only/cap_drop')
|
||||
check(any('no-new-privileges' in x for x in h['SecurityOpt']), 'missing no-new-privileges')
|
||||
check(h['Memory'] > 0 and h['NanoCpus'] > 0, 'missing resource limit')
|
||||
check(not any('docker.sock' in m['Source'] for m in info['Mounts']), 'Docker socket exposed')
|
||||
if service in ['api1', 'api2', 'worker', 'dispatcher', 'cleanup']:
|
||||
check(info['Config']['User'].split(':')[0] not in ('', '0', 'root'), 'application runs as root')
|
||||
check(not any('/secrets/operator' in m['Source'] for m in info['Mounts']), 'operator material exposed')
|
||||
controls[service] = 'PASS'
|
||||
result['runtime_hardening'] = controls
|
||||
dump_evidence('tls-matrix-grade4.json', result)
|
||||
print('PASS: TLS/mTLS matrix, denied identities, closed plaintext hops, scoped Bao and runtime hardening')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Grade 4 image contract: actual decoding, EXIF, alpha, limits and private storage."""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import struct
|
||||
import uuid
|
||||
import zlib
|
||||
from pipeline_helpers import *
|
||||
|
||||
|
||||
def make_fixture(kind):
|
||||
code = '''
|
||||
import base64,io,sys
|
||||
from PIL import Image
|
||||
kind=sys.argv[1]
|
||||
if kind=='orientation':
|
||||
im=Image.new('RGB',(320,200),'red');exif=Image.Exif();exif[274]=6;exif[315]='synthetic test';kw=dict(format='JPEG',exif=exif)
|
||||
elif kind=='alpha':
|
||||
im=Image.new('RGBA',(8,4),(255,0,0,0));kw=dict(format='PNG')
|
||||
elif kind=='boundary':
|
||||
im=Image.new('RGB',(8000,5000),'blue');kw=dict(format='PNG')
|
||||
else:
|
||||
im=Image.new('RGB',(1601,801),'blue');kw=dict(format='PNG')
|
||||
b=io.BytesIO();im.save(b,**kw);print(base64.b64encode(b.getvalue()).decode())
|
||||
'''
|
||||
return base64.b64decode(compose('exec', '-T', 'worker', 'python3', '-c', code, kind))
|
||||
|
||||
|
||||
def inspect_image(raw):
|
||||
code = '''
|
||||
import base64,io,json,sys
|
||||
from PIL import Image
|
||||
im=Image.open(io.BytesIO(base64.b64decode(sys.stdin.read())));im.load()
|
||||
print(json.dumps(dict(format=im.format,width=im.width,height=im.height,exif=len(im.getexif()),pixel=list(im.convert('RGB').getpixel((0,0))))))
|
||||
'''
|
||||
return json.loads(compose('exec', '-T', 'worker', 'python3', '-c', code, data=base64.b64encode(raw).decode()))
|
||||
|
||||
|
||||
def chunk(kind, payload):
|
||||
return struct.pack('>I', len(payload)) + kind + payload + struct.pack('>I', zlib.crc32(kind+payload) & 0xffffffff)
|
||||
|
||||
|
||||
def main():
|
||||
client=Client(timeout=60)
|
||||
actor, _, outsider, chat=client.bootstrap()
|
||||
results={}
|
||||
for kind in ('orientation','alpha','large','boundary'):
|
||||
raw=make_fixture(kind)
|
||||
content_type='image/jpeg' if kind=='orientation' else 'image/png'
|
||||
item=client.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=synthetic',202,actor=actor,raw=raw,
|
||||
headers={'Content-Type':content_type},schema='Attachment')['json']
|
||||
result=wait_state(client,actor,item)
|
||||
variants={v['name']:v for v in result['variants']}
|
||||
expected={'orientation':(160,256),'alpha':(8,4),'large':(256,128),'boundary':(256,160)}[kind]
|
||||
check((variants['thumbnail']['width'],variants['thumbnail']['height'])==expected,'thumbnail dimensions/orientation')
|
||||
check((variants['crop']['width'],variants['crop']['height'])==(128,128),'crop dimensions')
|
||||
optimized={'orientation':(200,320),'alpha':(8,4),'large':(1280,640),'boundary':(1280,800)}[kind]
|
||||
check((variants['optimized']['width'],variants['optimized']['height'])==optimized,'optimized fit dimensions')
|
||||
for name,meta in variants.items():
|
||||
blob=client.call('GET','/api/v1/attachments/'+item['id']+'/content?variant='+name,actor=actor)['bytes']
|
||||
check(hashlib.sha256(blob).hexdigest()==meta['sha256'] and len(blob)==meta['size_bytes'],'variant checksum/size')
|
||||
decoded=inspect_image(blob)
|
||||
check(decoded['format']==('WEBP' if name=='optimized' else 'JPEG'),'actual variant encoding')
|
||||
check(decoded['exif']==0,'EXIF leaked into variant')
|
||||
if kind=='alpha':
|
||||
check(all(v>=250 for v in decoded['pixel']),'alpha not composited on white')
|
||||
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'original changed')
|
||||
client.call('GET','/api/v1/attachments/'+item['id'],404,actor=outsider)
|
||||
client.call('GET','/api/v1/attachments/'+item['id']+'/content?variant=crop',404,actor=outsider)
|
||||
client.call('GET','/api/v1/attachments/'+item['id']+'/content?variant=missing',404,actor=actor)
|
||||
results[kind]={'status':'PASS','variants':variants}
|
||||
original=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
for size in (6294458,10485760):
|
||||
extra=size-len(original)-12
|
||||
raw=original[:-12]+chunk(b'paDd',bytes(extra))+original[-12:]
|
||||
check(len(raw)==size,'fixture exact size')
|
||||
item=upload(client,actor,chat,raw)
|
||||
wait_state(client,actor,item)
|
||||
check(client.call('GET','/api/v1/attachments/'+item['id']+'/content',actor=actor)['bytes']==raw,'large original changed')
|
||||
path='/api/v1/chats/'+chat['id']+'/attachments?filename=bad.png'
|
||||
client.call('POST',path,413,actor=actor,raw=bytes(10485761),headers={'Content-Type':'image/png'})
|
||||
for raw in (original[:40],original[:-12],b'not an image'):
|
||||
client.call('POST',path,415,actor=actor,raw=raw,headers={'Content-Type':'image/png'})
|
||||
huge=b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',20000,10000,8,2,0,0,0))+chunk(b'IEND',b'')
|
||||
client.call('POST',path,413,actor=actor,raw=huge,headers={'Content-Type':'image/png'})
|
||||
results['byte_limits_corrupt_pixel_limits']='PASS'
|
||||
item=upload(client,actor,chat)
|
||||
wait_state(client,actor,item)
|
||||
audit=compose('exec','-T','api1','/messenger','s3-audit','originals/'+item['id'])
|
||||
check('PASS' in audit,'S3 credential audit failed')
|
||||
results['private_bucket_limited_credentials']='PASS'
|
||||
metrics=json.loads(compose('exec','-T','worker','/messenger','memory'))
|
||||
check(metrics['memory.peak'] < metrics['memory.max'],'worker reached memory limit')
|
||||
results['worker_memory_bytes']=metrics
|
||||
dump_evidence('variants-grade4.json',results)
|
||||
print('PASS: actual JPEG/WebP, EXIF orientation, white alpha, bounds, ACL, checksums, private S3')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user