forked from mtusi2026/mtusi2026lab7
145 lines
6.3 KiB
Python
145 lines
6.3 KiB
Python
"""Run inside api1 and worker to test their actual TLS clients and permissions."""
|
|
import json
|
|
import os
|
|
import ssl
|
|
|
|
import pika
|
|
import psycopg
|
|
import requests
|
|
from botocore.exceptions import ClientError, SSLError
|
|
|
|
from src import jobs, s3
|
|
from src.config import secret
|
|
|
|
ROLE = os.environ["BAO_ROLE"]
|
|
CA = "/run/ca/server.crt"
|
|
UNRELATED = "/run/ca/unrelated.crt"
|
|
|
|
|
|
def evidence(case, **fields):
|
|
print(json.dumps({"role": ROLE, "case": case, "status": "PASS", **fields}), flush=True)
|
|
|
|
|
|
def bao():
|
|
base = os.environ["BAO_ADDR"] + "/v1/"
|
|
with requests.Session() as client:
|
|
client.trust_env = False
|
|
client.cert = ("/run/identity/client.crt", "/run/identity/client.key")
|
|
client.verify = CA
|
|
try:
|
|
client.get(base + "sys/seal-status", verify=UNRELATED, timeout=3)
|
|
except requests.exceptions.SSLError as exc:
|
|
assert "CERTIFICATE_VERIFY_FAILED" in str(exc)
|
|
evidence("Bao foreign CA")
|
|
else:
|
|
raise AssertionError("Bao trusted foreign CA")
|
|
login = client.post(base + "auth/cert/login", json={"name": ROLE}, timeout=3)
|
|
assert login.status_code == 200, login.status_code
|
|
auth = login.json()["auth"]
|
|
assert auth["policies"] == [f"lab7-{ROLE}"] and 0 < auth["lease_duration"] <= 300
|
|
headers = {"X-Vault-Token": auth["client_token"]}
|
|
peer = "worker" if ROLE == "api" else "api"
|
|
refused = client.post(base + "auth/cert/login", json={"name": peer}, timeout=3)
|
|
assert refused.status_code in (400, 403) and not refused.json().get("auth"), refused.status_code
|
|
own = client.get(base + "lab7/data/" + ROLE, headers=headers, timeout=3)
|
|
assert own.status_code == 200
|
|
assert set(own.json()["data"]["data"]) == {
|
|
"DATABASE_URL", "BROKER_URL", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY", "OTEL_LOGIN"}
|
|
evidence("Bao own KV and peer identity rejected", ttl=auth["lease_duration"], policies=auth["policies"])
|
|
for path, method in (("lab7/data/" + peer, "GET"), ("lab7/data/admin", "GET"),
|
|
("sys/mounts", "GET"), ("sys/policies/acl/review-denied", "PUT")):
|
|
response = client.request(method, base + path, headers=headers,
|
|
json={"policy": ""} if method == "PUT" else None, timeout=3)
|
|
assert response.status_code == 403, (path, response.status_code)
|
|
evidence("Bao authorization rejection", path=path, code=403)
|
|
|
|
|
|
def postgres():
|
|
dsn = secret("DATABASE_URL")
|
|
with psycopg.connect(dsn) as conn:
|
|
info = conn.execute("SELECT current_user, ssl, version FROM pg_stat_ssl WHERE pid = pg_backend_pid()").fetchone()
|
|
assert info[0] == f"lab_{ROLE}" and info[1]
|
|
evidence("PostgreSQL verify-full", identity=info[0], protocol=info[2])
|
|
try:
|
|
if ROLE == "worker":
|
|
conn.execute("SELECT token_hash FROM sessions LIMIT 0")
|
|
else:
|
|
conn.execute("CREATE TABLE review_forbidden (id int)")
|
|
except psycopg.errors.InsufficientPrivilege:
|
|
evidence("PostgreSQL ACL", sqlstate="42501")
|
|
else:
|
|
raise AssertionError("Database ACL did not reject")
|
|
for params in ({"sslrootcert": UNRELATED}, {"host": "wrong.test", "hostaddr": __import__("socket").gethostbyname("postgres")}):
|
|
try:
|
|
with psycopg.connect(dsn, connect_timeout=3, **params):
|
|
raise AssertionError("PostgreSQL trusted invalid peer")
|
|
except psycopg.OperationalError as exc:
|
|
assert "certificate" in str(exc).lower()
|
|
evidence("PostgreSQL foreign CA" if "sslrootcert" in params else "PostgreSQL wrong hostname")
|
|
|
|
|
|
def storage():
|
|
# Reading this known object is granted to API, but intentionally forbidden to worker.
|
|
if ROLE == "api":
|
|
s3.ready()
|
|
evidence("S3 verified HTTPS and authorized object HEAD")
|
|
forbidden = "staging/absent" if ROLE == "api" else "health/ready"
|
|
try:
|
|
s3.client.head_object(Bucket=s3.BUCKET, Key=forbidden)
|
|
except ClientError as exc:
|
|
assert exc.response["ResponseMetadata"]["HTTPStatusCode"] == 403
|
|
evidence("S3 prefix ACL", object=forbidden, code=403)
|
|
else:
|
|
raise AssertionError("Object ACL did not reject")
|
|
try:
|
|
client = s3.boto3.client(
|
|
"s3", endpoint_url=os.environ["S3_ENDPOINT"], verify=UNRELATED,
|
|
aws_access_key_id=secret("S3_ACCESS_KEY_ID"), aws_secret_access_key=secret("S3_SECRET_ACCESS_KEY"),
|
|
config=s3.client.meta.config,
|
|
)
|
|
client.head_object(Bucket=s3.BUCKET, Key="health/ready")
|
|
except SSLError as exc:
|
|
assert "CERTIFICATE_VERIFY_FAILED" in str(exc)
|
|
evidence("S3 foreign CA")
|
|
else:
|
|
raise AssertionError("S3 trusted foreign CA")
|
|
|
|
|
|
def broker():
|
|
with jobs.broker() as channel:
|
|
evidence("AMQPS verified and authenticated", identity=f"lab_{ROLE}")
|
|
try:
|
|
if ROLE == "api":
|
|
channel.basic_get(jobs.QUEUE, auto_ack=False)
|
|
else:
|
|
channel.queue_declare("review-forbidden", exclusive=True)
|
|
except pika.exceptions.ChannelClosedByBroker as exc:
|
|
assert exc.reply_code == 403
|
|
evidence("RabbitMQ ACL", code=403)
|
|
else:
|
|
raise AssertionError("RabbitMQ ACL did not reject")
|
|
context = ssl.create_default_context(cafile=UNRELATED)
|
|
try:
|
|
import socket
|
|
with socket.create_connection(("broker", 5671), timeout=3) as wire:
|
|
with context.wrap_socket(wire, server_hostname="broker"):
|
|
raise AssertionError("RabbitMQ trusted foreign CA")
|
|
except ssl.SSLCertVerificationError:
|
|
evidence("RabbitMQ foreign CA")
|
|
|
|
|
|
def collector():
|
|
url = os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] + "/v1/traces"
|
|
user, passwd = secret("OTEL_LOGIN").split(":", 1)
|
|
with requests.Session() as client:
|
|
client.trust_env = False
|
|
options = {"data": b"", "headers": {"Content-Type": "application/x-protobuf"}, "timeout": 4}
|
|
assert client.post(url, verify=CA, auth=(user, passwd), **options).status_code == 200
|
|
assert client.post(url, verify=CA, **options).status_code == 403
|
|
evidence("OTLP TLS, authorized ingest, anonymous rejected")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
for check in (bao, postgres, storage, broker, collector):
|
|
check()
|