forked from mtusi2026/mtusi2026lab7
200 lines
8.9 KiB
Python
200 lines
8.9 KiB
Python
"""Positive and negative checks inside the Compose network of the local test fixture."""
|
|
import json
|
|
import secrets
|
|
import socket
|
|
import ssl
|
|
import time
|
|
from pathlib import Path
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.request import Request, urlopen
|
|
|
|
import boto3
|
|
from botocore.config import Config
|
|
from botocore.exceptions import ClientError
|
|
import pika
|
|
import psycopg
|
|
from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest
|
|
from bao_client import Bao, BaoError
|
|
|
|
IDENTITIES = Path("/run/audit")
|
|
CA = str(IDENTITIES / "auditor" / "ca.crt")
|
|
QUEUE = "attachment-processing-v1"
|
|
|
|
|
|
def context(identity=None):
|
|
tls = ssl.create_default_context(cafile=CA)
|
|
tls.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
if identity:
|
|
folder = IDENTITIES / identity
|
|
tls.load_cert_chain(folder / "service.crt", folder / "service.key")
|
|
return tls
|
|
|
|
|
|
def http(url, identity=None, body=None, headers=None):
|
|
request = Request(url, data=body, headers=headers or {})
|
|
with urlopen(request, context=context(identity), timeout=4) as response:
|
|
return response.status, response.read()
|
|
|
|
|
|
def denied(action, exceptions):
|
|
try:
|
|
action()
|
|
except exceptions:
|
|
return
|
|
raise AssertionError("an expected denial did not occur")
|
|
|
|
|
|
def expires_at_role(connection):
|
|
return connection.execute("SELECT rolvaliduntil FROM pg_roles WHERE rolname=current_user").fetchone()[0]
|
|
|
|
|
|
def check_ingress():
|
|
host = socket.getaddrinfo("api", 8080, socket.AF_INET, socket.SOCK_STREAM)
|
|
replicas = {info[4][0] for info in host}
|
|
assert len(replicas) >= 2, "expected at least two API replicas"
|
|
|
|
def probe(address, identity, server_name="api"):
|
|
with socket.create_connection((address, 8080), timeout=3) as sock:
|
|
with context(identity).wrap_socket(sock, server_hostname=server_name) as peer:
|
|
peer.sendall(b"GET /health/ready HTTP/1.0\r\nHost: api\r\n\r\n")
|
|
response = peer.recv(256)
|
|
if not response:
|
|
raise ConnectionError("peer closed before HTTP")
|
|
assert response.startswith(b"HTTP/1.0 200 "), response.split(b"\r\n")[0]
|
|
for address in replicas:
|
|
probe(address, "ingress")
|
|
for identity in (None, "foreign", "worker"):
|
|
denied(lambda: probe(address, identity), (OSError,))
|
|
denied(lambda: probe(address, "ingress", "wrong.lab7"), (ssl.SSLCertVerificationError,))
|
|
print(f"PASS LB → {len(replicas)} API: valid client; none/foreign CA/wrong identity/hostname denied")
|
|
|
|
|
|
def broker(identity):
|
|
return pika.BlockingConnection(pika.ConnectionParameters(
|
|
host="rabbitmq", port=5671, virtual_host="/messenger",
|
|
credentials=pika.credentials.ExternalCredentials(),
|
|
ssl_options=pika.SSLOptions(context(identity), "rabbitmq"),
|
|
socket_timeout=3, stack_timeout=5,
|
|
))
|
|
|
|
|
|
def check_broker():
|
|
for role in ("api", "worker"):
|
|
with broker(role):
|
|
pass
|
|
for identity in (None, "foreign", "auditor"):
|
|
denied(lambda: broker(identity), (pika.exceptions.AMQPConnectionError, OSError))
|
|
with broker("api") as connection:
|
|
denied(lambda: connection.channel().basic_get(QUEUE),
|
|
(pika.exceptions.ChannelClosedByBroker,))
|
|
with broker("worker") as connection:
|
|
denied(lambda: connection.channel().queue_declare("lab7-acl-denied"),
|
|
(pika.exceptions.ChannelClosedByBroker,))
|
|
denied(lambda: socket.create_connection(("rabbitmq", 5672), timeout=2), (OSError,))
|
|
print("PASS RabbitMQ EXTERNAL + ACL: api/worker allowed, unknown identities/roles/plaintext denied")
|
|
|
|
|
|
def check_telemetry_transport():
|
|
ingest = "https://collector:4318/v1/traces"
|
|
headers = {"Content-Type": "application/x-protobuf"}
|
|
for role in ("api", "worker"):
|
|
assert http(ingest, role, b"", headers)[0] == 200
|
|
for identity in (None, "foreign"):
|
|
denied(lambda: http(ingest, identity, b"", headers), (URLError, OSError))
|
|
denied(lambda: http(ingest, "auditor", b"", headers), (HTTPError,))
|
|
for port in (8888, 8889):
|
|
endpoint = f"https://collector:{port}/metrics"
|
|
assert http(endpoint, "prometheus")[0] == 200
|
|
denied(lambda: http(endpoint, "worker"), (HTTPError,))
|
|
logs = ExportLogsServiceRequest()
|
|
resource = logs.resource_logs.add()
|
|
label = resource.resource.attributes.add()
|
|
label.key, label.value.string_value = "service.name", "lab7-audit"
|
|
record = resource.scope_logs.add().log_records.add()
|
|
record.body.string_value = "synthetic TLS audit"
|
|
record.time_unix_nano = time.time_ns()
|
|
assert http("https://loki:3100/otlp/v1/logs", "collector", logs.SerializeToString(), headers)[0] in (200, 204)
|
|
assert http("https://tempo:4318/v1/traces", "collector", b"", headers)[0] == 200
|
|
queries = (
|
|
"https://prometheus:9090/api/v1/query?query=up",
|
|
"https://loki:3100/loki/api/v1/labels",
|
|
"https://tempo:3200/api/search?limit=1",
|
|
)
|
|
for query in queries:
|
|
assert http(query, "grafana")[0] == 200
|
|
denied(lambda: http(query, "collector"), (HTTPError,))
|
|
denied(lambda: http("https://tempo:4318/v1/traces", "grafana", b"", headers), (HTTPError,))
|
|
for host, port in (("loki", 13100), ("tempo", 13200), ("collector", 14318),
|
|
("prometheus", 19090), ("rustfs", 19000), ("loki", 9095), ("tempo", 9095)):
|
|
denied(lambda: socket.create_connection((host, port), timeout=2), (OSError,))
|
|
assert http("https://grafana:3000/api/health")[0] == 200
|
|
print("PASS Collector mTLS, backend role ACL, scrape/Grafana mTLS, localhost-only plaintext hops")
|
|
|
|
|
|
def session(role):
|
|
bao = Bao("https://openbao:8200", context(role))
|
|
auth = bao.request("auth/cert/login", {"name": role})["auth"]
|
|
assert auth["lease_duration"] <= 45 and auth["policies"] == [role]
|
|
return bao, auth["client_token"]
|
|
|
|
|
|
def postgres(credentials, mode="verify-full"):
|
|
return psycopg.connect(host="postgres", dbname="messenger", user=credentials["username"],
|
|
password=credentials["password"], sslmode=mode, sslrootcert=CA,
|
|
connect_timeout=3)
|
|
|
|
|
|
def storage(config):
|
|
return boto3.client("s3", endpoint_url="https://rustfs:9000", region_name="us-east-1",
|
|
aws_access_key_id=config["S3_ACCESS_KEY_ID"],
|
|
aws_secret_access_key=config["S3_SECRET_ACCESS_KEY"],
|
|
verify=CA, config=Config(retries={"max_attempts": 0}))
|
|
|
|
|
|
def check_credentials():
|
|
s3 = {}
|
|
denied(lambda: Bao("https://openbao:8200", context("auditor")).request(
|
|
"auth/cert/login", {"name": "worker"}), (BaoError,))
|
|
denied(lambda: Bao("https://openbao:8200", context()).request(
|
|
"sys/policies/acl"), (BaoError,))
|
|
for role, other in (("api", "worker"), ("worker", "api")):
|
|
bao, token = session(role)
|
|
for path in (f"runtime/data/{other}", f"database/creds/{other}", "sys/policies/acl/root"):
|
|
denied(lambda: bao.request(path, token=token), (BaoError,))
|
|
denied(lambda: bao.request(f"runtime/data/{role}", {"data": {}}, token), (BaoError,))
|
|
config = bao.request(f"runtime/data/{role}", token=token)["data"]["data"]
|
|
assert ("CURSOR_SECRET" in config) == (role == "api")
|
|
s3[role] = storage(config)
|
|
issued = bao.request(f"database/creds/{role}", token=token)
|
|
assert issued["lease_duration"] <= 40 and issued["renewable"]
|
|
with postgres(issued["data"]) as connection:
|
|
assert connection.execute("SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()").fetchone() == (True,)
|
|
until = expires_at_role(connection)
|
|
if role == "worker":
|
|
denied(lambda: connection.execute("SELECT password_hash FROM users LIMIT 1"),
|
|
(psycopg.errors.InsufficientPrivilege,))
|
|
connection.rollback()
|
|
time.sleep(2)
|
|
bao.request("sys/leases/renew/" + issued["lease_id"], {}, token)
|
|
with postgres(issued["data"]) as connection:
|
|
assert expires_at_role(connection) > until
|
|
denied(lambda: postgres(issued["data"], "disable"), (psycopg.OperationalError,))
|
|
bucket = "messenger-attachments"
|
|
key = "staging/audit-" + secrets.token_hex(8)
|
|
api, worker = s3["api"], s3["worker"]
|
|
api.put_object(Bucket=bucket, Key=key, Body=b"synthetic fixture")
|
|
with worker.get_object(Bucket=bucket, Key=key)["Body"] as body:
|
|
assert body.read() == b"synthetic fixture"
|
|
denied(lambda: worker.put_object(Bucket=bucket, Key="outside/" + key, Body=b"fixture"), (ClientError,))
|
|
denied(lambda: api.put_object(Bucket=bucket, Key="attachments/" + key, Body=b"fixture"), (ClientError,))
|
|
denied(lambda: worker.list_buckets(), (ClientError,))
|
|
worker.delete_object(Bucket=bucket, Key=key)
|
|
print("PASS OpenBao scopes & renewal, PostgreSQL verify-full and worker DB ACL, S3 prefix ACL")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
check_ingress()
|
|
check_broker()
|
|
check_telemetry_transport()
|
|
check_credentials()
|