Skeleton contracts / contracts (pull_request) Blocked by required conditions
226 lines
10 KiB
Python
226 lines
10 KiB
Python
#!/usr/bin/env python3
|
|
"""Authorization and TLS checks invoked by the operator in an isolated test container."""
|
|
|
|
from http.client import HTTPSConnection
|
|
import json
|
|
from pathlib import Path
|
|
import socket
|
|
import ssl
|
|
import struct
|
|
import sys
|
|
import time
|
|
|
|
CA = "/trust/ca.crt"
|
|
STREAM = "attachments:jobs:v1"
|
|
|
|
|
|
def check(condition, description):
|
|
if not condition:
|
|
raise AssertionError(description)
|
|
|
|
|
|
def context(role=None):
|
|
ctx = ssl.create_default_context(cafile=CA)
|
|
ctx.maximum_version = ssl.TLSVersion.TLSv1_2 # TLS alerts are observable before sending HTTP bodies.
|
|
if role == "gateway":
|
|
ctx.load_cert_chain("/identities/gateway/client.pem")
|
|
elif role:
|
|
identity = Path("/retired" if role == "retired" else f"/identities/{role}")
|
|
ctx.load_cert_chain(identity / "tls.crt", identity / "tls.key")
|
|
return ctx
|
|
|
|
|
|
def connect(host, port, role, ip=None, name=None):
|
|
sock = socket.create_connection((ip or host, port), timeout=4)
|
|
try:
|
|
return context(role).wrap_socket(sock, server_hostname=name or host)
|
|
except BaseException:
|
|
sock.close()
|
|
raise
|
|
|
|
|
|
def http(host, port, role, path, method="GET", data=None, headers=None, ip=None, name=None):
|
|
client = HTTPSConnection(host, port, timeout=4)
|
|
with connect(host, port, role, ip, name) as tls:
|
|
client.sock = tls
|
|
client.request(method, path, body=data, headers=headers or {})
|
|
result = client.getresponse()
|
|
return result.status, result.read()
|
|
|
|
|
|
def post(host, port, role, path, data=None, token=None):
|
|
headers = {"Content-Type": "application/json"}
|
|
if token:
|
|
headers["X-Vault-Token"] = token
|
|
return http(host, port, role, path, "POST", json.dumps(data or {}), headers)
|
|
|
|
|
|
def redis(role, port, user, password, commands):
|
|
def command(sock, inp, *args):
|
|
data = [str(arg).encode() for arg in args]
|
|
sock.sendall(b"*%d\r\n" % len(data) + b"".join(b"$%d\r\n%s\r\n" % (len(x), x) for x in data))
|
|
return inp.readline()
|
|
|
|
with connect("redis", port, role) as tls, tls.makefile("rb") as inp:
|
|
if user:
|
|
auth = command(tls, inp, "AUTH", user, password)
|
|
if auth != b"+OK\r\n":
|
|
return [auth]
|
|
return [command(tls, inp, *item) for item in commands]
|
|
|
|
|
|
def secret(role):
|
|
return Path(f"/bootstrap/{role}/REDIS_PASSWORD").read_text()
|
|
|
|
|
|
def rejected(name, probe):
|
|
try:
|
|
probe()
|
|
except ssl.SSLCertVerificationError:
|
|
raise AssertionError(f"{name}: client received invalid server cert")
|
|
except ssl.SSLError as error:
|
|
check("ALERT" in (error.reason or ""), f"{name}: unexpected TLS error {error.reason}")
|
|
print(f"PASS {name}: {error.reason}")
|
|
return
|
|
raise AssertionError(f"{name}: expected TLS alert")
|
|
|
|
|
|
def log_export():
|
|
def field(number, raw):
|
|
return bytes((number * 8 + 2, len(raw))) + raw
|
|
metadata = field(1, b"service.name") + field(2, field(1, b"lab7-tls-audit"))
|
|
resource = field(1, metadata)
|
|
record = b"\x09" + struct.pack("<Q", time.time_ns()) + field(5, field(1, b"synthetic TLS audit"))
|
|
return field(1, field(1, resource) + field(2, field(2, record)))
|
|
|
|
|
|
def check_matrix():
|
|
replicas = sorted({a[4][0] for a in socket.getaddrinfo("api", 8080, family=socket.AF_INET)})
|
|
check(len(replicas) == 2, "two active API replicas required")
|
|
for index, ip in enumerate(replicas, 1):
|
|
def api(role):
|
|
return http("api", 8080, role, "/health/ready", ip=ip)
|
|
check(api("gateway")[0] == 200, "gateway identity")
|
|
for role in (None, "foreign", "outsider", "worker"):
|
|
rejected(f"API {index} {role}", lambda: api(role))
|
|
print(f"PASS API {index}: gateway verified")
|
|
|
|
for role, port in (("api", 6380), ("worker", 6381)):
|
|
def broker(identity):
|
|
return redis(identity, port, role, secret(role), [("PING",)])
|
|
check(broker(role) == [b"+PONG\r\n"], "broker valid identity")
|
|
for invalid in (None, "foreign", "outsider", "worker" if role == "api" else "api"):
|
|
rejected(f"broker {port} {invalid}", lambda: broker(invalid))
|
|
|
|
for role in ("api", "worker", None, "foreign", "outsider"):
|
|
def ingest():
|
|
return post("collector", 44318, role, "/v1/traces")
|
|
if role in ("api", "worker"):
|
|
check(ingest()[0] == 200, "collector valid identity")
|
|
else:
|
|
rejected(f"collector {role}", ingest)
|
|
|
|
endpoints = [
|
|
("collector", 48888, "prometheus", "/metrics"),
|
|
("collector", 48889, "prometheus", "/metrics"),
|
|
("loki", 43102, "prometheus", "/metrics"),
|
|
("tempo", 43201, "prometheus", "/metrics"),
|
|
("prometheus", 49090, "grafana", "/api/v1/query?query=up"),
|
|
("loki", 43101, "grafana", "/loki/api/v1/labels"),
|
|
("tempo", 43200, "grafana", "/api/search"),
|
|
]
|
|
for host, port, identity, path in endpoints:
|
|
def query(role):
|
|
return http(host, port, role, path)
|
|
check(query(identity)[0] == 200, f"TLS {host}:{port} route")
|
|
rejected(f"{host}:{port} worker", lambda: query("worker"))
|
|
print(f"PASS {host}:{port} {identity}")
|
|
for host, port, route in (("loki", 43100, "/otlp/v1/logs"), ("tempo", 44318, "/v1/traces")):
|
|
status, _ = http(host, port, "collector", route, "POST", log_export() if host == "loki" else b"",
|
|
{"Content-Type": "application/x-protobuf"})
|
|
check(status in (200, 204), f"collector export {host}: HTTP {status}")
|
|
rejected(f"{host} ingest wrong identity", lambda: post(host, port, "grafana", route))
|
|
check(post("loki", 43101, "grafana", "/loki/api/v1/push")[0] == 403, "Grafana cannot push logs")
|
|
check(post("prometheus", 49090, "grafana", "/api/v1/write")[0] == 403, "Grafana cannot write metrics")
|
|
check(http("minio", 9000, None, "/minio/health/live")[0] == 200, "MinIO HTTPS")
|
|
check(http("minio", 9000, None, "/attachments")[0] == 403, "S3 anonymous denied")
|
|
check(http("grafana", 3000, None, "/api/user")[0] == 401, "Grafana requires user auth")
|
|
try:
|
|
http("gateway", 8443, None, "/health/live", name="missing-name.lab")
|
|
except ssl.SSLCertVerificationError:
|
|
print("PASS ingress hostname verification")
|
|
else:
|
|
raise AssertionError("ingress accepted mismatched SAN")
|
|
|
|
for host, port in (("redis", 6379), ("collector", 4318), ("loki", 3100),
|
|
("tempo", 4318), ("tempo", 3200), ("prometheus", 9090)):
|
|
try:
|
|
with socket.create_connection((host, port), timeout=2):
|
|
raise AssertionError(f"{host}:{port} loopback service accessible from network")
|
|
except ConnectionRefusedError:
|
|
print(f"PASS {host}:{port} local hop closed")
|
|
|
|
|
|
def bao_scope(expiry=False):
|
|
for role, other in (("worker", "api"), ("api", "worker")):
|
|
status, data = post("openbao", 8200, role, "/v1/auth/cert/login")
|
|
check(status == 200, f"{role} cert login")
|
|
auth = json.loads(data)["auth"]
|
|
token, ttl = auth["client_token"], auth["lease_duration"]
|
|
check(0 < ttl <= 30 and auth["policies"] == [role], "scoped short TTL")
|
|
headers = {"X-Vault-Token": token}
|
|
def read(path):
|
|
return http("openbao", 8200, role, "/v1/lab/data/" + path, headers=headers)[0]
|
|
check(read(role) == 200 and read(other) == 403, "role KV scoping")
|
|
check(post("openbao", 8200, role, "/v1/sys/policies/acl/canary", token=token)[0] == 403,
|
|
"role policy write denied")
|
|
if expiry and role == "worker":
|
|
time.sleep(ttl + 2)
|
|
check(read(role) == 403, "working token is denied after expiry")
|
|
print(f"PASS OpenBao token expiry ({ttl}s)")
|
|
else:
|
|
check(post("openbao", 8200, role, "/v1/auth/token/revoke-self", token=token)[0] == 204,
|
|
"self-revocation")
|
|
check(read(role) == 403, "revoked token")
|
|
print(f"PASS OpenBao {role} own KV allowed, peer KV and policy write denied")
|
|
check(post("openbao", 8200, "outsider", "/v1/auth/cert/login")[0] in (400, 403), "unregistered leaf denied")
|
|
|
|
|
|
def worker_scope():
|
|
def worker(*ops):
|
|
return redis("worker", 6381, "worker", secret("worker"), ops)[0]
|
|
allow = worker(("XREADGROUP", "GROUP", "image-workers-v1", "scope-audit", "COUNT", 1,
|
|
"STREAMS", STREAM, "0"))
|
|
check(allow.startswith(b"*"), "consume existing stream authorized")
|
|
for operation in (("GET", "session:synthetic"), ("XADD", STREAM, "*", "job", "synthetic"),
|
|
("XREADGROUP", "GROUP", "image-workers-v1", "scope-audit",
|
|
"STREAMS", "unrelated:stream", "0"), ("FLUSHALL",)):
|
|
check(worker(operation).startswith(b"-NOPERM"), f"deny {operation[0]} outside worker scope")
|
|
print("PASS worker can consume queue; publish, foreign queue, sessions and FLUSHALL denied")
|
|
|
|
|
|
def reload_redis():
|
|
result = redis("operator", 6382, "operator", secret("operator"),
|
|
[("ACL", "LOAD"), ("CLIENT", "KILL", "USER", "worker")])
|
|
check(result[0] == b"+OK\r\n" and result[1].startswith(b":"), "reload and disconnect worker")
|
|
|
|
|
|
def audit_rotation():
|
|
old = Path("/retired/REDIS_PASSWORD").read_text()
|
|
def connect_redis(cert, password):
|
|
return redis(cert, 6381, "worker", password, [("PING",)])
|
|
rejected("retired worker / broker", lambda: connect_redis("retired", old))
|
|
rejected("retired worker / Collector",
|
|
lambda: post("collector", 44318, "retired", "/v1/traces"))
|
|
check(post("openbao", 8200, "retired", "/v1/auth/cert/login")[0] in (400, 403),
|
|
"retired worker identity denied by Bao")
|
|
check(connect_redis("worker", old)[0].startswith(b"-WRONGPASS"), "old password cannot use new identity")
|
|
check(connect_redis("worker", secret("worker")) == [b"+PONG\r\n"], "new identity and secret valid")
|
|
print("PASS renewed leaf, retired identity denied on three channels, old password rejected")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
actions = {"matrix": check_matrix, "bao": bao_scope, "bao-expiry": lambda: bao_scope(True),
|
|
"worker": worker_scope, "redis-reload": reload_redis, "rotation": audit_rotation}
|
|
actions[sys.argv[1]]()
|