forked from mtusi2026/mtusi2026lab4
209 lines
11 KiB
Python
209 lines
11 KiB
Python
"""Regression checks for false-positive paths in the student test runner."""
|
|
import contextlib
|
|
import io
|
|
import json
|
|
from pathlib import Path
|
|
import tempfile
|
|
import subprocess
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
import run
|
|
import s3_infrastructure
|
|
|
|
|
|
class HarnessTests(unittest.TestCase):
|
|
def test_s3_cleanup_continues_after_error_and_never_removes_application_bucket(self):
|
|
stack = s3_infrastructure.Stack("highload-lab4", self.evidence())
|
|
results = [subprocess.CompletedProcess([], 1, b"", b"AccessDenied")] + [
|
|
subprocess.CompletedProcess([], 0, b"", b"") for _ in range(4)]
|
|
with patch.object(stack, "client", side_effect=results) as client:
|
|
with self.assertRaises(run.Failure):
|
|
stack.cleanup()
|
|
self.assertEqual(client.call_count, 5)
|
|
for call in client.call_args_list:
|
|
self.assertNotIn("bucket remove root/messenger-attachments", call.args[0])
|
|
|
|
def test_s3_policy_rejects_broad_or_inherited_grants(self):
|
|
bucket = "arn:aws:s3:::messenger-attachments"
|
|
user = {"status": "enabled", "policies": [s3_infrastructure.POLICY], "memberOf": []}
|
|
document = {"Version": "2012-10-17", "Statement": [
|
|
{"Effect": "Allow", "Action": ["s3:ListBucket", "s3:GetBucketLocation"], "Resource": [bucket]},
|
|
{"Effect": "Allow", "Action": ["s3:PutObject", "s3:GetObject", "s3:DeleteObject"], "Resource": [bucket + "/*"]}]}
|
|
envelope = {"policy": {"policy": document}}
|
|
s3_infrastructure.validate_api_policy(user, envelope)
|
|
for defect in ("admin", "other_bucket", "group"):
|
|
changed_user, changed = json.loads(json.dumps(user)), json.loads(json.dumps(envelope))
|
|
if defect == "admin":
|
|
changed["policy"]["policy"]["Statement"][0]["Action"].append("admin:*")
|
|
elif defect == "other_bucket":
|
|
changed["policy"]["policy"]["Statement"][1]["Resource"] = ["arn:aws:s3:::*/*"]
|
|
else:
|
|
changed_user["memberOf"] = ["unexpected-group"]
|
|
with self.assertRaises(run.Failure):
|
|
s3_infrastructure.validate_api_policy(changed_user, changed)
|
|
|
|
def test_missing_s3_infrastructure_emits_no_success_hook_json(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
args = ["s3_infrastructure.py", "--project", "highload-lab4", "--as-hook", "--output", directory]
|
|
output, errors = io.StringIO(), io.StringIO()
|
|
with patch("sys.argv", args), patch.object(s3_infrastructure, "Stack") as stack, \
|
|
patch.object(s3_infrastructure, "topology", side_effect=run.Pending("no Docker")), \
|
|
contextlib.redirect_stdout(output), contextlib.redirect_stderr(errors):
|
|
stack.return_value.wait_s3.side_effect = run.Pending("no Docker")
|
|
code = s3_infrastructure.main()
|
|
self.assertEqual(code, 2)
|
|
self.assertEqual(output.getvalue(), "")
|
|
summary = json.loads((Path(directory) / "summary.json").read_text())
|
|
self.assertTrue(all(case["status"] == "PENDING_INFRA" for case in summary.values()))
|
|
|
|
def test_s3_network_failure_is_not_permission_denial(self):
|
|
for data in (b"connection refused", b"unrecognized subcommand", b"NoSuchBucket"):
|
|
self.assertFalse(s3_infrastructure.denied(subprocess.CompletedProcess([], 1, b"", data)))
|
|
self.assertFalse(s3_infrastructure.denied(subprocess.CompletedProcess([], 0, b"AccessDenied", b"")))
|
|
self.assertTrue(s3_infrastructure.denied(subprocess.CompletedProcess([], 1, b"", b'{"error":"AccessDenied (403)"}')))
|
|
|
|
def test_s3_rejects_unrelated_compose_project(self):
|
|
with self.assertRaises(run.Failure):
|
|
s3_infrastructure.Stack("highload-lab3", self.evidence())
|
|
|
|
def test_attachment_uuid_response_check_preserves_identity_and_order(self):
|
|
first = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"
|
|
second = "bbbbbbbb-cccc-4ddd-8eee-ffffffffffff"
|
|
body = {"text": "", "attachment_ids": [first.upper(), second.upper()]}
|
|
actor, chat = {"id": "actor"}, {"id": "chat"}
|
|
|
|
class Client:
|
|
def __init__(self, ids):
|
|
self.ids = ids
|
|
|
|
def call(self, *args, **kwargs):
|
|
return {"json": {"chat_id": "chat", "sender_id": "actor", "text": "", "attachment_ids": self.ids}}
|
|
|
|
run.post(Client([first, second]), actor, chat, body, "key")
|
|
for invalid in ([second, first], [first], [first, first]):
|
|
with self.assertRaises(run.Failure):
|
|
run.post(Client(invalid), actor, chat, body, "key")
|
|
|
|
def evidence(self):
|
|
temp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(temp.cleanup)
|
|
return run.Evidence(temp.name)
|
|
|
|
def test_pending_and_failure_never_produce_success_exit(self):
|
|
for exception, expected in [(run.Pending("LB absent"), "PENDING_INFRA"),
|
|
(run.Failure("contract mismatch"), "FAIL")]:
|
|
ev = self.evidence()
|
|
def action():
|
|
raise exception
|
|
with contextlib.redirect_stdout(io.StringIO()):
|
|
ev.case("example", action)
|
|
self.assertEqual(ev.finish(), 1)
|
|
self.assertEqual(ev.summary["example"]["status"], expected)
|
|
|
|
def test_output_reuse_does_not_overwrite_raw_results(self):
|
|
ev = self.evidence()
|
|
ev.record("original")
|
|
with self.assertRaises(ValueError):
|
|
run.Evidence(ev.directory)
|
|
self.assertEqual(json.loads(ev.path.read_text())["event"], "original")
|
|
|
|
def test_fault_needs_both_injection_and_restoration(self):
|
|
with self.assertRaises(run.Pending):
|
|
run.require_hooks({"hooks": {"make_unready": ["inject"]}}, "make_unready", "restore_ready")
|
|
|
|
def test_credential_bearing_or_non_origin_urls_are_rejected(self):
|
|
for url in ["http://alice:secret@localhost:8080", "http://localhost:8080/path",
|
|
"http://localhost:8080?token=secret", "http://localhost:8080#fragment"]:
|
|
with self.assertRaises(run.Failure):
|
|
run.client_for({"base_url": url})
|
|
|
|
def snapshots(self):
|
|
before, after = {}, {}
|
|
for name in ["api", "postgres", "redis", "s3", "lb", "migrate"]:
|
|
value = {"id": name + "-id", "started_at": "before", "volumes": [name + "-data"], "running": True}
|
|
before[name] = [value]
|
|
after[name] = [{**value, "started_at": "before" if name == "migrate" else "after"}]
|
|
return before, after
|
|
|
|
def test_restart_rejects_noop_store_and_volume_loss(self):
|
|
for defect in ["no_restart", "volume_loss", "migrate_reran"]:
|
|
before, after = self.snapshots()
|
|
if defect == "no_restart":
|
|
after["s3"][0]["started_at"] = "before"
|
|
elif defect == "volume_loss":
|
|
after["postgres"][0]["volumes"] = []
|
|
else:
|
|
after["migrate"][0]["started_at"] = "after"
|
|
with self.assertRaises(run.Failure):
|
|
run.verify_restart(before, after, self.evidence())
|
|
|
|
def test_restart_accepts_observed_process_transition(self):
|
|
run.verify_restart(*self.snapshots(), self.evidence())
|
|
|
|
def events(self):
|
|
return {"capture_started_before_stack": True, "events": [
|
|
{"service": "migrate", "action": "start", "container_id": "m", "time_ns": 1},
|
|
{"service": "migrate", "action": "die", "container_id": "m", "time_ns": 2, "exit_code": 0},
|
|
{"service": "api", "action": "start", "container_id": "a", "time_ns": 3},
|
|
{"service": "api", "action": "start", "container_id": "b", "time_ns": 4}]}
|
|
|
|
def test_migration_summary_without_raw_events_is_rejected(self):
|
|
with self.assertRaises(run.Failure):
|
|
run.validate_migration_events({"migration_starts": 1, "migration_exit_code": 0})
|
|
|
|
def test_duplicate_migration_or_early_api_is_rejected(self):
|
|
for defect in ["duplicate", "early_api", "failed_exit", "capture_too_late"]:
|
|
value = self.events()
|
|
if defect == "duplicate":
|
|
value["events"].append(dict(value["events"][0]))
|
|
elif defect == "early_api":
|
|
value["events"][2]["time_ns"] = 1
|
|
elif defect == "failed_exit":
|
|
value["events"][1]["exit_code"] = 1
|
|
else:
|
|
value["capture_started_before_stack"] = False
|
|
with self.assertRaises(run.Failure):
|
|
run.validate_migration_events(value)
|
|
|
|
def test_one_successful_migration_before_two_apis_is_accepted(self):
|
|
run.validate_migration_events(self.events())
|
|
|
|
def test_rolling_summary_needs_nonoverlapping_real_container_steps(self):
|
|
with self.assertRaises(run.Failure):
|
|
run.validate_rolling_steps({"replaced_processes": 2, "min_ready_during_update": 1}, {"a", "b"}, {"c", "d"})
|
|
value = {"steps": [
|
|
{"old_id": "a", "new_id": "c", "begin_ns": 1, "end_ns": 3, "ready_survivor_ids": ["b"]},
|
|
{"old_id": "b", "new_id": "d", "begin_ns": 4, "end_ns": 6, "ready_survivor_ids": ["c"]}]}
|
|
run.validate_rolling_steps(value, {"a", "b"}, {"c", "d"})
|
|
value["steps"][1]["begin_ns"] = 2
|
|
with self.assertRaises(run.Failure):
|
|
run.validate_rolling_steps(value, {"a", "b"}, {"c", "d"})
|
|
|
|
def test_adapters_cannot_return_only_pass_true(self):
|
|
for name in ["attachment_compensation", "attachment_parallel_memory", "attachment_bucket_security",
|
|
"attachment_s3_failure", "attachment_pixels_limit"]:
|
|
with self.assertRaises(run.Failure):
|
|
run.validate_attachment_observations(name, {"pass": True})
|
|
|
|
def test_load_history_rejects_duplicates_and_lost_confirmations(self):
|
|
result = {"_attempted_texts": {"a", "b"}, "_confirmed_texts": {"a"}}
|
|
for messages in [[{"text": "a"}, {"text": "a"}], [{"text": "b"}]]:
|
|
with patch.object(run, "history", return_value=messages), self.assertRaises(run.Failure):
|
|
run.verify_load_history(None, None, None, result)
|
|
|
|
def test_public_lb_check_rejects_direct_api_port_binding(self):
|
|
def identifiers(_config, service, all_containers=False):
|
|
return [service]
|
|
def inspect(identifier):
|
|
if identifier == "lb":
|
|
return {"NetworkSettings": {"Ports": {"8080/tcp": [{"HostPort": "8080", "HostIp": "127.0.0.1"}]}}}
|
|
return {"HostConfig": {"PortBindings": {"8080/tcp": [{"HostPort": "8081"}]}}}
|
|
with patch.object(run, "compose_ids", identifiers), patch.object(run, "inspect_container", inspect):
|
|
with self.assertRaises(run.Failure):
|
|
run.public_endpoint({"base_url": "http://localhost:8080"}, self.evidence())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|