forked from mtusi2026/mtusi2026lab7
lab 7
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
"""Replay concrete reviewer cases through real HTTP and controlled dependency freezes."""
|
||||
import io
|
||||
import json
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
import zlib
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True,stderr=subprocess.DEVNULL).strip()
|
||||
|
||||
|
||||
def png(width,height):
|
||||
# Complete PNG, including all scanlines and CRCs, without allocating a bitmap.
|
||||
def chunk(kind,data):
|
||||
return struct.pack('>I',len(data))+kind+data+struct.pack('>I',zlib.crc32(kind+data))
|
||||
compressor=zlib.compressobj()
|
||||
packed=io.BytesIO()
|
||||
row=b'\0'*(width+1)
|
||||
for _ in range(height): packed.write(compressor.compress(row))
|
||||
packed.write(compressor.flush())
|
||||
return (b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,height,8,0,0,0,0))
|
||||
+chunk(b'IDAT',packed.getvalue())+chunk(b'IEND',b''))
|
||||
|
||||
|
||||
DIRECT='''import json,sys,time,urllib.request,urllib.error
|
||||
p=json.load(sys.stdin);h={}
|
||||
if p.get('token'):h['Authorization']='Bearer '+p['token']
|
||||
r=urllib.request.Request('http://127.0.0.1:8080'+p['path'],headers=h)
|
||||
t=time.monotonic()
|
||||
try:r=urllib.request.urlopen(r,timeout=10)
|
||||
except urllib.error.HTTPError as e:r=e
|
||||
with r:
|
||||
data=json.load(r)
|
||||
if r.code>=400:
|
||||
assert data['error']['request_id']==r.headers['X-Request-Id']
|
||||
assert data['error']['code']=='unavailable'
|
||||
print(json.dumps({'status':r.code,'seconds':round(time.monotonic()-t,4),
|
||||
'request_id_present':bool(r.headers.get('X-Request-Id')),'instance_id_present':bool(r.headers.get('X-Instance-Id'))}))
|
||||
'''
|
||||
LOCKER='''import asyncio,sys,asyncpg
|
||||
from src.core.settings import settings
|
||||
async def f():
|
||||
c=await asyncpg.connect(settings.database_url.get_secret_value())
|
||||
await c.execute('BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE')
|
||||
print('LOCKED',flush=True)
|
||||
await asyncio.to_thread(sys.stdin.readline)
|
||||
await c.execute('ROLLBACK');await c.close()
|
||||
asyncio.run(f())
|
||||
'''
|
||||
PENDING='''import asyncio,asyncpg
|
||||
from src.core.settings import settings
|
||||
async def f():
|
||||
c=await asyncpg.connect(settings.database_url.get_secret_value())
|
||||
print(await c.fetchval("SELECT count(*) FROM pg_stat_activity WHERE wait_event_type='Lock' AND query LIKE '%FROM messages%'"))
|
||||
await c.close()
|
||||
asyncio.run(f())
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
args=arguments('API reviewer regression scenarios')
|
||||
c=Client(args.base_url,args.ca_file,timeout=15)
|
||||
alice,bob,_,chat=c.bootstrap()
|
||||
history='/api/v1/chats/'+chat['id']+'/messages'
|
||||
c.message(alice,chat,'Контроль до отказов')
|
||||
results=[]
|
||||
for name in ('review123\n','review123\r','review123\x00','review123\t'):
|
||||
c.call('POST','/api/v1/users',400,body={'username':name,'display_name':'Review','password':'valid-password-123'})
|
||||
results.append({'case':'username_control_characters','result':'PASS','status':400})
|
||||
data=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
upload='/api/v1/chats/'+chat['id']+'/attachments'
|
||||
for label,filename,payload,mime,status in [
|
||||
('truncated_png','sample.png',data[:-12],'image/png',415),
|
||||
('header_only_png','sample.png',data[:33],'image/png',415),
|
||||
('mismatched_mime','sample.png',data,'image/jpeg',415),
|
||||
('DEL_filename','a%7F.png',data,'image/png',400),
|
||||
('missing_filename',None,data,'image/png',400),
|
||||
]:
|
||||
c.call('POST',upload+('' if filename is None else '?filename='+filename),status,
|
||||
actor=alice,raw=payload,headers={'Content-Type':mime})
|
||||
results.append({'case':label,'result':'PASS','status':status})
|
||||
for width,height,status in ((8000,5000,202),(8000,5001,413),(20000,10000,413)):
|
||||
payload=png(width,height)
|
||||
reply=c.call('POST',upload+'?filename=dimensions.png',status,actor=alice,raw=payload,
|
||||
headers={'Content-Type':'image/png'},schema='Attachment' if status==202 else None)
|
||||
if status==202:
|
||||
c.wait_ready(alice, reply['json'])
|
||||
check(c.call('GET','/api/v1/attachments/'+reply['json']['id']+'/content',actor=bob)['bytes']==payload,
|
||||
'40 MP original changed')
|
||||
results.append({'case':'pixels','dimensions':[width,height],'result':'PASS','status':status})
|
||||
api=compose('ps','-q','api').split()[0]
|
||||
# Actual application credentials must not permit creating unrelated buckets.
|
||||
code='''from src.core.storage import get_storage
|
||||
from minio.error import S3Error
|
||||
import uuid
|
||||
s=get_storage();b='forbidden-'+uuid.uuid4().hex
|
||||
try:s.make_bucket(b)
|
||||
except S3Error as e:assert e.code=='AccessDenied';print('PASS')
|
||||
else:s.remove_bucket(b);raise AssertionError('API can create foreign buckets')
|
||||
'''
|
||||
check(subprocess.check_output(['docker','exec',api,'python','-c',code],text=True).strip()=='PASS',
|
||||
'API has excessive S3 rights')
|
||||
results.append({'case':'API_cannot_create_foreign_bucket','result':'PASS'})
|
||||
def direct(path,token=None):
|
||||
reply=subprocess.run(['docker','exec','-i',api,'python','-c',DIRECT],
|
||||
input=json.dumps({'path':path,'token':token}),text=True,capture_output=True,timeout=13,check=True)
|
||||
return json.loads(reply.stdout)
|
||||
transfer_code="""import asyncio,http.client,json,sys,time
|
||||
from sqlalchemy import func,select
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
from src.core.db.session import create_engine
|
||||
from src.core.db.models import Attachment,UploadIntent
|
||||
p=json.load(sys.stdin)
|
||||
async def counts():
|
||||
e=create_engine();f=async_sessionmaker(e)
|
||||
try:
|
||||
async with f() as s:
|
||||
return [await s.scalar(select(func.count()).select_from(m)) for m in (Attachment,UploadIntent)]
|
||||
finally:await e.dispose()
|
||||
before=asyncio.run(counts())
|
||||
c=http.client.HTTPConnection('127.0.0.1',8080,timeout=8)
|
||||
c.putrequest('POST',p['path'])
|
||||
c.putheader('Authorization','Bearer '+p['token'])
|
||||
c.putheader('Content-Type','image/png');c.putheader('Content-Length','1000');c.endheaders()
|
||||
c.send(b'\\x89PNG\\r\\n\\x1a\\nshort');c.close();time.sleep(.3)
|
||||
assert before==asyncio.run(counts()),'interrupted client created durable state'
|
||||
c=http.client.HTTPConnection('127.0.0.1',8080,timeout=8)
|
||||
c.request('POST',p['path'],body=(b'x'*65536 for _ in range(161)),
|
||||
headers={'Authorization':'Bearer '+p['token'],'Content-Type':'image/png'},encode_chunked=True)
|
||||
r=c.getresponse();body=json.loads(r.read())
|
||||
assert r.status==413 and body['error']['code']=='payload_too_large'
|
||||
assert body['error']['request_id']==r.getheader('X-Request-Id')
|
||||
c.close();assert before==asyncio.run(counts()),'oversized chunked body created durable state'
|
||||
print('PASS')
|
||||
"""
|
||||
transfer=subprocess.run(['docker','exec','-i',api,'python','-c',transfer_code],
|
||||
input=json.dumps({'path':upload+'?filename=interrupted.png','token':alice['token']}),
|
||||
text=True,capture_output=True,timeout=20,check=True)
|
||||
check(transfer.stdout.strip()=='PASS','transfer limits failed')
|
||||
results.append({'case':'client_abort_and_oversized_chunked_body','result':'PASS',
|
||||
'oversized_status':413,'durable_state_unchanged':True})
|
||||
direct(history,alice['token'])
|
||||
# Start an actual history SELECT, hold it on a table lock, then freeze PG.
|
||||
locker=subprocess.Popen(['docker','exec','-i',api,'python','-u','-c',LOCKER],
|
||||
stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
|
||||
check(locker.stdout.readline().strip()=='LOCKED','test table lock was not acquired')
|
||||
paused=False
|
||||
pool=ThreadPoolExecutor(max_workers=2)
|
||||
query=pool.submit(direct,history,alice['token'])
|
||||
try:
|
||||
deadline=time.monotonic()+2
|
||||
while True:
|
||||
pending=int(subprocess.check_output(['docker','exec',api,'python','-c',PENDING],text=True))
|
||||
if pending:break
|
||||
check(time.monotonic()<deadline,'history did not enter SQL before the freeze')
|
||||
time.sleep(.02)
|
||||
compose('pause','postgres');paused=True
|
||||
ready=pool.submit(direct,'/health/ready')
|
||||
history_result=query.result(timeout=8)
|
||||
readiness_result=ready.result(timeout=8)
|
||||
for result in (history_result,readiness_result):
|
||||
check(result['status']==503 and result['seconds']<7,'frozen PostgreSQL exceeded HTTP budget')
|
||||
check(result['request_id_present'] and result['instance_id_present'],'missing response headers')
|
||||
results.append({'case':'PostgreSQL_frozen_after_SQL_started','result':'PASS',
|
||||
'history':history_result,'readiness':readiness_result})
|
||||
finally:
|
||||
if paused:compose('unpause','postgres')
|
||||
try:locker.stdin.write('release\n');locker.stdin.flush()
|
||||
except BrokenPipeError:pass
|
||||
locker.wait(timeout=8)
|
||||
pool.shutdown(wait=True)
|
||||
deadline=time.monotonic()+12
|
||||
while True:
|
||||
try:
|
||||
response=direct(history,alice['token'])
|
||||
check(response['status']==200,'history did not recover')
|
||||
check(direct('/health/ready')['status']==200,'readiness did not recover')
|
||||
# Wait for HAProxy's rise checks as well as direct API recovery.
|
||||
c.call('GET', '/health/live', schema='Health')
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
c.call('GET', history, actor=alice, schema='MessagePage')
|
||||
break
|
||||
except Exception:
|
||||
if time.monotonic()>deadline:raise
|
||||
time.sleep(.2)
|
||||
results.append({'case':'PostgreSQL_resume_without_API_restart','result':'PASS'})
|
||||
print(json.dumps({'result':'PASS','checks':results},ensure_ascii=False,indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Lab4 black-box checks against the running Compose stack."""
|
||||
import hashlib
|
||||
import io
|
||||
import struct
|
||||
import zlib
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Attachment originals, ACL, validation and message limits')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id']
|
||||
content = (Path(__file__).parent / 'fixtures/sample.png').read_bytes()
|
||||
|
||||
def upload(data=content, name='photo.png', mime='image/png', status=202, actor=alice):
|
||||
return c.call('POST', path + '/attachments?filename=' + name, status,
|
||||
actor=actor, raw=data, headers={'Content-Type': mime},
|
||||
schema='Attachment' if status == 202 else None)['json']
|
||||
|
||||
first = upload()
|
||||
second = upload() # Same display name must not overwrite the first object.
|
||||
check(first['id'] != second['id'], 'same filename overwrote attachment')
|
||||
jpg = io.BytesIO()
|
||||
Image.new('RGB', (31, 17), 'red').save(jpg, format='JPEG')
|
||||
jpeg = upload(jpg.getvalue(), 'photo.jpg', 'image/jpeg')
|
||||
for att, original in [(first, content), (second, content), (jpeg, jpg.getvalue())]:
|
||||
check(att['sha256'] == hashlib.sha256(original).hexdigest(), 'incorrect digest')
|
||||
att = c.wait_ready(alice, att)
|
||||
check({v['name'] for v in att['variants']} == {'thumbnail', 'crop', 'optimized'}, 'incorrect ready metadata')
|
||||
for suffix in ('', '/content'):
|
||||
c.call('GET', '/api/v1/attachments/' + att['id'] + suffix, 404, actor=eve)
|
||||
downloaded = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)
|
||||
check(downloaded['bytes'] == original, 'original changed')
|
||||
|
||||
ids = [first['id'], second['id'], jpeg['id']]
|
||||
key = uuid.uuid4().hex
|
||||
message = c.message(alice, chat, '', key=key, attachments=ids)['json']
|
||||
check(message['attachment_ids'] == ids, 'attachment order lost')
|
||||
check(c.message(alice, chat, '', key=key, attachments=ids)['json'] == message,
|
||||
'idempotency replay changed message')
|
||||
c.call('POST', path + '/messages', 409, actor=alice,
|
||||
body={'text': '', 'attachment_ids': ids[:1]}, headers={'Idempotency-Key': key})
|
||||
page = c.call('GET', path + '/messages', actor=bob, schema='MessagePage')['json']
|
||||
check(any(m == message for m in page['items']), 'history lost attachments')
|
||||
# The contract permits referencing the same accessible chat attachment again.
|
||||
c.message(bob, chat, 'same image', attachments=[first['id']])
|
||||
|
||||
for body in ({'text': '', 'attachment_ids': []},
|
||||
{'text': '', 'attachment_ids': [first['id']] * 2},
|
||||
{'text': '', 'attachment_ids': [str(uuid.uuid4()) for _ in range(11)]}):
|
||||
c.call('POST', path + '/messages', 400, actor=alice, body=body,
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
c.call('POST', path + '/messages', 404, actor=alice,
|
||||
body={'text': '', 'attachment_ids': [str(uuid.uuid4())]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
other = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]},
|
||||
schema='Chat')['json']
|
||||
c.call('POST', '/api/v1/chats/' + other['id'] + '/messages', 404, actor=alice,
|
||||
body={'text': '', 'attachment_ids': ids},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
upload(actor=eve, status=404)
|
||||
upload(name='..%2Fphoto.png', status=400)
|
||||
upload(name='a%00b.png', status=400)
|
||||
upload(data=b'not a PNG', status=415)
|
||||
upload(data=content[:30], status=415)
|
||||
upload(mime='image/jpeg', status=415)
|
||||
upload(mime='application/octet-stream', status=415)
|
||||
# Oversized dimensions with a valid PNG header; no huge bitmap allocation.
|
||||
header = struct.pack('>IIBBBBB', 10000, 5000, 8, 2, 0, 0, 0)
|
||||
bomb = (content[:8] + struct.pack('>I', len(header)) + b'IHDR' + header
|
||||
+ struct.pack('>I', zlib.crc32(b'IHDR' + header)) + content[33:])
|
||||
upload(data=bomb, status=413)
|
||||
upload(data=b'x' * (10485760 + 1), status=413)
|
||||
c.call('POST', path + '/attachments?filename=a.png', 401,
|
||||
raw=content, headers={'Content-Type': 'image/png'})
|
||||
|
||||
# Exactly 10 distinct attachments must remain valid, including after reading history.
|
||||
ten = ids + [upload()['id'] for _ in range(7)]
|
||||
check(len(c.message(alice, chat, '', attachments=ten)['json']['attachment_ids']) == 10,
|
||||
'10 attachments rejected')
|
||||
replay_key = uuid.uuid4().hex
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
responses = list(pool.map(lambda _: Client(args.base_url, args.ca_file).message(
|
||||
alice, chat, 'Concurrent image', key=replay_key, attachments=ids
|
||||
), range(8)))
|
||||
check(all(r['json'] == responses[0]['json'] for r in responses),
|
||||
'concurrent attachment retries differ')
|
||||
print('PASS: PNG/JPEG bytes, metadata, ACL, chat boundaries, limits and idempotency')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check actual containers, restricted mounts and telemetry without printing secrets."""
|
||||
|
||||
# ruff: noqa: E402 -- repository scripts are imported after setting their path.
|
||||
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
from client import Client
|
||||
from securitylib import LOCAL, OPERATOR, compose, request, root_token, tls
|
||||
|
||||
|
||||
def main():
|
||||
rows = []
|
||||
|
||||
def ok(check, **values):
|
||||
rows.append({"check": check, "result": "PASS", **values})
|
||||
|
||||
containers = compose("ps", "-q", capture=True).split()
|
||||
details = json.loads(subprocess.check_output(["docker", "inspect", *containers], text=True))
|
||||
for item in details:
|
||||
role = item["Config"]["Labels"]["com.docker.compose.service"]
|
||||
config = item["HostConfig"]
|
||||
assert not config["Privileged"] and config["NetworkMode"] != "host"
|
||||
assert all("docker.sock" not in mount["Source"] for mount in item["Mounts"])
|
||||
assert "no-new-privileges:true" in config["SecurityOpt"]
|
||||
assert config["Memory"] > 0 and config["NanoCpus"] > 0
|
||||
for binding in (config.get("PortBindings") or {}).values():
|
||||
assert all(entry["HostIp"] == "127.0.0.1" for entry in binding)
|
||||
if role != "postgres":
|
||||
assert config["ReadonlyRootfs"] and "ALL" in config["CapDrop"]
|
||||
if role in ["api", "worker", "dispatcher", "reconciler"]:
|
||||
assert item["Config"]["User"] == "10001:10001"
|
||||
assert config["ReadonlyRootfs"] and "ALL" in config["CapDrop"]
|
||||
assert all("/operator" not in mount["Source"] for mount in item["Mounts"])
|
||||
env = dict(value.split("=", 1) for value in item["Config"]["Env"])
|
||||
assert not any(
|
||||
name in env
|
||||
for name in [
|
||||
"DATABASE_URL",
|
||||
"ADMIN_PASSWORD",
|
||||
"MINIO_ROOT_PASSWORD",
|
||||
"BAO_TOKEN",
|
||||
"S3_SECRET_ACCESS_KEY",
|
||||
]
|
||||
)
|
||||
ok("container-hardening:" + role)
|
||||
c = Client("https://localhost:8443", str(LOCAL / "trust/ca.crt"))
|
||||
actor = c.user("leak")
|
||||
response = c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
traceid = response["headers"]["X-Trace-Id"]
|
||||
forbidden = []
|
||||
values = json.loads((OPERATOR / "credentials.json").read_text())
|
||||
forbidden.extend(values.values())
|
||||
forbidden.extend([actor["token"], actor["registration"]["password"], root_token()])
|
||||
for role in ["api", "worker", "dispatcher", "reconciler"]:
|
||||
data = request("secret/data/messenger/" + role, token=root_token())["data"]["data"]
|
||||
for name, value in data.items():
|
||||
if "PASSWORD" in name or "SECRET_ACCESS_KEY" in name:
|
||||
forbidden.append(value)
|
||||
if name.endswith("_URL"):
|
||||
password = urllib.parse.urlsplit(value).password
|
||||
if password:
|
||||
forbidden.append(password)
|
||||
sources = {}
|
||||
sources["container-logs"] = subprocess.check_output(
|
||||
["docker", "compose", "logs", "--no-color"], cwd=ROOT, text=True, stderr=subprocess.DEVNULL
|
||||
)
|
||||
|
||||
def fetch(base, path):
|
||||
with urllib.request.urlopen(base + path, context=tls(), timeout=15) as response:
|
||||
return response.read().decode()
|
||||
|
||||
sources["metrics"] = fetch(
|
||||
"https://localhost:19090",
|
||||
"/api/v1/query?" + urllib.parse.urlencode({"query": "http_server_requests_total"}),
|
||||
)
|
||||
sources["logs"] = fetch(
|
||||
"https://localhost:13100",
|
||||
"/loki/api/v1/query_range?"
|
||||
+ urllib.parse.urlencode(
|
||||
{
|
||||
"query": '{service_name=~"messenger-.*"}',
|
||||
"limit": 200,
|
||||
"start": str(time.time_ns() - 120_000_000_000),
|
||||
}
|
||||
),
|
||||
)
|
||||
# Search includes real recent traces; specific trace may still be in the export buffer.
|
||||
sources["traces"] = fetch("https://localhost:13200", "/api/search?limit=20")
|
||||
for name, text in sources.items():
|
||||
assert not any(value and value in text for value in forbidden), "Secret found in " + name
|
||||
assert "-----BEGIN PRIVATE KEY-----" not in text
|
||||
ok("no-secrets:" + name)
|
||||
metrics = json.loads(sources["metrics"])["data"]["result"]
|
||||
assert metrics
|
||||
for series in metrics:
|
||||
assert not {
|
||||
"chat_id",
|
||||
"user_id",
|
||||
"message_id",
|
||||
"attachment_id",
|
||||
"request_id",
|
||||
"trace_id",
|
||||
}.intersection(series["metric"])
|
||||
ok("metric-labels-bounded")
|
||||
# Persist only safe counts and a synthetic trace id, not response bodies.
|
||||
assert json.loads(sources["logs"])["data"]["result"]
|
||||
assert json.loads(sources["traces"])["traces"]
|
||||
ok("live-telemetry-all-three-signals", sample_trace_id=traceid)
|
||||
admin = base64.b64encode(("admin:" + values["grafana"]).encode()).decode()
|
||||
for uid, path in [
|
||||
("prometheus", "/api/v1/query?query=up"),
|
||||
("loki", "/loki/api/v1/labels"),
|
||||
("tempo", "/api/search?limit=1"),
|
||||
]:
|
||||
req = urllib.request.Request(
|
||||
"https://localhost:13000/api/datasources/proxy/uid/" + uid + path,
|
||||
headers={"Authorization": "Basic " + admin},
|
||||
)
|
||||
with urllib.request.urlopen(req, context=tls(None), timeout=10) as response:
|
||||
data = json.load(response)
|
||||
assert response.status == 200
|
||||
ok("grafana-real-datasource-query:" + uid)
|
||||
|
||||
original = Path("/Users/andrejkamenskij/Downloads/mtusi2026lab7")
|
||||
if original.exists():
|
||||
count = 0
|
||||
for folder in ["tests", "contracts"]:
|
||||
for source in (original / folder).rglob("*"):
|
||||
if source.is_file() and "__pycache__" not in source.parts:
|
||||
relative = source.relative_to(original)
|
||||
# trust matrix is intentionally filled as required by assignment.
|
||||
if str(relative) == "contracts/trust-matrix.md":
|
||||
continue
|
||||
assert (ROOT / relative).read_bytes() == source.read_bytes(), str(relative)
|
||||
count += 1
|
||||
ok("public-tests-and-contracts-unchanged", files=count)
|
||||
(ROOT / "evidence/audit-summary.json").write_text(
|
||||
json.dumps({"checks": rows, "passed": len(rows)}, indent=2) + "\n"
|
||||
)
|
||||
print("PASS:", len(rows), "container/telemetry/public-file audit checks")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stop each exact API container under writes, preserving sessions and original files."""
|
||||
|
||||
# ruff: noqa: E402 -- repository scripts are imported after setting their path.
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
from client import Client, Failure
|
||||
from replicas import compose, containers, describe, instance_id, wait_ready
|
||||
from resilience import history
|
||||
|
||||
|
||||
def main():
|
||||
c = Client("https://localhost:8443", str(ROOT / ".local/trust/ca.crt"), timeout=2)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
attachment, content = c.attachment(alice, chat)
|
||||
c.wait_ready(alice, attachment)
|
||||
expected = [c.message(alice, chat, "Before failures")["json"]]
|
||||
targets = containers()
|
||||
assert len(targets) == 2
|
||||
results = []
|
||||
try:
|
||||
for container in targets:
|
||||
target = instance_id(container)
|
||||
env = {**os.environ, "TARGET_INSTANCE_ID": target}
|
||||
started = time.monotonic()
|
||||
process = subprocess.Popen(
|
||||
[str(ROOT / "scripts/stop-one.sh")],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
first = None
|
||||
failures = 0
|
||||
served = []
|
||||
success = 0
|
||||
key = uuid.uuid4().hex
|
||||
text = "During failure " + key
|
||||
while time.monotonic() - started < 15:
|
||||
assert process.poll() in (None, 0)
|
||||
try:
|
||||
response = c.message(alice, chat, text, key=key)
|
||||
expected.append(response["json"])
|
||||
success += 1
|
||||
if process.poll() == 0:
|
||||
if first is None:
|
||||
first = time.monotonic() - started
|
||||
served.append(response["headers"]["X-Instance-Id"])
|
||||
key = uuid.uuid4().hex
|
||||
text = "During failure " + key
|
||||
except Failure:
|
||||
failures += 1
|
||||
time.sleep(0.15)
|
||||
assert process.wait(timeout=1) == 0
|
||||
assert first is not None and first <= 10
|
||||
assert len(served) >= 5 and target not in served[-5:]
|
||||
assert not describe(container)["Running"]
|
||||
messages = history(c, bob, chat)
|
||||
assert len({x["id"] for x in messages}) == len(messages)
|
||||
assert len({x["text"] for x in messages}) == len(messages)
|
||||
assert all(x in messages for x in expected)
|
||||
assert (
|
||||
c.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob)[
|
||||
"bytes"
|
||||
]
|
||||
== content
|
||||
)
|
||||
results.append(
|
||||
{
|
||||
"container": container[:12],
|
||||
"target_instance": target,
|
||||
"successful_writes": success,
|
||||
"failed_attempts": failures,
|
||||
"first_recovery_seconds": round(first, 3),
|
||||
"result": "PASS",
|
||||
}
|
||||
)
|
||||
compose("start", "api")
|
||||
wait_ready(container)
|
||||
time.sleep(2)
|
||||
finally:
|
||||
compose("start", "api")
|
||||
(ROOT / "evidence/failover-summary.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"result": "PASS",
|
||||
"distinct_containers": len(results),
|
||||
"runs": len(results),
|
||||
"events": results,
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
print(
|
||||
"PASS: both exact API containers stopped under writes; sessions, messages and attachment preserved"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,150 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator-run rotation, expiry/revoke, sealed-store and restart recovery tests."""
|
||||
|
||||
# ruff: noqa: E402 -- repository scripts are imported after setting their path.
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
from client import Client
|
||||
from securitylib import LOCAL, OPERATOR, compose, request, root_token, tls
|
||||
|
||||
|
||||
def wait_ready(timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
"https://localhost:8443/health/ready", context=tls(None), timeout=3
|
||||
) as response:
|
||||
if response.status == 200:
|
||||
return
|
||||
except (OSError, urllib.error.URLError):
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise AssertionError("HTTPS did not recover")
|
||||
|
||||
|
||||
def worker_children():
|
||||
# PID 1 is supervisor (or tini); readiness checks the actual application child.
|
||||
code = "from pathlib import Path; print(sum(b'src.pipeline.worker' in p.read_bytes() and b'src.secure.runtime' not in p.read_bytes() for p in Path('/proc').glob('[0-9]*/cmdline')))"
|
||||
return int(compose("exec", "-T", "worker", "python", "-c", code, capture=True))
|
||||
|
||||
|
||||
def main():
|
||||
rows = []
|
||||
started = time.monotonic()
|
||||
subprocess.run([sys.executable, "scripts/lab7.py", "rotate-secret"], cwd=ROOT, check=True)
|
||||
record = json.loads((OPERATOR / "last-worker-rotation.json").read_text())
|
||||
code = """import asyncio,json,sys,asyncpg
|
||||
from src.secure.transport import context
|
||||
async def main():
|
||||
x=json.load(sys.stdin)
|
||||
try:c=await asyncpg.connect(x['url'],ssl=context(),direct_tls=True,timeout=3)
|
||||
except asyncpg.InvalidAuthorizationSpecificationError:print('OLD_DENIED');return
|
||||
else:await c.close();raise AssertionError('Old DB credential still accepted')
|
||||
asyncio.run(main())"""
|
||||
result = subprocess.check_output(
|
||||
["docker", "compose", "run", "--rm", "--no-deps", "-T", "migration", "python", "-c", code],
|
||||
input=json.dumps({"url": record["old_url"]}),
|
||||
text=True,
|
||||
cwd=ROOT,
|
||||
)
|
||||
assert "OLD_DENIED" in result
|
||||
rows.append(
|
||||
{
|
||||
"check": "db-secret-rotation-old-login-denied",
|
||||
"result": "PASS",
|
||||
"seconds": round(time.monotonic() - started, 2),
|
||||
}
|
||||
)
|
||||
before = set(OPERATOR.glob("revoked-worker-*"))
|
||||
subprocess.run(
|
||||
[sys.executable, "scripts/lab7.py", "rotate-cert", "--role", "worker"], cwd=ROOT, check=True
|
||||
)
|
||||
archived = (set(OPERATOR.glob("revoked-worker-*")) - before).pop()
|
||||
# New TLS connection with revoked certificate must fail, not only an old socket.
|
||||
code = """import socket,ssl
|
||||
ctx=ssl.create_default_context(cafile='/run/trust/ca.crt')
|
||||
ctx.load_cert_chain('/run/revoked/service.crt','/run/revoked/service.key')
|
||||
try:
|
||||
with socket.create_connection(('broker',6379),timeout=3) as raw:
|
||||
with ctx.wrap_socket(raw,server_hostname='broker') as s:
|
||||
s.sendall(b'*1\\r\\n$4\\r\\nPING\\r\\n');data=s.recv(100)
|
||||
assert not data,'Revoked client certificate accepted'
|
||||
except (ssl.SSLError,ConnectionResetError):pass
|
||||
print('OLD_CERT_DENIED')"""
|
||||
result = compose(
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-v",
|
||||
str(archived) + ":/run/revoked:ro",
|
||||
"migration",
|
||||
"python",
|
||||
"-c",
|
||||
code,
|
||||
capture=True,
|
||||
)
|
||||
assert "OLD_CERT_DENIED" in result
|
||||
deadline = time.monotonic() + 60
|
||||
while worker_children() == 0 and time.monotonic() < deadline:
|
||||
time.sleep(1)
|
||||
assert worker_children() > 0
|
||||
rows.append({"check": "leaf-rotation-crl-old-cert-new-connection-denied", "result": "PASS"})
|
||||
wait_ready()
|
||||
c = Client("https://localhost:8443", str(LOCAL / "trust/ca.crt"))
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
attachment, _ = c.attachment(alice, chat)
|
||||
c.wait_ready(alice, attachment)
|
||||
rows.append({"check": "pipeline-after-credential-and-certificate-rotation", "result": "PASS"})
|
||||
# Sealed Bao: cached credentials can run only until last renewable token TTL.
|
||||
token = root_token()
|
||||
request("sys/seal", {}, token=token)
|
||||
try:
|
||||
deadline = time.monotonic() + 80
|
||||
while worker_children() > 0 and time.monotonic() < deadline:
|
||||
time.sleep(2)
|
||||
assert worker_children() == 0, "Worker kept running past its Bao access deadline"
|
||||
rows.append({"check": "sealed-bao-stops-worker-within-ttl", "result": "PASS"})
|
||||
api_stopped = False
|
||||
deadline = time.monotonic() + 25
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
"https://localhost:8443/health/ready", context=tls(None), timeout=4
|
||||
) as _response:
|
||||
pass
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 503
|
||||
api_stopped = True
|
||||
break
|
||||
time.sleep(1)
|
||||
assert api_stopped
|
||||
rows.append({"check": "sealed-bao-api-fails-closed", "result": "PASS"})
|
||||
finally:
|
||||
subprocess.run([sys.executable, "scripts/lab7.py", "unseal"], cwd=ROOT, check=True)
|
||||
wait_ready()
|
||||
deadline = time.monotonic() + 30
|
||||
while worker_children() == 0 and time.monotonic() < deadline:
|
||||
time.sleep(1)
|
||||
assert worker_children() > 0
|
||||
c.call("GET", "/api/v1/chats/" + chat["id"], actor=alice, schema="Chat")
|
||||
attachment, _ = c.attachment(alice, chat)
|
||||
c.wait_ready(alice, attachment)
|
||||
rows.append({"check": "unseal-recovers-api-session-and-pipeline", "result": "PASS"})
|
||||
(ROOT / "evidence/lifecycle-summary.json").write_text(
|
||||
json.dumps({"checks": rows, "passed": len(rows)}, indent=2) + "\n"
|
||||
)
|
||||
print("PASS:", len(rows), "lifecycle checks")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rotate a real MinIO principal, deny old credentials and finish a new job."""
|
||||
|
||||
# ruff: noqa: E402 -- repository scripts are imported after setting their path.
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
from client import Client
|
||||
from securitylib import LOCAL, OPERATOR
|
||||
|
||||
subprocess.run([sys.executable, "scripts/lab7.py", "rotate-s3"], cwd=ROOT, check=True)
|
||||
old = json.loads((OPERATOR / "last-s3-rotation.json").read_text())
|
||||
code = """import sys,json,urllib3
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
x=json.load(sys.stdin)
|
||||
s=Minio('minio:9000',secure=True,access_key=x['S3_WORKER_ACCESS_KEY_ID'],secret_key=x['S3_WORKER_SECRET_ACCESS_KEY'],http_client=urllib3.PoolManager(ca_certs='/run/trust/ca.crt',cert_reqs='CERT_REQUIRED'))
|
||||
try:s.bucket_exists('messenger-attachments')
|
||||
except S3Error as error:assert error.code in ('AccessDenied','InvalidAccessKeyId');print('OLD_S3_DENIED')
|
||||
else:raise AssertionError('Old S3 credential still works')"""
|
||||
result = subprocess.check_output(
|
||||
["docker", "compose", "run", "--rm", "--no-deps", "-T", "migration", "python", "-c", code],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
input=json.dumps(old),
|
||||
)
|
||||
assert "OLD_S3_DENIED" in result
|
||||
from lab7_lifecycle import wait_ready
|
||||
|
||||
wait_ready()
|
||||
c = Client("https://localhost:8443", str(LOCAL / "trust/ca.crt"))
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
attachment, content = c.attachment(alice, chat)
|
||||
c.wait_ready(alice, attachment)
|
||||
assert (
|
||||
c.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob)["bytes"]
|
||||
== content
|
||||
)
|
||||
(ROOT / "evidence/s3-rotation-summary.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"result": "PASS",
|
||||
"checks": [
|
||||
"new-s3-identity-applied",
|
||||
"old-s3-key-denied",
|
||||
"new-job-ready-original-preserved",
|
||||
],
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
print("PASS: S3 rotation, disabled old credential and new image ready")
|
||||
@@ -0,0 +1,510 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real TLS/identity, ACL, secret lifecycle and application regression checks."""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
ROWS = []
|
||||
|
||||
|
||||
def ok(name, **data):
|
||||
ROWS.append({"check": name, "result": "PASS", **data})
|
||||
|
||||
|
||||
def context(role=None):
|
||||
ctx = ssl.create_default_context(cafile="/run/trust/ca.crt")
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_3
|
||||
if role:
|
||||
directory = Path("/run/test-identities") / role
|
||||
ctx.load_cert_chain(directory / "service.crt", directory / "service.key")
|
||||
return ctx
|
||||
|
||||
|
||||
def bao(path, role="operator", body=None, token=None, method=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
req = urllib.request.Request(
|
||||
"https://openbao:8200/v1/" + path,
|
||||
headers=headers,
|
||||
data=json.dumps(body).encode() if body is not None else None,
|
||||
method=method,
|
||||
)
|
||||
with urllib.request.urlopen(req, context=context(role), timeout=4) as response:
|
||||
raw = response.read()
|
||||
return json.loads(raw) if raw else {}
|
||||
|
||||
|
||||
def forbidden(name, call, exception, *, code=None):
|
||||
try:
|
||||
call()
|
||||
except exception as error:
|
||||
if code is not None:
|
||||
assert error.code == code, name
|
||||
ok(name)
|
||||
else:
|
||||
raise AssertionError("Forbidden operation succeeded: " + name)
|
||||
|
||||
|
||||
def wire(host, port, role, data):
|
||||
with socket.create_connection((host, port), timeout=3) as raw:
|
||||
with context(role).wrap_socket(raw, server_hostname=host) as secured:
|
||||
secured.sendall(data)
|
||||
return secured.recv(4096)
|
||||
|
||||
|
||||
def denied_wire(host, port, role, data):
|
||||
try:
|
||||
result = wire(host, port, role, data)
|
||||
assert not result or result.startswith(b"HTTP/1.1 403"), (host, port, role)
|
||||
except ssl.SSLError:
|
||||
pass
|
||||
except ConnectionResetError:
|
||||
pass
|
||||
# Timeouts, DNS errors and connection refused deliberately do not count.
|
||||
ok(f"mtls-deny:{host}:{port}:{role or 'no-cert'}")
|
||||
|
||||
|
||||
async def internal():
|
||||
import asyncpg
|
||||
import redis
|
||||
import urllib3
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
|
||||
token = json.loads(Path("/run/operator/bao-init.json").read_text())["root_token"]
|
||||
secrets = {}
|
||||
for role in ["api", "worker", "dispatcher", "reconciler"]:
|
||||
auth = bao("auth/cert/login", role, {"name": role})["auth"]
|
||||
assert role in auth["policies"] and "root" not in auth["policies"]
|
||||
value = bao("secret/data/messenger/" + role, role, token=auth["client_token"])
|
||||
secrets[role] = value["data"]["data"]
|
||||
ok("bao-own-secret:" + role)
|
||||
other = "worker" if role == "api" else "api"
|
||||
forbidden(
|
||||
"bao-other-secret:" + role,
|
||||
lambda: bao("secret/data/messenger/" + other, role, token=auth["client_token"]),
|
||||
urllib.error.HTTPError,
|
||||
code=403,
|
||||
)
|
||||
forbidden(
|
||||
"bao-policy-write:" + role,
|
||||
lambda: bao(
|
||||
"sys/policies/acl/forbidden",
|
||||
role,
|
||||
{"policy": 'path "*" { capabilities=["sudo"] }'},
|
||||
token=auth["client_token"],
|
||||
),
|
||||
urllib.error.HTTPError,
|
||||
code=403,
|
||||
)
|
||||
renewal = bao("auth/token/renew-self", role, {}, token=auth["client_token"])
|
||||
assert renewal["auth"]["lease_duration"] > 0
|
||||
ok("bao-renew:" + role)
|
||||
# Full chain/identity rejection at each mandatory grade-4 mTLS boundary.
|
||||
for host, port, right, payload in [
|
||||
(
|
||||
"api",
|
||||
8443,
|
||||
"lb",
|
||||
b"GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n",
|
||||
),
|
||||
("broker", 6379, "worker", b"*1\r\n$4\r\nPING\r\n"),
|
||||
(
|
||||
"otel-collector",
|
||||
4318,
|
||||
"api",
|
||||
b"POST /v1/traces HTTP/1.1\r\nHost: otel-collector\r\nContent-Length: 0\r\nContent-Type: application/x-protobuf\r\nConnection: close\r\n\r\n",
|
||||
),
|
||||
]:
|
||||
result = wire(host, port, right, payload)
|
||||
assert result and (b"200" in result[:40] if host != "broker" else b"NOAUTH" in result)
|
||||
ok(f"mtls-allow:{host}:{port}:{right}")
|
||||
for wrong in [None, "intruder", "foreign", "expired"] + (
|
||||
["worker"] if host == "api" else []
|
||||
):
|
||||
denied_wire(host, port, wrong, payload)
|
||||
# Loopback-only plaintext listeners cannot be reached from another container.
|
||||
for host, port in [
|
||||
("api", 8080),
|
||||
("postgres", 15432),
|
||||
("redis", 16379),
|
||||
("broker", 16379),
|
||||
("otel-collector", 14318),
|
||||
("otel-collector", 18889),
|
||||
("loki", 13100),
|
||||
("tempo", 13200),
|
||||
("tempo", 14318),
|
||||
("prometheus", 19090),
|
||||
]:
|
||||
try:
|
||||
connection = socket.create_connection((host, port), timeout=2)
|
||||
except ConnectionRefusedError:
|
||||
ok(f"no-plaintext-bypass:{host}:{port}")
|
||||
else:
|
||||
connection.close()
|
||||
raise AssertionError("Plaintext listener is reachable: " + host)
|
||||
# Each remaining matrix row has a real positive TLS probe.
|
||||
for host, port, role, path in [
|
||||
("redis", 6379, "api", None),
|
||||
("postgres", 5432, "operator", None),
|
||||
("loki", 3100, "grafana", "/ready"),
|
||||
("tempo", 3200, "grafana", "/ready"),
|
||||
("prometheus", 9090, "grafana", "/-/ready"),
|
||||
("otel-collector", 8889, "prometheus", "/metrics"),
|
||||
("otel-collector", 8888, "prometheus", "/metrics"),
|
||||
("otel-collector", 13133, "operator", "/"),
|
||||
("tempo", 4318, "otel-collector", "/v1/traces"),
|
||||
]:
|
||||
if host == "postgres":
|
||||
connection = await asyncpg.connect(
|
||||
os.environ["DATABASE_URL"], ssl=context("operator"), direct_tls=True
|
||||
)
|
||||
assert await connection.fetchval("SELECT 1") == 1
|
||||
await connection.close()
|
||||
elif host == "redis":
|
||||
result = wire(host, port, role, b"*1\r\n$4\r\nPING\r\n")
|
||||
assert b"NOAUTH" in result
|
||||
else:
|
||||
data = f"GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n".encode()
|
||||
if host == "tempo" and port == 4318:
|
||||
data = b"POST /v1/traces HTTP/1.1\r\nHost: tempo\r\nContent-Length: 0\r\nContent-Type: application/x-protobuf\r\nConnection: close\r\n\r\n"
|
||||
result = wire(host, port, role, data)
|
||||
assert b"200" in result[:40] or b"503" in result[:40], host
|
||||
ok(f"tls-matrix:{host}:{port}:{role}")
|
||||
for role in ["worker", "dispatcher"]:
|
||||
connection = await asyncpg.connect(
|
||||
secrets[role]["DATABASE_URL"], ssl=context(role), direct_tls=True
|
||||
)
|
||||
try:
|
||||
await connection.fetch("SELECT id FROM attachment_jobs LIMIT 1")
|
||||
for name, sql in [
|
||||
("users", "SELECT password_hash FROM users LIMIT 1"),
|
||||
("ddl", "CREATE TABLE forbidden(id int)"),
|
||||
("roles", "CREATE ROLE forbidden"),
|
||||
]:
|
||||
try:
|
||||
await connection.execute(sql)
|
||||
except asyncpg.InsufficientPrivilegeError:
|
||||
ok(f"db-deny:{role}:{name}")
|
||||
else:
|
||||
raise AssertionError("Excessive DB privilege")
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
def redis_client(role, kind):
|
||||
url = secrets[role]["BROKER_URL" if kind == "broker" else "REDIS_URL"]
|
||||
folder = Path("/run/test-identities") / role
|
||||
return redis.Redis.from_url(
|
||||
url,
|
||||
ssl_ca_certs="/run/trust/ca.crt",
|
||||
ssl_certfile=str(folder / "service.crt"),
|
||||
ssl_keyfile=str(folder / "service.key"),
|
||||
ssl_check_hostname=True,
|
||||
socket_timeout=3,
|
||||
)
|
||||
|
||||
for role, kind in [("api", "sessions"), ("worker", "broker"), ("dispatcher", "broker")]:
|
||||
client = redis_client(role, kind)
|
||||
assert client.ping()
|
||||
forbidden(
|
||||
f"redis-admin-deny:{role}",
|
||||
lambda: client.config_get("*"),
|
||||
redis.exceptions.NoPermissionError,
|
||||
)
|
||||
forbidden(
|
||||
f"redis-prefix-deny:{role}",
|
||||
lambda: client.get("operator:secret"),
|
||||
redis.exceptions.NoPermissionError,
|
||||
)
|
||||
if role == "worker":
|
||||
forbidden(
|
||||
"consumer-cannot-publish",
|
||||
lambda: client.xadd("attachment-jobs-v1", {"job": "{}"}),
|
||||
redis.exceptions.NoPermissionError,
|
||||
)
|
||||
if role == "dispatcher":
|
||||
forbidden(
|
||||
"producer-cannot-consume",
|
||||
lambda: client.xreadgroup(
|
||||
"image-workers-v1", "probe", {"attachment-jobs-v1": ">"}, count=1
|
||||
),
|
||||
redis.exceptions.NoPermissionError,
|
||||
)
|
||||
client.close()
|
||||
for role, prefix in [("api", "S3"), ("worker", "S3_WORKER")]:
|
||||
data = secrets[role]
|
||||
client = Minio(
|
||||
"minio:9000",
|
||||
access_key=data[prefix + "_ACCESS_KEY_ID"],
|
||||
secret_key=data[prefix + "_SECRET_ACCESS_KEY"],
|
||||
secure=True,
|
||||
http_client=urllib3.PoolManager(
|
||||
ca_certs="/run/trust/ca.crt", cert_reqs="CERT_REQUIRED"
|
||||
),
|
||||
)
|
||||
assert client.bucket_exists("messenger-attachments")
|
||||
try:
|
||||
client.put_object("messenger-attachments", "admin/forbidden", io.BytesIO(b"x"), 1)
|
||||
except S3Error as error:
|
||||
assert error.code == "AccessDenied"
|
||||
ok("s3-prefix-deny:" + role)
|
||||
else:
|
||||
raise AssertionError("Forbidden S3 prefix allowed")
|
||||
if role == "api":
|
||||
try:
|
||||
client.put_object(
|
||||
"messenger-attachments", "variants/forbidden", io.BytesIO(b"x"), 1
|
||||
)
|
||||
except S3Error as error:
|
||||
assert error.code == "AccessDenied"
|
||||
ok("api-cannot-write-variants")
|
||||
else:
|
||||
raise AssertionError("API can overwrite worker variants")
|
||||
for host, port, path in [
|
||||
("loki", 3100, "/otlp/v1/logs"),
|
||||
("tempo", 3200, "/api/traces/anything"),
|
||||
("prometheus", 9090, "/api/v1/admin/tsdb/delete_series"),
|
||||
]:
|
||||
data = f"POST {path} HTTP/1.1\r\nHost: {host}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".encode()
|
||||
assert b"403" in wire(host, port, "grafana", data)[:40]
|
||||
ok("grafana-write-deny:" + host)
|
||||
short = bao(
|
||||
"auth/token/create",
|
||||
body={"policies": ["worker"], "ttl": "1s", "explicit_max_ttl": "1s"},
|
||||
token=token,
|
||||
)["auth"]["client_token"]
|
||||
time.sleep(1.5)
|
||||
forbidden(
|
||||
"bao-expired-token",
|
||||
lambda: bao("secret/data/messenger/worker", "worker", token=short),
|
||||
urllib.error.HTTPError,
|
||||
code=403,
|
||||
)
|
||||
short = bao("auth/cert/login", "worker", {"name": "worker"})["auth"]["client_token"]
|
||||
bao("auth/token/revoke", body={"token": short}, token=token)
|
||||
forbidden(
|
||||
"bao-revoked-token",
|
||||
lambda: bao("secret/data/messenger/worker", "worker", token=short),
|
||||
urllib.error.HTTPError,
|
||||
code=403,
|
||||
)
|
||||
print(json.dumps(ROWS))
|
||||
|
||||
|
||||
def host_checks():
|
||||
from client import Client
|
||||
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
from securitylib import LOCAL, compose
|
||||
|
||||
probe = [
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-v",
|
||||
str(ROOT / "tests") + ":/app/tests:ro",
|
||||
"-v",
|
||||
str(LOCAL / "identities") + ":/run/test-identities:ro",
|
||||
"-v",
|
||||
str(LOCAL / "operator") + ":/run/operator:ro",
|
||||
"migration",
|
||||
"python",
|
||||
"tests/lab7_security.py",
|
||||
"--internal",
|
||||
]
|
||||
result = compose(*probe, capture=True)
|
||||
ROWS.extend(json.loads(result.splitlines()[-1]))
|
||||
(ROOT / "evidence/security-internal-summary.json").write_text(
|
||||
json.dumps({"checks": ROWS, "passed": len(ROWS)}, indent=2) + "\n"
|
||||
)
|
||||
c = Client("https://localhost:8443", str(LOCAL / "trust/ca.crt"))
|
||||
with socket.create_connection(("localhost", 8443), timeout=3) as connection:
|
||||
try:
|
||||
tls_context = ssl.create_default_context(cafile=str(LOCAL / "trust/ca.crt"))
|
||||
tls_context.wrap_socket(connection, server_hostname="wrong.invalid")
|
||||
except ssl.SSLCertVerificationError:
|
||||
ok("external-wrong-hostname-denied")
|
||||
else:
|
||||
raise AssertionError("Wrong hostname accepted")
|
||||
actor = c.user("security")
|
||||
# Body forged user identity never replaces verified session identity.
|
||||
response = c.call(
|
||||
"GET",
|
||||
"/api/v1/users/me",
|
||||
actor=actor,
|
||||
headers={"X-User-Id": "00000000-0000-0000-0000-000000000000"},
|
||||
schema="User",
|
||||
)
|
||||
assert response["json"]["id"] == actor["id"]
|
||||
ok("bearer-not-x-user-id")
|
||||
username = actor["registration"]["username"]
|
||||
password = actor["registration"]["password"]
|
||||
dbcode = """import asyncio,os,json,sys
|
||||
import asyncpg
|
||||
from argon2 import PasswordHasher
|
||||
from src.secure.transport import context
|
||||
async def main():
|
||||
c=await asyncpg.connect(os.environ['DATABASE_URL'],ssl=context(),direct_tls=True)
|
||||
data=json.load(sys.stdin)
|
||||
if data['action']=='old':
|
||||
value=PasswordHasher(memory_cost=19456,time_cost=2,parallelism=1).hash(data['password'])
|
||||
await c.execute('UPDATE users SET password_hash=$1 WHERE username=$2',value,data['username'])
|
||||
else:
|
||||
value=await c.fetchval('SELECT password_hash FROM users WHERE username=$1',data['username'])
|
||||
assert not PasswordHasher(memory_cost=65536,time_cost=3,parallelism=4).check_needs_rehash(value)
|
||||
await c.close()
|
||||
asyncio.run(main())"""
|
||||
|
||||
def db(action):
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-T",
|
||||
"migration",
|
||||
"python",
|
||||
"-c",
|
||||
dbcode,
|
||||
],
|
||||
cwd=ROOT,
|
||||
input=json.dumps({"action": action, "username": username, "password": password}),
|
||||
text=True,
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
db("old")
|
||||
credentials = base64.b64encode((username + ":" + password).encode()).decode()
|
||||
c.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
201,
|
||||
headers={"Authorization": "Basic " + credentials},
|
||||
schema="Session",
|
||||
)
|
||||
db("check")
|
||||
ok("successful-login-rehash")
|
||||
# Account limit must hold while spoofed forwarding headers change.
|
||||
observed = set()
|
||||
blocked = False
|
||||
bad = base64.b64encode((username + ":WrongPassword123!").encode()).decode()
|
||||
for index in range(14):
|
||||
response = c.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
[401, 429],
|
||||
headers={
|
||||
"Authorization": "Basic " + bad,
|
||||
"X-Real-IP": f"198.51.100.{index}",
|
||||
"X-Forwarded-For": f"198.51.100.{index}",
|
||||
},
|
||||
)
|
||||
observed.add(response["headers"]["X-Instance-Id"])
|
||||
if response["status"] == 429:
|
||||
assert int(response["headers"]["Retry-After"]) > 0
|
||||
blocked = True
|
||||
assert blocked and len(observed) >= 2
|
||||
ok("shared-account-rate-limit", replicas=len(observed))
|
||||
seed_ip = """import os,redis
|
||||
r=redis.Redis.from_url(os.environ['REDIS_URL'],ssl_ca_certs='/run/trust/ca.crt',ssl_certfile='/run/identity/service.crt',ssl_keyfile='/run/identity/service.key',ssl_check_hostname=True)
|
||||
keys=list(r.scan_iter('rl:login:ip:*'))
|
||||
assert keys
|
||||
for key in keys:r.set(key,120,px=3000)
|
||||
"""
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-T",
|
||||
"migration",
|
||||
"python",
|
||||
"-c",
|
||||
seed_ip,
|
||||
],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
)
|
||||
login = "ipprobe_" + os.urandom(4).hex()
|
||||
credential = base64.b64encode((login + ":WrongPassword123!").encode()).decode()
|
||||
response = c.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
429,
|
||||
headers={
|
||||
"Authorization": "Basic " + credential,
|
||||
"X-Real-IP": "203.0.113.55",
|
||||
"X-Forwarded-For": "203.0.113.55",
|
||||
},
|
||||
)
|
||||
assert int(response["headers"]["Retry-After"]) > 0
|
||||
ok("shared-ip-rate-limit-spoofed-headers-denied")
|
||||
time.sleep(3.1) # Let the synthetic IP saturation expire before later tests.
|
||||
|
||||
# Expire a real user session in Redis; the same bearer must stop working.
|
||||
expire = """import hashlib,os,sys,json,redis
|
||||
from src.secure.transport import context
|
||||
x=json.load(sys.stdin)
|
||||
r=redis.Redis.from_url(x['url'],ssl_ca_certs='/run/trust/ca.crt',ssl_certfile='/run/identity/service.crt',ssl_keyfile='/run/identity/service.key',ssl_check_hostname=True)
|
||||
r.pexpire('session:v1:'+hashlib.sha256(x['token'].encode()).hexdigest(),1)"""
|
||||
from securitylib import request, root_token
|
||||
|
||||
api = request("secret/data/messenger/api", token=root_token())["data"]["data"]
|
||||
# The operator TLS role is allowed; session Redis auth uses the scoped API account.
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-T",
|
||||
"migration",
|
||||
"python",
|
||||
"-c",
|
||||
expire,
|
||||
],
|
||||
cwd=ROOT,
|
||||
input=json.dumps({"url": api["REDIS_URL"], "token": actor["token"]}),
|
||||
text=True,
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
)
|
||||
time.sleep(0.05)
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
ok("session-expiry")
|
||||
(ROOT / "evidence/security-summary.json").write_text(
|
||||
json.dumps({"checks": ROWS, "passed": len(ROWS)}, indent=2) + "\n"
|
||||
)
|
||||
print("PASS:", len(ROWS), "security checks; evidence/security-summary.json")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--internal", action="store_true")
|
||||
args = parser.parse_args()
|
||||
if args.internal:
|
||||
asyncio.run(internal())
|
||||
else:
|
||||
host_checks()
|
||||
Reference in New Issue
Block a user