Files
mtusi2026lab7/tests/security_internal.py
T

248 lines
9.9 KiB
Python

"""Check expected service permissions with synthetic requests on the lab network."""
import asyncio
import base64
from io import BytesIO
import json
import os
from pathlib import Path
import socket
import ssl
import time
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import HTTPSHandler, ProxyHandler, Request, build_opener
from uuid import uuid4
import aio_pika
from aiormq.exceptions import ChannelAccessRefused
import asyncpg
from minio import Minio
from minio.error import S3Error
from urllib3 import PoolManager
from app.config.bao import BaoClient, BaoError
from app.db.redis import create_redis
from redis.exceptions import NoPermissionError
CA = '/run/secrets/lab_ca'
PROBE = Path('/run/probe')
def tls(role=None):
context = ssl.create_default_context(cafile=CA)
if role:
directory = PROBE / role
context.load_cert_chain(directory / 'public.crt', directory / 'private.key')
return context
def require(condition, description):
if not condition:
raise RuntimeError(description)
def check_api_replicas():
addresses = {item[4][0] for item in socket.getaddrinfo('api', 8443, type=socket.SOCK_STREAM)}
require(len(addresses) == 2, f'Expected two API replicas, found {len(addresses)}')
request = b'GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n'
for address in sorted(addresses):
for role in ('lb', None, 'foreign', 'worker'):
with socket.create_connection((address, 8443), timeout=5) as conn:
try:
with tls(role).wrap_socket(conn, server_hostname='api') as channel:
channel.sendall(request)
result = channel.recv(4096)
except ssl.SSLCertVerificationError:
raise # The server certificate must always verify.
except (ssl.SSLError, BrokenPipeError, ConnectionResetError):
result = b''
if role == 'lb':
require(result.startswith(b'HTTP/1.1 200 '), 'LB certificate did not get HTTP 200')
else:
require(not result, f'API responded to a client with identity {role!r}')
print('PASS: both API replicas accept LB only, including same-CA identity rejection')
def expect_bao_denied(function):
try:
function()
except BaoError as error:
require(error.status == 403, f'Expected OpenBao 403, received {error.status}')
else:
raise RuntimeError('OpenBao granted forbidden access')
def check_bao():
bundles = {}
for role in ('api', 'publisher', 'worker'):
client = BaoClient('https://openbao:8200', CA, PROBE / role)
auth = client.login(role)
token = auth['client_token']
try:
require(0 < auth['lease_duration'] <= 300, 'Unexpected OpenBao token TTL')
bundles[role] = client.read_service(role, token)
for other in {'api', 'publisher', 'worker'} - {role}:
expect_bao_denied(lambda: client.read_service(other, token))
expect_bao_denied(lambda: client.request(
f'sys/policies/acl/negative-test-{uuid4().hex}',
{'policy': 'path "sys/health" { capabilities = ["read"] }'}, token=token,
))
finally:
client.request('auth/token/revoke-self', {}, token=token)
expect_bao_denied(lambda: client.read_service(role, token))
outsider = BaoClient('https://openbao:8200', CA, PROBE / 'query')
try:
outsider.login('api')
except BaoError as error:
require(error.status in (400, 403), 'Unexpected status for OpenBao identity rejection')
else:
raise RuntimeError('OpenBao accepted a different certificate signed by the same CA')
print('PASS: OpenBao scoped reads, short TTL, cross-role and policy-write denial, token revoked')
return bundles
async def check_store_permissions(bundles):
for role in ('api', 'publisher', 'worker'):
dsn = bundles[role]['DATABASE_URL'].replace('postgresql+asyncpg://', 'postgresql://', 1)
db = await asyncpg.connect(dsn, ssl=tls(), timeout=4)
try:
require(await db.fetchval('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()'),
'PostgreSQL connection is not encrypted')
if role == 'api':
await db.fetchval('SELECT count(*) FROM users')
else:
try:
await db.fetchval('SELECT count(*) FROM users')
except asyncpg.InsufficientPrivilegeError:
pass
else:
raise RuntimeError(f'{role} should not have access to users')
finally:
await db.close()
redis = create_redis(bundles['api']['REDIS_URL'])
try:
await redis.ping()
try:
await redis.get('operator:probe')
except NoPermissionError:
pass
else:
raise RuntimeError('Redis ACL allowed an unrelated prefix')
finally:
await redis.aclose()
for role in ('publisher', 'worker'):
async with await aio_pika.connect(bundles[role]['BROKER_URL'], ssl_context=tls(), timeout=5) as broker:
channel = await broker.channel()
try:
await channel.declare_queue(f'negative-test-{uuid4().hex}', auto_delete=True, exclusive=True)
except ChannelAccessRefused:
pass
else:
raise RuntimeError(f'{role} can create unrelated RabbitMQ queues')
print('PASS: PostgreSQL, Redis and RabbitMQ accept scoped TLS identities and deny unrelated access')
def check_s3(bundles):
clients = {
role: Minio('s3:9000', credentials['S3_ACCESS_KEY_ID'], credentials['S3_SECRET_ACCESS_KEY'],
region='us-east-1', http_client=PoolManager(ca_certs=CA, cert_reqs='CERT_REQUIRED'))
for role, credentials in bundles.items() if role in ('api', 'worker')
}
bucket = os.getenv('S3_BUCKET', 'messenger-attachments')
clients['api'].stat_object(bucket, 'originals/.health')
key = f'staging/test-{uuid4().hex}/original'
clients['api'].put_object(bucket, key, BytesIO(b'x'), 1)
try:
clients['worker'].stat_object(bucket, key)
try:
clients['worker'].put_object(bucket, key, BytesIO(b'y'), 1)
except S3Error as error:
require(error.code == 'AccessDenied', 'S3 returned a different error than access denial')
else:
raise RuntimeError('Worker can overwrite staging data')
finally:
clients['api'].remove_object(bucket, key)
print('PASS: MinIO TLS, API stages data, worker can read but not overwrite staging')
def check_telemetry_roles():
opener = build_opener(ProxyHandler({}), HTTPSHandler(context=tls('query')))
request = Request('https://otel-collector:4318/v1/logs', data=b'',
headers={'Content-Type': 'application/x-protobuf'})
try:
opener.open(request, timeout=5).close()
except HTTPError as error:
require(error.code == 403, 'Expected 403 for a Grafana identity on OTLP ingest')
else:
raise RuntimeError('Grafana identity can send OTLP')
print('PASS: query identity cannot submit telemetry')
def check_telemetry_privacy():
marker = 'synthetic-privacy-' + uuid4().hex
api = build_opener(ProxyHandler({}), HTTPSHandler(context=tls('lb')))
request = Request(
'https://api:8443/api/v1/users/me?' + urlencode({'probe': marker}),
headers={'Authorization': 'Bearer ' + marker},
)
try:
api.open(request, timeout=5).close()
except HTTPError as error:
require(error.code == 401, 'Synthetic unauthorized API request should return 401')
request_id = error.headers.get('X-Request-Id')
error.close()
require(request_id, 'Privacy probe is missing a request ID')
else:
raise RuntimeError('Synthetic credential was unexpectedly accepted')
user = os.getenv('GRAFANA_ADMIN_USER', 'admin')
password = Path('/run/secrets/grafana_admin_password').read_text().strip()
auth = base64.b64encode(f'{user}:{password}'.encode()).decode()
grafana = build_opener(ProxyHandler({}), HTTPSHandler(context=tls()))
deadline = time.monotonic() + 35
since = time.time_ns() - 30_000_000_000
def fetch(path):
request = Request('https://grafana:3000' + path, headers={'Authorization': 'Basic ' + auth})
with grafana.open(request, timeout=5) as response:
payload = response.read()
require(marker.encode() not in payload, 'Synthetic credential or query value reached telemetry')
return json.loads(payload)
while time.monotonic() < deadline:
query = urlencode({
'query': '{service_name="messenger-api"} | json | request_id="' + request_id + '"',
'start': str(since), 'end': str(time.time_ns()), 'limit': '5',
})
logs = fetch('/api/datasources/proxy/uid/loki/loki/api/v1/query_range?' + query)
for stream in logs['data']['result']:
for entry in stream['values']:
trace_id = json.loads(entry[1]).get('trace_id')
if not trace_id:
continue
try:
trace = fetch('/api/datasources/proxy/uid/tempo/api/traces/' + trace_id)
except HTTPError as error:
if error.code != 404:
raise
else:
require(trace.get('batches'), 'Tempo trace response was empty')
print('PASS: correlated log and trace omit synthetic credential and URL query')
return
time.sleep(1)
raise RuntimeError('Could not find the privacy probe log and trace')
if __name__ == '__main__':
check_api_replicas()
values = check_bao()
check_s3(values)
os.environ['TLS_CA_FILE'] = CA
asyncio.run(check_store_permissions(values))
check_telemetry_roles()
check_telemetry_privacy()