Complete lab 7 TLS and secret management
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
"""Additional grade-3 checks: concurrent replay and invalid uploads."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import uuid
|
||||
import struct
|
||||
import zlib
|
||||
import subprocess
|
||||
from client import Client, LAB, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Extra acceptance checks')
|
||||
c = Client(args.base_url,args.ca_file)
|
||||
alice,bob,eve,chat = c.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
def send(_):
|
||||
return c.message(alice,chat,'Concurrent retry',key=key)['json']
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
results = list(pool.map(send,range(16)))
|
||||
check(all(r==results[0] for r in results),'concurrent replay created different messages')
|
||||
print('PASS: 16 concurrent retries return one message')
|
||||
if LAB >= 4:
|
||||
path = '/api/v1/chats/'+chat['id']+'/attachments'
|
||||
content = open('tests/fixtures/sample.png','rb').read()
|
||||
c.call('POST',path+'?filename=../x.png',400,actor=alice,raw=content,headers={'Content-Type':'image/png'})
|
||||
c.call('POST',path+'?filename=x.jpg',415,actor=alice,raw=content,headers={'Content-Type':'image/jpeg'})
|
||||
c.call('POST',path+'?filename=x.png',415,actor=alice,raw=b'broken',headers={'Content-Type':'image/png'})
|
||||
c.call('POST',path+'?filename=x.png',413,actor=alice,raw=b'x'*(10485760+1),headers={'Content-Type':'image/png'})
|
||||
# A real valid PNG >40 million pixels, highly compressible on the wire.
|
||||
def chunk(kind, data):
|
||||
return struct.pack('!I',len(data))+kind+data+struct.pack('!I',zlib.crc32(kind+data)&0xffffffff)
|
||||
compressor = zlib.compressobj()
|
||||
compressed = b''.join(compressor.compress(b'\0'*10001) for _ in range(4001))+compressor.flush()
|
||||
huge = b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('!IIBBBBB',10000,4001,8,0,0,0,0))+chunk(b'IDAT',compressed)+chunk(b'IEND',b'')
|
||||
c.call('POST',path+'?filename=huge.png',413,actor=alice,raw=huge,headers={'Content-Type':'image/png'})
|
||||
jpeg = subprocess.check_output(['docker','compose','exec','-T','api1','python','-c',"from PIL import Image; import sys; Image.new('RGB',(8,8),'red').save(sys.stdout.buffer,format='JPEG')"])
|
||||
uploaded = c.call('POST',path+'?filename=real.jpg',202,actor=alice,raw=jpeg,headers={'Content-Type':'image/jpeg'},schema='Attachment')['json']
|
||||
uploaded = c.wait_ready(bob,uploaded)
|
||||
downloaded = c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content',actor=bob)
|
||||
check(downloaded['bytes']==jpeg,'JPEG original changed')
|
||||
other = c.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Another chat','member_ids':[alice['id']]},schema='Chat')['json']
|
||||
c.call('POST','/api/v1/chats/'+other['id']+'/messages',404,actor=alice,body={'text':'','attachment_ids':[uploaded['id']]},headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
print('PASS: real JPEG roundtrip; >40 million pixels rejected; cross-chat attachment rejected')
|
||||
print('PASS: unsafe filename, MIME mismatch, corruption and byte limit')
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Stop the API that accepted a file after its asynchronous job is ready."""
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args=arguments('Upload/download failover on both APIs')
|
||||
c=Client(args.base_url,args.ca_file)
|
||||
alice,bob,eve,chat=c.bootstrap()
|
||||
content=open('tests/fixtures/sample.png','rb').read()
|
||||
path='/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png'
|
||||
for service in ('api1','api2'):
|
||||
cid=subprocess.check_output(['docker','compose','ps','-q',service],text=True).strip()
|
||||
env=subprocess.check_output(['docker','inspect','--format','{{range .Config.Env}}{{println .}}{{end}}',cid],text=True)
|
||||
target=next((line.split('=',1)[1] for line in env.splitlines() if line.startswith('APP_INSTANCE_ID=')),None)
|
||||
check(bool(target),'API instance identity is missing')
|
||||
for _ in range(20):
|
||||
uploaded=c.call('POST',path,202,actor=alice,raw=content,headers={'Content-Type':'image/png'},schema='Attachment')
|
||||
if uploaded['headers']['X-Instance-Id']==target: break
|
||||
else: raise AssertionError('Target API not observed through LB')
|
||||
att=uploaded['json']; c.wait_ready(alice,att)
|
||||
c.message(alice,chat,'',attachments=[att['id']])
|
||||
started=time.monotonic()
|
||||
try:
|
||||
subprocess.run(['scripts/stop-one.sh'],env=dict(os.environ,TARGET_INSTANCE_ID=target),check=True,stdout=subprocess.DEVNULL)
|
||||
while time.monotonic()-started<10:
|
||||
try: downloaded=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)
|
||||
except Exception:
|
||||
time.sleep(.2); continue
|
||||
check(downloaded['headers']['X-Instance-Id']!=target,'stopped API still responds')
|
||||
check(downloaded['bytes']==content,'original changed')
|
||||
print('PASS:',service,'downloaded original via other API in',round(time.monotonic()-started,3),'s; SHA-256',hashlib.sha256(content).hexdigest(),flush=True)
|
||||
break
|
||||
else: raise AssertionError('Download did not recover within 10 seconds')
|
||||
finally:
|
||||
subprocess.run(['docker','compose','start',service],check=True)
|
||||
for _ in range(30):
|
||||
health=subprocess.check_output(['docker','inspect','--format','{{.State.Health.Status}}',cid],text=True).strip()
|
||||
if health=='healthy': time.sleep(2); break
|
||||
time.sleep(1)
|
||||
else: raise AssertionError('API did not recover')
|
||||
|
||||
if __name__=='__main__': run(main)
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run from the API/worker container to verify scoped runtime identities."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from app.secrets import load_secrets
|
||||
load_secrets()
|
||||
|
||||
|
||||
def bao(path,method='GET',body=None,token=None):
|
||||
ctx=ssl.create_default_context(cafile=os.environ['BAO_CA_CERT'])
|
||||
data=None if body is None else json.dumps(body).encode()
|
||||
req=urllib.request.Request(os.environ['BAO_ADDR'].rstrip('/')+'/v1/'+path,data=data,method=method)
|
||||
if token: req.add_header('X-Vault-Token',token)
|
||||
if data: req.add_header('Content-Type','application/json')
|
||||
try:
|
||||
with urllib.request.urlopen(req,context=ctx,timeout=5) as r: return r.status,json.load(r)
|
||||
except urllib.error.HTTPError as e: return e.code,{}
|
||||
|
||||
|
||||
role=os.environ['APP_ROLE']
|
||||
service_path='messenger/'+role
|
||||
role_id=open(os.environ['BAO_ROLE_ID_FILE']).read().strip()
|
||||
secret_id=open(os.environ['BAO_SECRET_ID_FILE']).read().strip()
|
||||
_,login=bao('auth/approle/login','POST',{'role_id':role_id,'secret_id':secret_id})
|
||||
token=login['auth']['client_token']
|
||||
assert bao('kv/data/'+service_path,token=token)[0]==200
|
||||
other='messenger/worker' if role=='api' else 'messenger/api'
|
||||
assert bao('kv/data/'+other,token=token)[0]==403
|
||||
assert bao('kv/data/'+service_path,'POST',{'data':{'probe':'denied'}},token)[0]==403
|
||||
print('PASS: AppRole reads its own secret only; cross-read and write denied')
|
||||
|
||||
import psycopg
|
||||
from psycopg.errors import InsufficientPrivilege
|
||||
with psycopg.connect(os.environ['DATABASE_URL']) as db:
|
||||
if role=='api':
|
||||
query='DELETE FROM attachments WHERE false'
|
||||
else:
|
||||
query='SELECT username FROM users LIMIT 1'
|
||||
try:
|
||||
db.execute(query)
|
||||
except InsufficientPrivilege:
|
||||
db.rollback()
|
||||
else:
|
||||
raise AssertionError('database role exceeded its table privileges')
|
||||
print('PASS: PostgreSQL role is limited to its assigned tables and actions')
|
||||
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
s3=boto3.client('s3',endpoint_url=os.environ['S3_ENDPOINT'],aws_access_key_id=os.environ['S3_ACCESS_KEY'],
|
||||
aws_secret_access_key=os.environ['S3_SECRET_KEY'],region_name='us-east-1',verify=os.environ['S3_CA_CERT'],
|
||||
config=boto3.session.Config(s3={'addressing_style':'path'}))
|
||||
try:
|
||||
original=os.environ['S3_ORIGINAL_BUCKET']
|
||||
if role=='api': s3.put_object(Bucket=original,Key='security-probe',Body=b'')
|
||||
else: s3.get_object(Bucket=original,Key='security-probe')
|
||||
except ClientError as exc:
|
||||
assert exc.response['ResponseMetadata']['HTTPStatusCode'] in (401,403)
|
||||
else:
|
||||
raise AssertionError('S3 identity accessed a forbidden prefix')
|
||||
print('PASS: S3 identity cannot use a prefix outside its scoped policy')
|
||||
|
||||
import pika
|
||||
params=pika.URLParameters(os.environ['BROKER_URL'])
|
||||
params.ssl_options=pika.SSLOptions(ssl.create_default_context(cafile=os.environ['BROKER_CA_CERT']),'broker')
|
||||
connection=pika.BlockingConnection(params)
|
||||
channel=connection.channel()
|
||||
try:
|
||||
channel.queue_declare(queue='forbidden.security.probe',durable=True)
|
||||
except pika.exceptions.ChannelClosedByBroker as exc:
|
||||
assert exc.reply_code==403
|
||||
else:
|
||||
channel.close(); connection.close()
|
||||
raise AssertionError('broker identity configured a queue outside its permission')
|
||||
connection.close()
|
||||
print('PASS: RabbitMQ identity is restricted to the attachment queue')
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Verify the protected Prometheus, Loki, Tempo and Grafana endpoints."""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PKI = ROOT / '.local' / 'pki'
|
||||
PROM = os.getenv('PROM_URL', 'https://localhost:9097')
|
||||
LOKI = os.getenv('LOKI_URL', 'https://localhost:3107')
|
||||
TEMPO = os.getenv('TEMPO_URL', 'https://localhost:3207')
|
||||
GRAFANA = os.getenv('GRAFANA_URL', 'https://localhost:3007')
|
||||
|
||||
|
||||
def context_for(url):
|
||||
context = ssl.create_default_context(cafile=str(PKI / 'service-ca.crt'))
|
||||
if url.startswith((PROM, LOKI, TEMPO)):
|
||||
context.load_cert_chain(str(PKI / 'backend-grafana.crt'), str(PKI / 'backend-grafana.key'))
|
||||
return context
|
||||
|
||||
|
||||
def get_json(url, auth=None):
|
||||
request = urllib.request.Request(url)
|
||||
if auth:
|
||||
token = base64.b64encode((auth[0] + ':' + auth[1]).encode()).decode()
|
||||
request.add_header('Authorization', 'Basic ' + token)
|
||||
with urllib.request.urlopen(request, context=context_for(url), timeout=8) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def grafana_password():
|
||||
value = os.getenv('GRAFANA_PASSWORD')
|
||||
if value:
|
||||
return value
|
||||
env_file = ROOT / '.env'
|
||||
if env_file.exists():
|
||||
for line in env_file.read_text().splitlines():
|
||||
if line.startswith('GRAFANA_PASSWORD='):
|
||||
return line.split('=', 1)[1]
|
||||
return 'local-grafana-password-only'
|
||||
|
||||
|
||||
def prom_value(expr):
|
||||
doc = get_json(PROM + '/api/v1/query?' + urllib.parse.urlencode({'query': expr}))
|
||||
assert doc['status'] == 'success', doc
|
||||
result = doc['data']['result']
|
||||
return float(result[0]['value'][1]) if result else 0.0
|
||||
|
||||
|
||||
def main():
|
||||
deadline = time.time() + 90
|
||||
api_total = worker_total = 0.0
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
api_total = prom_value('sum(messenger_http_requests_total)')
|
||||
worker_total = prom_value('sum(messenger_jobs_processed_total)')
|
||||
if api_total > 0 and worker_total > 0:
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(2)
|
||||
assert api_total > 0, 'API request metric not found in Prometheus'
|
||||
assert worker_total > 0, 'worker job metric not found in Prometheus'
|
||||
|
||||
start = int((time.time() - 900) * 1_000_000_000)
|
||||
end = time.time_ns()
|
||||
q = '{service_name="messenger-api"} |= "http.request.completed"'
|
||||
url = LOKI + '/loki/api/v1/query_range?' + urllib.parse.urlencode(
|
||||
{'query': q, 'start': str(start), 'end': str(end), 'limit': '20', 'direction': 'backward'})
|
||||
logs = get_json(url)
|
||||
assert logs['status'] == 'success' and logs['data']['result'], 'API structured logs not found in Loki'
|
||||
|
||||
deadline = time.time() + 90
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(TEMPO + '/ready', context=context_for(TEMPO), timeout=5) as response:
|
||||
if response.status == 200:
|
||||
break
|
||||
except Exception:
|
||||
time.sleep(2)
|
||||
else:
|
||||
raise AssertionError('Tempo did not become ready')
|
||||
|
||||
def trace_search(service):
|
||||
params = {'tags': 'service.name=' + service, 'start': str(int(time.time() - 900)),
|
||||
'end': str(int(time.time())), 'limit': '20'}
|
||||
return get_json(TEMPO + '/api/search?' + urllib.parse.urlencode(params)).get('traces', [])
|
||||
|
||||
api_traces = worker_traces = []
|
||||
deadline = time.time() + 90
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
api_traces = trace_search('messenger-api')
|
||||
worker_traces = trace_search('messenger-worker')
|
||||
if api_traces and worker_traces:
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(3)
|
||||
assert api_traces, 'API traces not found in Tempo'
|
||||
assert worker_traces, 'worker traces not found in Tempo'
|
||||
|
||||
correlated_trace = None
|
||||
deadline = time.time() + 90
|
||||
while time.time() < deadline and correlated_trace is None:
|
||||
q = '{service_name="messenger-worker"} |= "worker.job.completed"'
|
||||
params = {'query': q, 'start': str(int((time.time() - 900) * 1_000_000_000)),
|
||||
'end': str(time.time_ns()), 'limit': '20', 'direction': 'backward'}
|
||||
rows = get_json(LOKI + '/loki/api/v1/query_range?' + urllib.parse.urlencode(params))['data']['result']
|
||||
for row in rows:
|
||||
trace_id = row['stream'].get('trace_id')
|
||||
if not trace_id:
|
||||
continue
|
||||
try:
|
||||
trace_doc = get_json(TEMPO + '/api/traces/' + trace_id)
|
||||
except Exception:
|
||||
continue
|
||||
services = set()
|
||||
for batch in trace_doc.get('batches', []):
|
||||
for attr in batch.get('resource', {}).get('attributes', []):
|
||||
if attr.get('key') == 'service.name':
|
||||
services.add(attr.get('value', {}).get('stringValue'))
|
||||
if {'messenger-api', 'messenger-worker'} <= services:
|
||||
correlated_trace = trace_id
|
||||
break
|
||||
if correlated_trace is None:
|
||||
time.sleep(2)
|
||||
assert correlated_trace, 'worker log trace is not correlated with API trace'
|
||||
|
||||
health = get_json(GRAFANA + '/api/health')
|
||||
assert health.get('database') == 'ok', 'Grafana is not ready'
|
||||
password = grafana_password()
|
||||
dashboard = get_json(GRAFANA + '/api/dashboards/uid/messenger-observability', ('admin', password))
|
||||
assert dashboard.get('dashboard', {}).get('uid') == 'messenger-observability', 'provisioned dashboard is missing'
|
||||
|
||||
print('PASS: protected Prometheus/Loki/Tempo; API and worker telemetry; correlated traces; Grafana dashboard')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Inject a corrupt staged object and prove bounded failure is visible."""
|
||||
import subprocess
|
||||
import time
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args=arguments('Bounded retry and safe failed state')
|
||||
c=Client(args.base_url,args.ca_file,timeout=10)
|
||||
alice,bob,eve,chat=c.bootstrap()
|
||||
subprocess.run(['docker','compose','stop','worker'],check=True,stdout=subprocess.DEVNULL)
|
||||
try:
|
||||
att,original=c.attachment(alice,chat)
|
||||
code="from app.worker import s3,BUCKET; import os,psycopg; c=psycopg.connect(os.environ['DATABASE_URL']); k=c.execute('SELECT stage_key FROM attachments WHERE id=%s',(\""+att['id']+"\",)).fetchone()[0]; s3().put_object(Bucket=BUCKET,Key=k,Body=b'corrupt image data',ContentType='image/png'); c.close()"
|
||||
subprocess.run(['docker','compose','exec','-T','api1','python','-c',code],check=True,stdout=subprocess.DEVNULL)
|
||||
finally:
|
||||
subprocess.run(['docker','compose','up','-d','worker'],check=True,stdout=subprocess.DEVNULL)
|
||||
deadline=time.monotonic()+60
|
||||
while time.monotonic()<deadline:
|
||||
att=c.call('GET','/api/v1/attachments/'+att['id'],actor=bob,schema='Attachment')['json']
|
||||
if att['status']=='failed': break
|
||||
time.sleep(.5)
|
||||
check(att['status']=='failed','corrupt image did not reach bounded failed state')
|
||||
check(att['error_code'] in ('invalid_image','retry_exhausted'),'unexpected public failure code')
|
||||
c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=bob)
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=alice,
|
||||
body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':'failed-attachment-test'})
|
||||
print('PASS: corrupt job ended as failed after bounded retries; content and message attachment are rejected')
|
||||
|
||||
if __name__=='__main__': run(main)
|
||||
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Local negative checks for TLS identity, secret scope, ACL and session storage."""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
from client import Client, check
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
PKI=ROOT/'.local/pki'
|
||||
|
||||
|
||||
def probe(mode):
|
||||
p=subprocess.run(['docker','compose','run','--rm','-T','--no-deps','tls-probe',
|
||||
'--url','https://api1:8443','--mode',mode],cwd=ROOT,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
|
||||
if p.returncode:
|
||||
raise AssertionError('internal mTLS probe '+mode+' failed: '+p.stdout[-800:])
|
||||
print(p.stdout.strip())
|
||||
|
||||
|
||||
def psql(query):
|
||||
return subprocess.check_output(['docker','compose','exec','-T','postgres','psql','-U','postgres','-d','messenger','-At','-c',query],cwd=ROOT,text=True).strip()
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('--base-url',default='https://localhost:8443')
|
||||
parser.add_argument('--ca-file',default=str(PKI/'external-ca.crt'))
|
||||
args=parser.parse_args()
|
||||
c=Client(args.base_url,args.ca_file)
|
||||
c.call('GET','/health/ready',schema='Health')
|
||||
print('PASS: external HTTPS endpoint is trusted')
|
||||
subprocess.run(['docker','compose','build','tls-probe'],cwd=ROOT,check=True,
|
||||
stdout=subprocess.DEVNULL,stderr=subprocess.STDOUT)
|
||||
for mode in ('trusted','no-cert','untrusted-ca','wrong-identity'):
|
||||
probe(mode)
|
||||
|
||||
# The login rate table is shared in PostgreSQL, so both API replicas enforce it.
|
||||
username='rate_'+uuid.uuid4().hex
|
||||
auth='Basic '+base64.b64encode((username+':wrong-pass').encode()).decode()
|
||||
for _ in range(5): c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':auth})
|
||||
limited=c.call('POST','/api/v1/auth/sessions',429,headers={'Authorization':auth})
|
||||
check(int(limited['headers'].get('Retry-After','0'))>=1,'429 response lacks Retry-After')
|
||||
print('PASS: login limiter returns 429 with Retry-After across shared database')
|
||||
|
||||
user=c.user('hash')
|
||||
stored=psql("SELECT password FROM users WHERE username='"+user['registration']['username']+"'")
|
||||
check(bool(re.fullmatch(r'\$argon2id\$v=19\$m=19456,t=2,p=1\$[^$]+\$[^$]+',stored)), 'password is not Argon2id m=19456,t=2,p=1')
|
||||
token_hash=hashlib.sha256(user['token'].encode()).hexdigest()
|
||||
check(psql("SELECT count(*) FROM sessions WHERE token='"+token_hash+"'")=='1','session token hash is not stored')
|
||||
check(psql("SELECT count(*) FROM sessions WHERE token='"+user['token']+"'")=='0','raw session token was stored')
|
||||
expired=c.user('expiry')
|
||||
expired_hash=hashlib.sha256(expired['token'].encode()).hexdigest()
|
||||
check(psql("UPDATE sessions SET expires_at=now()-interval '1 second' WHERE token='"+expired_hash+"'")=='UPDATE 1','could not prepare expired-session probe')
|
||||
c.call('GET','/api/v1/users/me',401,actor=expired)
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=user)
|
||||
c.call('GET','/api/v1/users/me',401,actor=user)
|
||||
print('PASS: password parameters, hashed session tokens, expiry and logout')
|
||||
|
||||
for service in ('api1','worker'):
|
||||
r=subprocess.run(['docker','compose','exec','-T',service,'python','tests/component_security.py'],cwd=ROOT,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
|
||||
if r.returncode: raise AssertionError(service+' component security checks failed: '+r.stdout[-1200:])
|
||||
print(r.stdout.strip())
|
||||
|
||||
# API listeners are private and contain no database/S3/broker app credentials in container env.
|
||||
docs=[json.loads(line) for line in subprocess.check_output(['docker','compose','ps','--format','json'],cwd=ROOT,text=True).splitlines() if line.strip()]
|
||||
for service in ('api1','api2'):
|
||||
doc=next(x for x in docs if x.get('Service')==service)
|
||||
check(not doc.get('Publishers'),service+' published a direct API port')
|
||||
cid=doc['ID']
|
||||
config=json.loads(subprocess.check_output(['docker','inspect',cid],cwd=ROOT,text=True))[0]
|
||||
check(config['Config']['User']=='10001:10001',service+' is not non-root')
|
||||
host=config['HostConfig']
|
||||
check(not host.get('Privileged') and host.get('ReadonlyRootfs'),service+' container hardening is missing')
|
||||
check('ALL' in (host.get('CapDrop') or []),service+' did not drop capabilities')
|
||||
env=config['Config'].get('Env',[])
|
||||
check(not any(item.startswith(prefix+'=') for item in env for prefix in ('DATABASE_URL','S3_ACCESS_KEY','S3_SECRET_KEY','BROKER_URL','BAO_TOKEN')),
|
||||
service+' contains a runtime credential in its environment')
|
||||
check(not any('/var/run/docker.sock' in (item.get('Source','')+' '+item.get('Destination','')) for item in (config.get('Mounts') or [])),service+' has Docker socket access')
|
||||
print('PASS: API ports are private; non-root/read-only/cap-drop; no runtime credentials or Docker socket')
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Check readiness and upload when S3 is unavailable; always restore S3."""
|
||||
import subprocess
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
from client import Client, arguments, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Storage failure')
|
||||
c = Client(args.base_url,args.ca_file)
|
||||
alice,bob,eve,chat = c.bootstrap()
|
||||
data = open('tests/fixtures/sample.png','rb').read()
|
||||
try:
|
||||
subprocess.run(['docker','compose','stop','-t','2','s3'],check=True)
|
||||
for path, probe in [('/health/ready', {'expected':503}),
|
||||
('/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png', {
|
||||
'method':'POST','body_b64':base64.b64encode(data).decode(),
|
||||
'headers':{'Content-Type':'image/png','Authorization':'Bearer '+alice['token']},'expected':503})]:
|
||||
cmd=['docker','compose','run','--rm','-T','--no-deps','tls-probe','--url','https://api1:8443',
|
||||
'--mode','trusted','--path',path]
|
||||
subprocess.run(cmd,input=json.dumps(probe),text=True,check=True)
|
||||
print('PASS: S3 down returns 503 for readiness and upload')
|
||||
finally:
|
||||
subprocess.run(['docker','compose','start','s3'],check=True)
|
||||
for _ in range(60):
|
||||
try:
|
||||
c.call('GET','/health/ready')
|
||||
print('PASS: S3 restored')
|
||||
break
|
||||
except Exception:
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise AssertionError('S3 did not recover')
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-shot in-network mTLS probe used by security_runtime.py."""
|
||||
import argparse
|
||||
import base64
|
||||
import http.client
|
||||
import json
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
p=argparse.ArgumentParser()
|
||||
p.add_argument('--url',required=True)
|
||||
p.add_argument('--path',default='/health/ready')
|
||||
p.add_argument('--mode',choices=('trusted','no-cert','untrusted-ca','wrong-identity'),required=True)
|
||||
a=p.parse_args()
|
||||
ctx=ssl.create_default_context(cafile='/run/certs/service-ca.crt')
|
||||
if a.mode=='trusted':
|
||||
ctx.load_cert_chain('/run/certs/lb-client.crt','/run/certs/lb-client.key')
|
||||
elif a.mode=='untrusted-ca':
|
||||
ctx.load_cert_chain('/run/certs/untrusted-client.crt','/run/certs/untrusted-client.key')
|
||||
elif a.mode=='wrong-identity':
|
||||
ctx.load_cert_chain('/run/certs/foreign-client.crt','/run/certs/foreign-client.key')
|
||||
try:
|
||||
raw=sys.stdin.read() if not sys.stdin.isatty() else ''
|
||||
probe=json.loads(raw) if raw.strip() else {}
|
||||
headers=probe.get('headers',{})
|
||||
body=base64.b64decode(probe['body_b64']) if probe.get('body_b64') else None
|
||||
request=urllib.request.Request(a.url.rstrip('/')+a.path,data=body,headers=headers,method=probe.get('method','GET'))
|
||||
with urllib.request.urlopen(request,context=ctx,timeout=5) as response:
|
||||
status=response.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
status=exc.code
|
||||
except http.client.RemoteDisconnected:
|
||||
if a.mode in ('no-cert','untrusted-ca'):
|
||||
print('PASS: API rejected '+a.mode+' during TLS handshake')
|
||||
raise SystemExit(0)
|
||||
raise SystemExit('FAIL: unexpected TLS peer disconnect')
|
||||
except urllib.error.URLError as exc:
|
||||
if a.mode in ('no-cert','untrusted-ca') and isinstance(exc.reason,(ssl.SSLError,ConnectionResetError,http.client.RemoteDisconnected)):
|
||||
print('PASS: API rejected '+a.mode+' during TLS handshake')
|
||||
raise SystemExit(0)
|
||||
raise SystemExit('FAIL: unexpected TLS probe error: '+type(exc.reason).__name__)
|
||||
expected=probe.get('expected',200) if 'probe' in locals() else 200
|
||||
if a.mode=='trusted' and status==expected:
|
||||
print('PASS: API returned expected status '+str(status)+' for the allowlisted LB identity')
|
||||
elif a.mode=='wrong-identity' and status==403:
|
||||
print('PASS: API rejected a CA-signed certificate with the wrong SAN identity')
|
||||
else:
|
||||
raise SystemExit('FAIL: '+a.mode+' probe returned HTTP '+str(status))
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Demonstrate durable handoff while the worker is stopped and redelivery safety."""
|
||||
import subprocess
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(['docker','compose',*args],check=True,stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def main():
|
||||
args=arguments('Durable async image processing acceptance flow')
|
||||
c=Client(args.base_url,args.ca_file,timeout=10)
|
||||
alice,bob,eve,chat=c.bootstrap()
|
||||
compose('stop','worker')
|
||||
try:
|
||||
att,original=c.attachment(alice,chat)
|
||||
check(att['status']=='queued','upload should be durably queued while worker is stopped')
|
||||
c.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=bob)
|
||||
msg=c.message(alice,chat,'',attachments=[att['id']])['json']
|
||||
check(msg['attachment_ids']==[att['id']],'queued attachment could not be linked to message')
|
||||
compose('restart','broker','api1','api2')
|
||||
compose('up','-d','worker')
|
||||
ready=c.wait_ready(bob,att,wait_seconds=60)
|
||||
check(ready['status']=='ready' and len(ready['variants'])==1,'worker did not publish one ready thumbnail')
|
||||
original_read=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)
|
||||
check(original_read['bytes']==original,'original changed during async processing')
|
||||
thumb=ready['variants'][0]
|
||||
content=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=thumbnail',actor=bob)
|
||||
check(content['bytes'] and len(content['bytes'])==thumb['size_bytes'],'thumbnail bytes do not match metadata')
|
||||
# Redeliver the exact logical job. The ready state and deterministic object
|
||||
# keys make this a no-op; it cannot create another variant.
|
||||
code="import psycopg,os; from app.worker import publish; c=psycopg.connect(os.environ['DATABASE_URL']); p=c.execute('SELECT payload FROM attachment_jobs WHERE attachment_id=%s',(\""+att['id']+"\",)).fetchone()[0]; publish(p); publish(p); c.close()"
|
||||
subprocess.run(['docker','compose','exec','-T','worker','python','-c',code],check=True,stdout=subprocess.DEVNULL)
|
||||
check(c.wait_ready(bob,att)['variants']==ready['variants'],'duplicate delivery changed ready result')
|
||||
print('PASS: stopped-worker upload returned 202, survived API/broker restart, and reached ready')
|
||||
print('PASS: original preserved; repeated job delivery produced one identical thumbnail')
|
||||
finally:
|
||||
compose('up','-d','worker')
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user