forked from mtusi2026/mtusi2026lab7
test(security): automate lifecycle and login budget measurements
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
"""Prepare an owner-only libpq key inside the explicit operator task tmpfs."""
|
||||
|
||||
import os
|
||||
import runpy
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def prepare_key():
|
||||
# Docker Desktop bind ownership differs from the rootless container UID.
|
||||
# The source stays beneath the host operator directory; only this explicit
|
||||
# task mounts it. libpq receives an owned 0600 file in ephemeral tmpfs.
|
||||
target = Path("/tmp/operator-client.key")
|
||||
temporary = target.with_name(target.name + "." + str(os.getpid()))
|
||||
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as stream:
|
||||
stream.write(Path("/run/identity/current/key.pem").read_bytes())
|
||||
temporary.replace(target)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def main():
|
||||
prepare_key()
|
||||
runpy.run_module("src.operator", run_name="__main__")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+247
-238
@@ -32,7 +32,7 @@ def context(role=None, *, foreign=False, wrong_ca=False):
|
||||
if foreign
|
||||
else (
|
||||
Path("/probe-fixtures") / role
|
||||
if role in {"revoked-lb", "retired-ca-lb"}
|
||||
if role in {"revoked-lb", "retired-ca-lb", "operator"}
|
||||
else Path("/identities") / role / "current"
|
||||
)
|
||||
)
|
||||
@@ -77,255 +77,264 @@ def values(role):
|
||||
|
||||
def main():
|
||||
report = {"complete": False, "tls": [], "bypass": [], "database": {}}
|
||||
request = (
|
||||
b"GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n"
|
||||
)
|
||||
addresses = sorted(
|
||||
{
|
||||
x[4][0]
|
||||
for x in socket.getaddrinfo(
|
||||
"api", 8443, type=socket.SOCK_STREAM, family=socket.AF_INET
|
||||
)
|
||||
}
|
||||
)
|
||||
assert len(addresses) >= 2, "Both API replicas must be running"
|
||||
endpoints = [
|
||||
("api", 8443, "lb", "worker", request, ip) for ip in addresses
|
||||
]
|
||||
body = b"{}"
|
||||
otlp = (
|
||||
b"POST /v1/traces HTTP/1.1\r\nHost: otel\r\n"
|
||||
b"Content-Type: application/json\r\nContent-Length: 2\r\n"
|
||||
b"Connection: close\r\n\r\n" + body
|
||||
)
|
||||
endpoints += [
|
||||
("otel", 4438, "api", "lb", otlp, None),
|
||||
("broker", 6380, "worker", "api", b"*1\r\n$4\r\nPING\r\n", None),
|
||||
]
|
||||
for host, port, good, wrong, payload, address in endpoints:
|
||||
response = exchange(host, port, good, payload, address=address)
|
||||
assert b" 200 " in response or response.startswith(b"-NOAUTH"), (
|
||||
host,
|
||||
response[:80],
|
||||
try:
|
||||
request = (
|
||||
b"GET /health/live HTTP/1.1\r\nHost: api\r\n"
|
||||
b"Connection: close\r\n\r\n"
|
||||
)
|
||||
result = {
|
||||
"host": host,
|
||||
"port": port,
|
||||
"address": address,
|
||||
"authorized": True,
|
||||
}
|
||||
for case, role, foreign in [
|
||||
("no_certificate", None, False),
|
||||
("foreign_ca", good, True),
|
||||
("trusted_wrong_identity", wrong, False),
|
||||
]:
|
||||
result[case + "_denied"] = denied(
|
||||
partial(
|
||||
exchange,
|
||||
host,
|
||||
port,
|
||||
role,
|
||||
payload,
|
||||
address=address,
|
||||
foreign=foreign,
|
||||
addresses = sorted(
|
||||
{
|
||||
x[4][0]
|
||||
for x in socket.getaddrinfo(
|
||||
"api", 8443, type=socket.SOCK_STREAM, family=socket.AF_INET
|
||||
)
|
||||
)
|
||||
report["tls"].append(result)
|
||||
report["tls_server_ca_denied"] = denied(
|
||||
lambda: exchange("api", 8443, "lb", request, wrong_ca=True)
|
||||
)
|
||||
report["tls_server_hostname_denied"] = denied(
|
||||
lambda: exchange(
|
||||
"api", 8443, "lb", request, hostname="unexpected.invalid"
|
||||
}
|
||||
)
|
||||
)
|
||||
for host, port in [
|
||||
("api", 8080),
|
||||
("postgres", 5432),
|
||||
("broker", 6379),
|
||||
("cache", 6379),
|
||||
("s3", 9000),
|
||||
("otel", 4318),
|
||||
("otel", 8889),
|
||||
("prometheus", 9090),
|
||||
("loki", 3100),
|
||||
("tempo", 3200),
|
||||
("grafana", 3000),
|
||||
("lb", 8404),
|
||||
]:
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=2):
|
||||
raise AssertionError("Plaintext boundary bypass: " + host)
|
||||
except ConnectionRefusedError:
|
||||
report["bypass"].append(
|
||||
{"host": host, "port": port, "closed": True}
|
||||
assert len(addresses) >= 2, "Both API replicas must be running"
|
||||
endpoints = [
|
||||
("api", 8443, "lb", "worker", request, ip) for ip in addresses
|
||||
]
|
||||
body = b"{}"
|
||||
otlp = (
|
||||
b"POST /v1/traces HTTP/1.1\r\nHost: otel\r\n"
|
||||
b"Content-Type: application/json\r\nContent-Length: 2\r\n"
|
||||
b"Connection: close\r\n\r\n" + body
|
||||
)
|
||||
endpoints += [
|
||||
("otel", 4438, "api", "lb", otlp, None),
|
||||
("broker", 6380, "worker", "api", b"*1\r\n$4\r\nPING\r\n", None),
|
||||
]
|
||||
for host, port, good, wrong, payload, address in endpoints:
|
||||
response = exchange(host, port, good, payload, address=address)
|
||||
assert b" 200 " in response or response.startswith(b"-NOAUTH"), (
|
||||
host,
|
||||
response[:80],
|
||||
)
|
||||
worker = values("worker")
|
||||
with psycopg.connect(
|
||||
worker["DATABASE_URL"].replace(
|
||||
"/run/identity/", "/identities/worker/"
|
||||
),
|
||||
connect_timeout=3,
|
||||
autocommit=True,
|
||||
) as connection:
|
||||
assert connection.execute("SELECT 1").fetchone()[0] == 1
|
||||
for key, query in [
|
||||
(
|
||||
"user_passwords_denied",
|
||||
"SELECT password_hash FROM users LIMIT 1",
|
||||
),
|
||||
(
|
||||
"session_hashes_denied",
|
||||
"SELECT token_digest FROM sessions LIMIT 1",
|
||||
),
|
||||
("create_role_denied", "CREATE ROLE unauthorized_probe LOGIN"),
|
||||
result = {
|
||||
"host": host,
|
||||
"port": port,
|
||||
"address": address,
|
||||
"authorized": True,
|
||||
}
|
||||
for case, role, foreign in [
|
||||
("no_certificate", None, False),
|
||||
("foreign_ca", good, True),
|
||||
("trusted_wrong_identity", wrong, False),
|
||||
]:
|
||||
result[case + "_denied"] = denied(
|
||||
partial(
|
||||
exchange,
|
||||
host,
|
||||
port,
|
||||
role,
|
||||
payload,
|
||||
address=address,
|
||||
foreign=foreign,
|
||||
)
|
||||
)
|
||||
report["tls"].append(result)
|
||||
report["tls_server_ca_denied"] = denied(
|
||||
lambda: exchange("api", 8443, "lb", request, wrong_ca=True)
|
||||
)
|
||||
report["tls_server_hostname_denied"] = denied(
|
||||
lambda: exchange(
|
||||
"api", 8443, "lb", request, hostname="unexpected.invalid"
|
||||
)
|
||||
)
|
||||
for host, port in [
|
||||
("api", 8080),
|
||||
("postgres", 5432),
|
||||
("broker", 6379),
|
||||
("cache", 6379),
|
||||
("s3", 9000),
|
||||
("otel", 4318),
|
||||
("otel", 8889),
|
||||
("prometheus", 9090),
|
||||
("loki", 3100),
|
||||
("tempo", 3200),
|
||||
("grafana", 3000),
|
||||
("lb", 8404),
|
||||
]:
|
||||
try:
|
||||
connection.execute(query)
|
||||
except InsufficientPrivilege:
|
||||
report["database"][key] = True
|
||||
with socket.create_connection((host, port), timeout=2):
|
||||
raise AssertionError("Plaintext boundary bypass: " + host)
|
||||
except ConnectionRefusedError:
|
||||
report["bypass"].append(
|
||||
{"host": host, "port": port, "closed": True}
|
||||
)
|
||||
worker = values("worker")
|
||||
with psycopg.connect(
|
||||
worker["DATABASE_URL"].replace(
|
||||
"/run/identity/", "/identities/worker/"
|
||||
),
|
||||
connect_timeout=3,
|
||||
autocommit=True,
|
||||
) as connection:
|
||||
assert connection.execute("SELECT 1").fetchone()[0] == 1
|
||||
for key, query in [
|
||||
(
|
||||
"user_passwords_denied",
|
||||
"SELECT password_hash FROM users LIMIT 1",
|
||||
),
|
||||
(
|
||||
"session_hashes_denied",
|
||||
"SELECT token_digest FROM sessions LIMIT 1",
|
||||
),
|
||||
("create_role_denied", "CREATE ROLE unauthorized_probe LOGIN"),
|
||||
]:
|
||||
try:
|
||||
connection.execute(query)
|
||||
except InsufficientPrivilege:
|
||||
report["database"][key] = True
|
||||
else:
|
||||
raise AssertionError(
|
||||
"Worker SQL privilege was excessive: " + key
|
||||
)
|
||||
url = worker["BROKER_URL"]
|
||||
queue = redis.Redis.from_url(
|
||||
url,
|
||||
ssl_ca_certs="/trust/ca.pem",
|
||||
ssl_certfile="/identities/worker/current/cert.pem",
|
||||
ssl_keyfile="/identities/worker/current/key.pem",
|
||||
ssl_cert_reqs="required",
|
||||
ssl_check_hostname=True,
|
||||
socket_timeout=3,
|
||||
socket_connect_timeout=3,
|
||||
)
|
||||
try:
|
||||
assert queue.ping()
|
||||
try:
|
||||
queue.config_get("*")
|
||||
except redis.exceptions.NoPermissionError:
|
||||
report["broker_admin_denied"] = True
|
||||
else:
|
||||
raise AssertionError(
|
||||
"Worker SQL privilege was excessive: " + key
|
||||
"Worker received broker administration privileges"
|
||||
)
|
||||
url = worker["BROKER_URL"]
|
||||
queue = redis.Redis.from_url(
|
||||
url,
|
||||
ssl_ca_certs="/trust/ca.pem",
|
||||
ssl_certfile="/identities/worker/current/cert.pem",
|
||||
ssl_keyfile="/identities/worker/current/key.pem",
|
||||
ssl_cert_reqs="required",
|
||||
ssl_check_hostname=True,
|
||||
socket_timeout=3,
|
||||
socket_connect_timeout=3,
|
||||
)
|
||||
try:
|
||||
assert queue.ping()
|
||||
try:
|
||||
queue.config_get("*")
|
||||
except redis.exceptions.NoPermissionError:
|
||||
report["broker_admin_denied"] = True
|
||||
else:
|
||||
raise AssertionError(
|
||||
"Worker received broker administration privileges"
|
||||
)
|
||||
finally:
|
||||
queue.close()
|
||||
|
||||
# Real service certificate authentication against persistent OpenBao.
|
||||
def bao(method, path, payload=None, token=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
request = urllib.request.Request(
|
||||
"https://openbao:8200/v1/" + path,
|
||||
data=json.dumps(payload).encode() if payload is not None else None,
|
||||
method=method,
|
||||
headers=headers,
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
request, context=context("worker"), timeout=4
|
||||
) as response:
|
||||
return response.status, json.load(
|
||||
response
|
||||
) if response.length != 0 else {}
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, {}
|
||||
|
||||
status, login = bao("POST", "auth/cert/login", {})
|
||||
assert status == 200
|
||||
token = login["auth"]["client_token"]
|
||||
assert set(login["auth"]["policies"]) == {"messenger-worker"}
|
||||
report["openbao"] = {
|
||||
"service_policies": login["auth"]["policies"],
|
||||
"token_ttl_seconds": login["auth"]["lease_duration"],
|
||||
}
|
||||
assert bao("GET", "secret/data/worker", token=token)[0] == 200
|
||||
for key, method, path, payload in [
|
||||
("foreign_secret_denied", "GET", "secret/data/api", None),
|
||||
(
|
||||
"policy_write_denied",
|
||||
"PUT",
|
||||
"sys/policies/acl/messenger-worker",
|
||||
{"policy": 'path "*" { capabilities=["sudo"] }'},
|
||||
),
|
||||
(
|
||||
"foreign_pki_role_denied",
|
||||
"POST",
|
||||
"pki/issue/lb",
|
||||
{"common_name": "lb"},
|
||||
),
|
||||
]:
|
||||
assert bao(method, path, payload, token)[0] == 403, key
|
||||
report["openbao"][key] = True
|
||||
clients = {}
|
||||
pools = []
|
||||
for role in ["api", "worker", "reconciler"]:
|
||||
credentials = values(role)
|
||||
pool = urllib3.PoolManager(
|
||||
ssl_context=context(role),
|
||||
timeout=urllib3.Timeout(connect=2, read=4),
|
||||
retries=False,
|
||||
)
|
||||
pools.append(pool)
|
||||
clients[role] = Minio(
|
||||
"s3:9443",
|
||||
credentials=StaticProvider(
|
||||
credentials["S3_ACCESS_KEY"], credentials["S3_SECRET_KEY"]
|
||||
),
|
||||
secure=True,
|
||||
http_client=pool,
|
||||
region="us-east-1",
|
||||
)
|
||||
prefix = uuid4().hex
|
||||
staging = "objects/staging/probe-" + prefix
|
||||
derived = "objects/probe-" + prefix + "/v1/original"
|
||||
|
||||
def put(role, key):
|
||||
clients[role].put_object(
|
||||
"messenger", key, io.BytesIO(b"Synthetic IAM probe"), 19
|
||||
)
|
||||
|
||||
def s3_denied(action):
|
||||
try:
|
||||
action()
|
||||
except S3Error as error:
|
||||
assert error.code == "AccessDenied", error.code
|
||||
return True
|
||||
raise AssertionError("S3 operation unexpectedly allowed")
|
||||
|
||||
try:
|
||||
put("api", staging)
|
||||
received = clients["worker"].get_object("messenger", staging)
|
||||
try:
|
||||
assert received.read() == b"Synthetic IAM probe"
|
||||
finally:
|
||||
received.close()
|
||||
received.release_conn()
|
||||
put("worker", derived)
|
||||
report["s3"] = {
|
||||
"api_staging_write": True,
|
||||
"worker_source_read": True,
|
||||
"worker_derived_write": True,
|
||||
"api_derived_write_denied": s3_denied(lambda: put("api", derived)),
|
||||
"worker_staging_write_denied": s3_denied(
|
||||
lambda: put("worker", staging)
|
||||
),
|
||||
"worker_list_all_buckets_denied": s3_denied(
|
||||
lambda: clients["worker"].list_buckets()
|
||||
),
|
||||
"worker_delete_denied": s3_denied(
|
||||
lambda: clients["worker"].remove_object("messenger", derived)
|
||||
),
|
||||
queue.close()
|
||||
|
||||
# Real service certificate authentication against persistent OpenBao.
|
||||
def bao(method, path, payload=None, token=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
request = urllib.request.Request(
|
||||
"https://openbao:8200/v1/" + path,
|
||||
data=json.dumps(payload).encode()
|
||||
if payload is not None
|
||||
else None,
|
||||
method=method,
|
||||
headers=headers,
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
request, context=context("worker"), timeout=4
|
||||
) as response:
|
||||
return response.status, json.load(
|
||||
response
|
||||
) if response.length != 0 else {}
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, {}
|
||||
|
||||
status, login = bao("POST", "auth/cert/login", {})
|
||||
assert status == 200
|
||||
token = login["auth"]["client_token"]
|
||||
assert set(login["auth"]["policies"]) == {"messenger-worker"}
|
||||
report["openbao"] = {
|
||||
"service_policies": login["auth"]["policies"],
|
||||
"token_ttl_seconds": login["auth"]["lease_duration"],
|
||||
}
|
||||
assert bao("GET", "secret/data/worker", token=token)[0] == 200
|
||||
for key, method, path, payload in [
|
||||
("foreign_secret_denied", "GET", "secret/data/api", None),
|
||||
(
|
||||
"policy_write_denied",
|
||||
"PUT",
|
||||
"sys/policies/acl/messenger-worker",
|
||||
{"policy": 'path "*" { capabilities=["sudo"] }'},
|
||||
),
|
||||
(
|
||||
"foreign_pki_role_denied",
|
||||
"POST",
|
||||
"pki/issue/lb",
|
||||
{"common_name": "lb"},
|
||||
),
|
||||
]:
|
||||
assert bao(method, path, payload, token)[0] == 403, key
|
||||
report["openbao"][key] = True
|
||||
clients = {}
|
||||
pools = []
|
||||
for role in ["api", "worker", "reconciler"]:
|
||||
credentials = values(role)
|
||||
pool = urllib3.PoolManager(
|
||||
ssl_context=context(role),
|
||||
timeout=urllib3.Timeout(connect=2, read=4),
|
||||
retries=False,
|
||||
)
|
||||
pools.append(pool)
|
||||
clients[role] = Minio(
|
||||
"s3:9443",
|
||||
credentials=StaticProvider(
|
||||
credentials["S3_ACCESS_KEY"], credentials["S3_SECRET_KEY"]
|
||||
),
|
||||
secure=True,
|
||||
http_client=pool,
|
||||
region="us-east-1",
|
||||
)
|
||||
prefix = uuid4().hex
|
||||
staging = "objects/staging/probe-" + prefix
|
||||
derived = "objects/probe-" + prefix + "/v1/original"
|
||||
|
||||
def put(role, key):
|
||||
clients[role].put_object(
|
||||
"messenger", key, io.BytesIO(b"Synthetic IAM probe"), 19
|
||||
)
|
||||
|
||||
def s3_denied(action):
|
||||
try:
|
||||
action()
|
||||
except S3Error as error:
|
||||
assert error.code == "AccessDenied", error.code
|
||||
return True
|
||||
raise AssertionError("S3 operation unexpectedly allowed")
|
||||
|
||||
try:
|
||||
put("api", staging)
|
||||
received = clients["worker"].get_object("messenger", staging)
|
||||
try:
|
||||
assert received.read() == b"Synthetic IAM probe"
|
||||
finally:
|
||||
received.close()
|
||||
received.release_conn()
|
||||
put("worker", derived)
|
||||
report["s3"] = {
|
||||
"api_staging_write": True,
|
||||
"worker_source_read": True,
|
||||
"worker_derived_write": True,
|
||||
"api_derived_write_denied": s3_denied(
|
||||
lambda: put("api", derived)
|
||||
),
|
||||
"worker_staging_write_denied": s3_denied(
|
||||
lambda: put("worker", staging)
|
||||
),
|
||||
"worker_list_all_buckets_denied": s3_denied(
|
||||
lambda: clients["worker"].list_buckets()
|
||||
),
|
||||
"worker_delete_denied": s3_denied(
|
||||
lambda: clients["worker"].remove_object(
|
||||
"messenger", derived
|
||||
)
|
||||
),
|
||||
}
|
||||
finally:
|
||||
for key in [staging, derived]:
|
||||
clients["reconciler"].remove_object("messenger", key)
|
||||
for pool in pools:
|
||||
pool.clear()
|
||||
report["complete"] = True
|
||||
finally:
|
||||
for key in [staging, derived]:
|
||||
clients["reconciler"].remove_object("messenger", key)
|
||||
for pool in pools:
|
||||
pool.clear()
|
||||
report["complete"] = True
|
||||
print(json.dumps(report))
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user