Files
mtusi2026lab4/student-tests/lab4/s3_infrastructure.py

366 lines
21 KiB
Python

#!/usr/bin/env python3
"""Runtime S3 checks for an explicitly selected synthetic Compose project.
Reuses lab4 Evidence/Client. Secrets stay in the existing one-shot client's
secret mounts; raw rc output (which may contain account IDs) is never saved.
"""
import argparse
import base64
import contextlib
import hashlib
import io
import json
import os
from pathlib import Path
import re
import shlex
import subprocess
import sys
import time
import uuid
import run as checks
BUCKET = "messenger-attachments"
POLICY = "messenger-attachments-api-v1"
def validate_api_policy(user, envelope):
"""Validate actual attached grants, including absence of inherited groups."""
checks.check(user.get("status") == "enabled" and user.get("policies") == [POLICY] and
user.get("memberOf") == [], "API identity has unexpected policies/groups or is disabled")
document = envelope.get("policy", {}).get("policy", {})
checks.check(isinstance(document, dict) and document.get("Version") == "2012-10-17",
"runtime policy document missing")
granted = set()
for statement in document.get("Statement", []):
checks.check(statement.get("Effect") == "Allow" and "NotAction" not in statement and
"NotResource" not in statement, "unexpected policy statement")
actions, resources = statement.get("Action"), statement.get("Resource")
actions = [actions] if isinstance(actions, str) else actions
resources = [resources] if isinstance(resources, str) else resources
checks.check(isinstance(actions, list) and isinstance(resources, list), "policy grant arrays missing")
granted.update((action, resource) for action in actions for resource in resources)
bucket = "arn:aws:s3:::" + BUCKET
expected = {("s3:ListBucket", bucket), ("s3:GetBucketLocation", bucket),
("s3:PutObject", bucket + "/*"), ("s3:GetObject", bucket + "/*"),
("s3:DeleteObject", bucket + "/*")}
checks.check(granted == expected, "API policy contains unexpected IAM/admin/bucket grants")
return [{"action": action, "resource": resource} for action, resource in sorted(granted)]
def denied(result):
"""A network/CLI error must never pass as an authorization denial."""
text = result.stdout + result.stderr
return result.returncode != 0 and bool(re.search(rb"access.?denied|\b403\b|\bforbidden\b", text, re.I))
class Stack:
def __init__(self, project, evidence):
if project != "highload-lab4" and not re.fullmatch(r"lab4-(s3-test|final)-[a-z0-9-]+", project):
raise checks.Failure("use highload-lab4 or an isolated lab4-s3-test-* or lab4-final-* project")
self.project, self.evidence = project, evidence
self.base = ["docker", "compose", "--project-name", project]
self.nonce = uuid.uuid4().hex
self.prefix = "student-tests/s3-" + self.nonce + "/"
self.key = "roundtrip-" + self.nonce + ".bin"
self.control = "student-control-" + self.nonce
self.forbidden = "student-forbidden-" + self.nonce
self.payload = bytes(range(256)) * 257 + self.nonce.encode()
self.digest = hashlib.sha256(self.payload).hexdigest()
self.failures, self.bootstrap_runs = [], 0
def execute(self, argv, input=None, timeout=30):
try:
return subprocess.run(argv, input=input, cwd=checks.ROOT, capture_output=True,
timeout=timeout, check=False)
except (OSError, subprocess.TimeoutExpired) as exc:
raise checks.Failure("test command unavailable/timed out: " + type(exc).__name__) from None
def docker_json(self, argv):
result = self.execute(argv)
if result.returncode:
raise checks.Pending("Docker inspection unavailable for selected project")
return json.loads(result.stdout)
def containers(self, service):
result = self.execute(self.base + ["ps", "-aq", service])
if result.returncode:
raise checks.Pending("Docker Compose inspection unavailable")
values = []
for identifier in result.stdout.decode().split():
value = self.docker_json(["docker", "inspect", identifier])[0]
labels = value["Config"].get("Labels", {})
checks.check(labels.get("com.docker.compose.project") == self.project and
labels.get("com.docker.compose.service") == service, "container ownership mismatch")
values.append(value)
checks.check(values, "selected project has no " + service + " container")
return values
def s3(self):
values = self.containers("s3")
checks.check(len(values) == 1, "expected one owned RustFS container")
return values[0]
@staticmethod
def snapshot(value):
return {"id": value["Id"], "started_at": value["State"]["StartedAt"],
"image": value["Config"]["Image"], "running": value["State"]["Running"],
"volumes": checks.volume_names(value)}
def client(self, command, root=False, payload=False):
# Only allow generated bucket/key paths and fixed argv. No credentials
# enter host Python variables, command arguments or evidence files.
setup = '''set -eu
rc=/usr/bin/rc
app_key=$(cat /run/secrets/s3_access_key_id)
app_secret=$(cat /run/secrets/s3_secret_access_key)
root_key=$(cat /run/secrets/rustfs_root_access_key)
root_secret=$(cat /run/secrets/rustfs_root_secret_key)
test "$app_key" != "$root_key"
"$rc" alias set app http://s3:9000 "$app_key" "$app_secret" --region us-east-1 --bucket-lookup path >/dev/null 2>&1
'''
if root:
setup += '"$rc" alias set root http://s3:9000 "$root_key" "$root_secret" --region us-east-1 --bucket-lookup path >/dev/null 2>&1\n'
if payload:
setup += "printf '%s' " + shlex.quote(base64.b64encode(self.payload).decode()) + " | base64 -d > /tmp/source\n"
result = self.execute(self.base + ["run", "--rm", "--no-deps", "-T", "--entrypoint", "/bin/sh", "s3-init", "-s"],
input=(setup + command + "\n").encode(), timeout=40)
return result
def rc(self, args, *, root=False, payload=False, expect_denied=False, label):
command = '"$rc" --json ' + shlex.join(args)
result = self.client(command, root=root, payload=payload)
refusal = denied(result)
self.evidence.record("s3_operation", operation=label, exit_code=result.returncode,
authorization_denied=refusal,
s3_error_code="AccessDenied" if refusal else None)
checks.check(refusal if expect_denied else result.returncode == 0,
label + (": expected S3 authorization denial" if expect_denied else ": S3 operation failed"))
return result
def verify_download(self, label):
command = '"$rc" --json object copy ' + shlex.quote("app/" + BUCKET + "/" + self.prefix + self.key) + ''' /tmp/received >/dev/null 2>&1
cmp /tmp/source /tmp/received
sha256sum /tmp/received
'''
result = self.client(command, payload=True)
digest = result.stdout.decode(errors="replace").split()[0] if result.stdout.strip() else ""
checks.check(result.returncode == 0 and digest == self.digest,
label + ": downloaded bytes differ or GET failed")
self.evidence.record("s3_roundtrip", phase=label, byte_equal=True, size_bytes=len(self.payload), sha256=digest)
def unsigned(self, path):
result = self.execute(self.base + ["exec", "-T", "s3", "curl", "-sS", "--max-time", "5",
"-o", "/dev/null", "-w", "%{http_code}", "http://127.0.0.1:9000/" + path])
checks.check(result.returncode == 0 and re.fullmatch(rb"\d{3}", result.stdout), "unsigned HTTP probe failed")
return int(result.stdout)
def wait_s3(self):
deadline = time.monotonic() + 60
while time.monotonic() < deadline:
value = self.s3()
if value["State"]["Running"] and value["State"].get("Health", {}).get("Status") == "healthy":
return value
time.sleep(.5)
raise checks.Failure("RustFS did not regain Docker health in 60 seconds")
def bootstrap(self):
# Reuses the actual bootstrap mounted by the existing service. Does not
# recreate API/DB, alter Compose or delete/recreate the RustFS volume.
for _ in range(2):
before = self.snapshot(self.s3())
result = self.execute(self.base + ["run", "--rm", "--no-deps", "-T", "s3-init"], timeout=45)
self.evidence.record("s3_bootstrap", attempt=self.bootstrap_runs + 1, exit_code=result.returncode)
checks.check(result.returncode == 0, "repeated real bootstrap failed")
self.bootstrap_runs += 1
checks.check(self.snapshot(self.s3()) == before, "bootstrap replaced/restarted RustFS or changed its volume")
self.verify_download("bootstrap_" + str(self.bootstrap_runs))
def restart(self):
before = self.snapshot(self.s3())
started = time.monotonic()
result = self.execute(self.base + ["restart", "--no-deps", "--timeout", "20", "s3"], timeout=35)
checks.check(result.returncode == 0, "RustFS restart command failed")
after = self.snapshot(self.wait_s3())
checks.check(before["id"] == after["id"] and before["volumes"] == after["volumes"] and
before["volumes"] and before["started_at"] != after["started_at"],
"restart did not preserve the real container/volume or restart its process")
self.evidence.record("s3_restart", before=before, after=after, ready_seconds=round(time.monotonic() - started, 3))
self.verify_download("after_restart")
def permissions(self):
target = "app/" + BUCKET + "/" + self.prefix
listing = self.rc(["bucket", "list", target], label="api_list_allowed_bucket")
checks.check(self.key.encode() in listing.stdout, "API LIST did not include its uploaded object")
# A real second bucket and known root-written sentinel distinguish a
# policy denial from a nonexistent bucket/object and network failures.
self.rc(["bucket", "create", "root/" + self.control], root=True, label="prepare_control_bucket")
self.rc(["object", "copy", "/tmp/source", "root/" + self.control + "/sentinel.bin"],
root=True, payload=True, label="prepare_control_object")
for label, args in [
("api_other_bucket_put", ["object", "copy", "/tmp/source", "app/" + self.control + "/api-write.bin"]),
("api_other_bucket_get", ["object", "copy", "app/" + self.control + "/sentinel.bin", "/tmp/received"]),
("api_other_bucket_delete", ["object", "remove", "app/" + self.control + "/sentinel.bin"]),
("api_other_bucket_list", ["bucket", "list", "app/" + self.control]),
("api_create_bucket", ["bucket", "create", "app/" + self.forbidden]),
("api_iam_user_list", ["admin", "user", "list", "app/"]),
("api_iam_policy_list", ["admin", "policy", "ls", "app/"]),
]:
try:
self.rc(args, payload=True, expect_denied=True, label=label)
except checks.Failure as exc:
# Probe every boundary even if one permission is too broad.
self.failures.append(str(exc))
checks.check(not self.failures, "; ".join(self.failures))
def private_bucket(self):
self.anonymous_get = self.unsigned(BUCKET + "/" + self.prefix + self.key)
self.anonymous_list = self.unsigned(BUCKET + "?list-type=2")
self.evidence.record("s3_unsigned", object_get_status=self.anonymous_get, bucket_list_status=self.anonymous_list)
checks.check(self.anonymous_get == 403 and self.anonymous_list == 403,
"known existing object and bucket must return HTTP 403 without a signature")
def effective_policy(self):
# The user-info response contains an access key. Keep it only in memory;
# save the validated grants, never the original response/account fields.
user = self.client('"$rc" --json admin user info root/ "$app_key"', root=True)
policy = self.client('"$rc" --json admin policy info root/ ' + POLICY, root=True)
checks.check(user.returncode == policy.returncode == 0, "cannot read actual API policy binding")
try:
grants = validate_api_policy(json.loads(user.stdout), json.loads(policy.stdout))
except ValueError:
raise checks.Failure("runtime IAM evidence was not valid JSON") from None
self.evidence.record("s3_effective_policy", policy_name=POLICY, inherited_groups=0, grants=grants,
root_credentials_distinct=True, iam_admin_grants=0)
def console(self):
raw = self.s3()
networks = list(raw.get("NetworkSettings", {}).get("Networks", {}))
checks.check(len(networks) == 1, "select a single shared Compose network for the console probe")
network = networks[0]
labels = self.docker_json(["docker", "network", "inspect", network])[0].get("Labels", {})
checks.check(labels.get("com.docker.compose.project") == self.project, "network ownership mismatch")
base = ["docker", "run", "--rm", "--pull=never", "--network", network, "--read-only", "--cap-drop", "ALL",
"--security-opt", "no-new-privileges:true", "--entrypoint", "curl", raw["Config"]["Image"],
"-sS", "--connect-timeout", "2", "--max-time", "3", "-o", "/dev/null", "-w", "%{http_code}"]
control = self.execute(base + ["http://s3:9000/health/ready"])
checks.check(control.returncode == 0 and control.stdout == b"200", "shared-network control probe failed")
result = self.execute(base + ["http://s3:9001/"])
self.evidence.record("s3_console", control_status=200, console_curl_exit=result.returncode,
console_http_status=result.stdout.decode(errors="replace")[:3])
checks.check(result.returncode == 7 and result.stdout == b"000", "console accepts connections on shared network")
def delete_probe(self):
path = "app/" + BUCKET + "/" + self.prefix + self.key
self.rc(["object", "remove", path], label="api_delete_allowed_object")
listing = self.rc(["bucket", "list", "app/" + BUCKET + "/" + self.prefix], label="api_list_after_delete")
checks.check(self.key.encode() not in listing.stdout, "API DELETE left its known object present")
def cleanup(self):
# Fixed generated paths only. Never recursive-delete the application
# bucket, remove volumes, reset IAM or touch pre-existing objects.
commands = [
["object", "remove", "root/" + BUCKET + "/" + self.prefix + self.key],
["object", "remove", "root/" + self.control + "/sentinel.bin"],
["object", "remove", "root/" + self.control + "/api-write.bin"],
["bucket", "remove", "root/" + self.control],
["bucket", "remove", "root/" + self.forbidden],
]
errors = []
for args in commands:
try:
result = self.client('"$rc" --json ' + shlex.join(args), root=True)
# Missing generated objects/buckets are normal after an expected
# denial; any other error is retained while cleanup continues.
missing = bool(re.search(rb"nosuchkey|nosuchbucket|not.?found|\b404\b|does not exist", result.stdout + result.stderr, re.I))
self.evidence.record("s3_cleanup", operation=" ".join(args[:2]), target=args[-1],
exit_code=result.returncode, already_absent=missing)
checks.check(result.returncode == 0 or missing, "could not clean generated S3 fixture")
except checks.Failure as exc:
errors.append(str(exc))
checks.check(not errors, "; ".join(errors))
def topology(stack, base_url, evidence):
apis, lbs = stack.containers("api"), stack.containers("lb")
checks.check(len(apis) >= 2 and len(lbs) == 1, "expected >=2 API containers behind one LB")
for raw in apis:
checks.check(raw["State"]["Running"] and raw["State"].get("Health", {}).get("Status") == "healthy",
"API is not healthy")
checks.check(not any((raw["HostConfig"].get("PortBindings") or {}).values()), "API has a direct host port")
config = {"base_url": base_url, "compose_base_argv": stack.base, "api_services": ["api"], "lb_services": ["lb"]}
# Bind the check to this explicit project; common inspection defaults would
# otherwise risk probing the concurrently running lab3 stack on port 8080.
checks.public_endpoint(config, evidence)
client = checks.client_for(config)
if not hasattr(stack, "actor"):
stack.actor = client.user("s3infra")
actor = stack.actor
aliases = checks.observe_instances(client, actor, count=32)
expected = {raw["Config"]["Hostname"] for raw in apis}
checks.check(set(aliases) == expected, "same token did not traverse every actual API replica")
evidence.record("s3_api_topology", api_ids=sorted(raw["Id"] for raw in apis), observed_instances=aliases,
lb_id=lbs[0]["Id"], lb_image=lbs[0]["Config"]["Image"], same_token=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--project", required=True)
parser.add_argument("--base-url", default="http://127.0.0.1:8081")
parser.add_argument("--output")
parser.add_argument("--as-hook", action="store_true", help="emit only the existing attachment_bucket_security observation JSON")
args = parser.parse_args()
directory = args.output or os.environ.get("STUDENT_TEST_EVIDENCE_DIR")
if not directory:
if not args.as_hook:
parser.error("--output is required outside hook mode")
directory = checks.ROOT / "student-tests/results" / ("s3-" + uuid.uuid4().hex)
evidence = checks.Evidence(directory)
stack = Stack(args.project, evidence)
def execute():
ready = stack.wait_s3()
evidence.record("s3_initial", **stack.snapshot(ready), project=args.project,
payload_size_bytes=len(stack.payload), payload_sha256=stack.digest,
fixture_prefix=stack.prefix, control_bucket=stack.control, create_probe_bucket=stack.forbidden)
checks.check(checks.volume_names(ready), "RustFS has no persistent named volume")
try:
stack.rc(["object", "copy", "/tmp/source", "app/" + BUCKET + "/" + stack.prefix + stack.key],
payload=True, label="api_put_allowed_object")
stack.verify_download("before_bootstrap")
evidence.case("s3_bootstrap_preserves_object_and_volume", stack.bootstrap)
evidence.case("s3_restart_preserves_original_bytes", stack.restart)
evidence.case("s3_unsigned_known_object_403", stack.private_bucket)
evidence.case("s3_api_bucket_scope_and_iam_denials", stack.permissions)
evidence.case("s3_api_effective_policy", stack.effective_policy)
evidence.case("s3_console_closed_on_shared_network", stack.console)
evidence.case("s3_api_delete_effect", stack.delete_probe)
evidence.case("s3_two_replicas_after_restart", lambda: topology(stack, args.base_url, evidence))
finally:
evidence.case("s3_fixture_cleanup", stack.cleanup)
failed = [name for name, value in evidence.summary.items() if value["status"] == "FAIL"]
pending = [name for name, value in evidence.summary.items() if value["status"] == "PENDING_INFRA"]
checks.check(not failed, "S3 cases failed: " + ", ".join(failed))
if pending:
raise checks.Pending("S3 cases pending: " + ", ".join(pending))
capture = io.StringIO()
with contextlib.redirect_stdout(capture if args.as_hook else sys.stdout):
evidence.case("s3_two_replicas_before", lambda: topology(stack, args.base_url, evidence))
evidence.case("s3_setup_and_scenarios", execute)
code = evidence.finish()
if code and all(value["status"] != "FAIL" for value in evidence.summary.values()):
code = 2 # PENDING_INFRA is distinct from a failed capability check.
if args.as_hook:
if code:
print("S3 checks incomplete/failed; inspect " + str(evidence.directory / "summary.json"), file=sys.stderr)
else:
print(json.dumps({"bootstrap_runs": stack.bootstrap_runs, "bucket_survived_second_bootstrap": True,
"anonymous_get_status": stack.anonymous_get, "anonymous_list_status": stack.anonymous_list,
"api_credentials_are_admin": False, "api_can_administer_other_buckets": False,
"console_reachable_from_shared_network": False}))
return code
if __name__ == "__main__":
raise SystemExit(main())