Files
mtusi2026lab7-fork/scripts/check_grade3_runtime.py
T

47 lines
2.6 KiB
Python

#!/usr/bin/env python3
"""Inspect runtime constraints without printing inspect output or secrets."""
import json
import subprocess
APP_ROLES = {"api", "worker", "dispatcher", "upload-cleanup"}
READ_ONLY = APP_ROLES | {"haproxy", "otel-collector", "prometheus", "loki", "tempo", "grafana"}
ALLOWED_PORTS = {("haproxy", "8443/tcp"), ("grafana", "3000/tcp"),
("openbao", "8200/tcp"), ("s3", "9000/tcp")}
def main():
ids = subprocess.check_output(["docker", "compose", "ps", "-q"], text=True).split()
assert ids, "No running Compose services"
services = json.loads(subprocess.check_output(["docker", "inspect", *ids], text=True))
for service in services:
name = service["Config"]["Labels"]["com.docker.compose.service"]
config = service["HostConfig"]
assert not config["Privileged"] and config["NetworkMode"] != "host", name
mounts = [mount["Destination"] for mount in service["Mounts"]]
assert not any("docker.sock" in path for path in mounts), name
for port, bindings in (config.get("PortBindings") or {}).items():
assert (name, port) in ALLOWED_PORTS, (name, port)
assert all(binding["HostIp"] == "127.0.0.1" for binding in bindings), name
if name in READ_ONLY:
assert config["ReadonlyRootfs"] and config["CapDrop"] == ["ALL"], name
assert "no-new-privileges:true" in config["SecurityOpt"], name
assert config["Memory"] > 0 and config["NanoCpus"] > 0, name
assert config["Tmpfs"], name
if name == "worker":
env = dict(item.split("=", 1) for item in service["Config"]["Env"] if "=" in item)
assert 0 < int(env["JOB_TIMEOUT_SECONDS"]) <= 60, name
assert config["Memory"] <= 512 * 1024 * 1024 and config["NanoCpus"] <= 10**9, name
if name in APP_ROLES:
assert service["Config"]["User"] == "app:app", name
assert config["CapDrop"] == ["ALL"] and not config["CapAdd"], name
assert config["Memory"] > 0 and config["NanoCpus"] > 0, name
assert config["ReadonlyRootfs"] and "/run/runtime-secrets" in config["Tmpfs"], name
assert not any(path.startswith("/run/secrets") for path in mounts), name
assert not any("BAO_TOKEN=" in field for field in service["Config"]["Env"]), name
assert APP_ROLES <= {svc["Config"]["Labels"]["com.docker.compose.service"] for svc in services}
print("PASS: local ports, read-only app/ingress/telemetry, no-new-privileges, dropped capabilities, worker CPU/RAM/time budget")
if __name__ == "__main__":
main()