Files
mtusi2026lab7/student-tests/internal.py
T
2026-11-27 21:55:47 +03:00

186 lines
11 KiB
Python

"""Operator-only, real network negative tests; no credentials in result files."""
import base64
import hashlib
import json
import resource
from pathlib import Path
import socket
import ssl
import statistics
import sys
import time
import uuid
import boto3
from botocore.exceptions import ClientError
import psycopg
from redis import Redis
from redis.exceptions import ResponseError
import requests
from argon2 import PasswordHasher
S=Path('/audit-secrets')
sys.path.insert(0, '/app')
CA=str(S/'ca.crt')
config=json.loads((S/'operator-private/credentials.json').read_text())
results=[]
def record(name, condition=True, **details):
assert condition, name
results.append({'test':name,'passed':True,**details})
print('PASS: '+name,flush=True)
def http(method,url,role=None,**kw):
client=requests.Session();client.trust_env=False
cert=(str(S/role/'tls.crt'),str(S/role/'tls.key')) if role else None
return client.request(method,url,verify=CA,cert=cert,timeout=8,**kw)
def tls(host,port,identity,body,hostname=None):
ctx=ssl.create_default_context(cafile=CA)
if identity: ctx.load_cert_chain(str(S/identity/'tls.crt'),str(S/identity/'tls.key'))
with socket.create_connection((host,port),timeout=3) as raw:
with ctx.wrap_socket(raw,server_hostname=hostname or host) as conn:
conn.sendall(body)
return conn.recv(8192)
def rejection(host,port,identity,body):
try: response=tls(host,port,identity,body)
except (ssl.SSLError,ConnectionResetError): response=b''
# Timeouts/refused connections are NOT accepted as proof of authorization denial.
return not response
def db(role):
return psycopg.connect(host='postgres',dbname='messenger',user=role,password=config[role]['db'],
sslmode='verify-full',sslrootcert=CA,connect_timeout=3,autocommit=True)
def redis(role,broker=False):
return Redis(host='broker' if broker else 'redis',port=6380,username=role,
password=config[role]['broker' if broker else 'redis'],ssl=True,ssl_ca_certs=CA,
ssl_check_hostname=True,ssl_certfile=str(S/role/'tls.crt') if broker else None,
ssl_keyfile=str(S/role/'tls.key') if broker else None,decode_responses=True,
socket_timeout=3,socket_connect_timeout=3)
def main():
from src.telemetry import extract, trace
start=time.perf_counter()
for _ in range(20):
extract({'traceparent':'00-'+' '*100000+'\n','tracestate':' '*100000+'x'})
record('Oversized HTTP/JSON trace context has bounded parsing cost',time.perf_counter()-start<1)
context=extract({'traceparent':'00-'+'1'*32+'-'+'2'*16+'-01'})
record('Valid trace context remains supported',trace.get_current_span(context).get_span_context().is_valid)
body=b'GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n'
ingest=b'POST /v1/traces HTTP/1.1\r\nHost: otel-collector\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}'
matrix=[('api1',8443,'lb',body),('api2',8443,'lb',body),
('broker',6380,'worker',b'*1\r\n$4\r\nPING\r\n'),('otel-collector',44318,'api',ingest)]
for host,port,allowed,payload in matrix:
record(host+' accepts allowed identity',bool(tls(host,port,allowed,payload)))
for forbidden in [None,'foreign-'+allowed,'outsider','expired-'+allowed]:
record(host+' rejects '+str(forbidden),rejection(host,port,forbidden,payload))
if host.startswith('api') and (S/'old-lb/tls.crt').exists():
record(host+' rejects revoked LB serial',rejection(host,port,'old-lb',payload))
for role in ['worker','dispatcher']:
record('Collector accepts '+role,b'200' in tls('otel-collector',44318,role,ingest))
for host,port in [('lb',8443),('redis',6380),('s3',9443),('grafana',3443),('openbao',8200)]:
ctx=ssl.create_default_context(cafile=CA)
with socket.create_connection((host,port),timeout=3) as raw:
with ctx.wrap_socket(raw,server_hostname=host) as conn:
record(host+' server TLS verified',True,protocol=conn.version())
try: tls(host,port,None,b'GET / HTTP/1.0\r\n\r\n',hostname='wrong.invalid')
except ssl.SSLCertVerificationError: record(host+' rejects wrong hostname')
else: raise AssertionError('hostname accepted')
for host,port,local,role,path in [('prometheus',19090,9090,'grafana','/-/ready'),
('loki',13100,3100,'grafana','/ready'),('tempo',13200,3200,'grafana','/ready'),
('otel-collector',18889,8889,'prometheus','/metrics'),('otel-collector',18888,8888,'prometheus','/metrics'),
('tempo',14318,4318,'otel-collector','/v1/traces')]:
payload=(f'GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n').encode()
record(f'{host}:{port} trusted identity',bool(tls(host,port,role,payload)))
record(f'{host}:{port} rejects outsider',rejection(host,port,'outsider',payload))
for host,port in [('api1',8080),('api2',8080),('broker',6379),('redis',6379),('s3',9000),
('otel-collector',4318),('otel-collector',8888),('otel-collector',8889),
('prometheus',9090),('loki',3100),('loki',9095),('tempo',3200),('tempo',4318),('tempo',9095),('grafana',3000)]:
try:
with socket.create_connection((host,port),timeout=2): pass
except ConnectionRefusedError: record(f'No plaintext bypass {host}:{port}')
else: raise AssertionError('plaintext listener exposed')
for role in ['api','worker','dispatcher','cleanup']:
with db(role) as conn:
record('PostgreSQL TLS '+role,conn.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()[0])
try: conn.execute('CREATE TABLE forbidden_probe(id int)')
except psycopg.errors.InsufficientPrivilege: record('DB no DDL '+role)
else: raise AssertionError('DDL allowed')
if role!='api':
try: conn.execute('SELECT password_hash FROM users LIMIT 1')
except psycopg.errors.InsufficientPrivilege: record('DB password hashes denied '+role)
else: raise AssertionError('password hashes exposed')
auth=http('POST','https://openbao:8200/v1/auth/cert/login',role,json={'name':role})
record('OpenBao cert auth '+role,auth.status_code==200)
token=auth.json()['auth']['client_token'];headers={'X-Vault-Token':token}
record('OpenBao short TTL '+role,0<auth.json()['auth']['lease_duration']<=60)
record('OpenBao own KV '+role,http('GET','https://openbao:8200/v1/secret/data/'+role,role,headers=headers).status_code==200)
other='worker' if role=='api' else 'api'
record('OpenBao other KV denied '+role,http('GET','https://openbao:8200/v1/secret/data/'+other,role,headers=headers).status_code==403)
record('OpenBao policy write denied '+role,http('PUT','https://openbao:8200/v1/sys/policies/acl/forbidden',role,headers=headers,json={'policy':''}).status_code==403)
record('OpenBao outsider denied',http('POST','https://openbao:8200/v1/auth/cert/login','outsider',json={'name':'api'}).status_code==400)
for role,cmd in [('api',lambda c:c.xadd('attachment-jobs',{'job':'forbidden'})),
('worker',lambda c:c.xadd('attachment-jobs',{'job':'forbidden'})),
('dispatcher',lambda c:c.xreadgroup('image-workers','forbidden',{'attachment-jobs':'>'},count=1))]:
client=redis(role,True);record('Broker authenticated '+role,client.ping())
try:cmd(client)
except ResponseError as exc: record('Broker ACL denied '+role,'permissions' in str(exc).lower() or 'noperm' in str(exc).lower())
else:raise AssertionError('broker command allowed')
for role,prefix in [('api','variants'),('worker','staging'),('cleanup','staging')]:
client=boto3.client('s3',endpoint_url='https://s3:9443',verify=CA,
aws_access_key_id=role,aws_secret_access_key=config[role]['s3'],region_name='us-east-1')
try:client.put_object(Bucket='messenger-attachments',Key=prefix+'/forbidden',Body=b'x')
except ClientError as exc:record('S3 denied write prefix '+role,exc.response['Error']['Code']=='AccessDenied')
else:raise AssertionError('S3 write allowed')
# Real rehash via the public API and a synthetic old Argon2id record.
username='rehash_'+uuid.uuid4().hex[:12];password='synthetic-'+uuid.uuid4().hex
old=PasswordHasher(time_cost=1,memory_cost=8192,parallelism=1).hash(password)
user_id=str(uuid.uuid4())
with db('api') as conn:
conn.execute('INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s)',(user_id,username,'Rehash test',old))
response=http('POST','https://lb:8443/api/v1/auth/sessions',auth=(username,password))
record('Old Argon2 login succeeds',response.status_code==201)
token=response.json()['token']
with db('api') as conn:
encoded=conn.execute('SELECT password_hash FROM users WHERE id=%s',(user_id,)).fetchone()[0]
record('Password rehashed',encoded.startswith('$argon2id$v=19$m=19456,t=2,p=1$'))
client=redis('api');key='session:'+hashlib.sha256(token.encode()).hexdigest()
stored=client.get(key)
record('Session stores digest key, no credential',stored is not None and token not in stored and password not in stored)
client.expire(key,1);time.sleep(1.1)
record('Expired session rejected',http('GET','https://lb:8443/api/v1/users/me',headers={'Authorization':'Bearer '+token}).status_code==401)
# Same account alternates replicas. Eight accepted attempts total, not per replica.
username='missing_'+uuid.uuid4().hex[:12];statuses=[];instances=set()
for _ in range(12):
r=http('POST','https://lb:8443/api/v1/auth/sessions',auth=(username,'synthetic-password'))
statuses.append(r.status_code);instances.add(r.headers.get('X-Instance-Id'))
if r.status_code==429:record('Rate limit carries Retry-After',r.headers.get('Retry-After')=='1')
record('Rate limit shared across replicas',statuses.count(401)==8 and statuses.count(429)==4 and len(instances)==2,instances=len(instances),statuses=statuses)
samples=[];hasher=PasswordHasher(time_cost=2,memory_cost=19456,parallelism=1)
hasher.verify(encoded,password) # One warmup; sequential measurements, no HTTP load.
wall_start=time.perf_counter();cpu_start=time.process_time()
for _ in range(20):
start=time.perf_counter();hasher.verify(encoded,password);samples.append(time.perf_counter()-start)
record('Measured Argon2 budget',True,memory_kib=19456,time_cost=2,parallelism=1,
median_ms=round(statistics.median(samples)*1000,2),p95_ms=round(sorted(samples)[18]*1000,2),
p99_ms=round(max(samples)*1000,2),samples_ms=[round(s*1000,3) for s in samples],
duration_seconds=round(time.perf_counter()-wall_start,3),
cpu_seconds=round(time.process_time()-cpu_start,3),
process_peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
global_limit_per_second=32,account_limit_per_10seconds=8,hash_concurrency_per_api=2)
# Every secret is checked as a value, but never serialized in evidence.
(Path('/evidence')/'internal.json').write_text(json.dumps({'checks':results},indent=2))
print(f'PASS: {len(results)} internal checks')
if __name__=='__main__':main()