forked from mtusi2026/mtusi2026lab7
fix: address rotation-revocation verify findings
Close handshakes and logins that started before a revocation or a password change, converge after a failure in any phase, survive a closed terminal, lock parallel commands and make the drill detect a dead load. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,327 @@
|
||||
"""Тот же ли код в образе тега, что у реплик (change `rotation-revocation`,
|
||||
«Уточнения verify», W5): `infra/rotation/same_image.py` и его вызов из
|
||||
`scripts/rolling-update.sh` — на подставном docker. Настоящие образы — проба
|
||||
в `evidence/security/rotation-revocation.md`.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from src.config.settings import BASE_DIR
|
||||
|
||||
SCRIPT = BASE_DIR / "infra" / "rotation" / "same_image.py"
|
||||
ROLLOUT = BASE_DIR / "scripts" / "rolling-update.sh"
|
||||
|
||||
|
||||
def _load() -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location("same_image", SCRIPT)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules.setdefault("same_image", module)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
same_image = _load()
|
||||
|
||||
CONFIG: dict[str, Any] = {
|
||||
"User": "app",
|
||||
"Cmd": ["python", "-m", "src"],
|
||||
"Entrypoint": None,
|
||||
"WorkingDir": "/app",
|
||||
"ExposedPorts": {"8080/tcp": {}},
|
||||
"Healthcheck": {"Test": ["CMD", "python"], "Retries": 3},
|
||||
"Env": ["PATH=/usr/bin", "LANG=C"],
|
||||
"Labels": {"com.docker.compose.project": "one"},
|
||||
}
|
||||
FILES = {
|
||||
"app/src/main.py": (b"code", 0o644),
|
||||
"usr/bin/tool": (b"tool", 0o755),
|
||||
}
|
||||
|
||||
|
||||
def _archive(files: dict[str, tuple[bytes, int]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
with tarfile.open(fileobj=buffer, mode="w") as archive:
|
||||
folder = tarfile.TarInfo("app")
|
||||
folder.type = tarfile.DIRTYPE
|
||||
archive.addfile(folder)
|
||||
for name, (body, mode) in files.items():
|
||||
item = tarfile.TarInfo(name)
|
||||
item.size, item.mode = len(body), mode
|
||||
archive.addfile(item, io.BytesIO(body))
|
||||
link = tarfile.TarInfo("app/link")
|
||||
link.type, link.linkname = tarfile.SYMTYPE, "src"
|
||||
archive.addfile(link)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
class Docker:
|
||||
"""Образ тега, две реплики, модель compose; экспорт — архивы."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.image = dict(CONFIG)
|
||||
self.containers = {
|
||||
name: dict(
|
||||
CONFIG,
|
||||
Env=[*CONFIG["Env"], "APP__PORT=8080"],
|
||||
Labels={"com.docker.compose.project": "two"},
|
||||
)
|
||||
for name in ("one", "two")
|
||||
}
|
||||
mounted = {
|
||||
"app/config.toml": (b"", 0o644),
|
||||
"run/secrets/api.key": (b"", 0o600),
|
||||
"tmp/file": (b"x", 0o644),
|
||||
".dockerenv": (b"", 0o755),
|
||||
"etc/hostname": (b"one", 0o644),
|
||||
}
|
||||
self.trees = {
|
||||
"tag": dict(FILES),
|
||||
"one": {**FILES, **mounted},
|
||||
"two": {**FILES, **mounted},
|
||||
}
|
||||
self.removed: list[str] = []
|
||||
|
||||
def output(self, *args: str) -> str:
|
||||
if args[:2] == ("image", "inspect"):
|
||||
return json.dumps([{"Config": self.image}])
|
||||
if args[:2] == ("container", "inspect"):
|
||||
return json.dumps(
|
||||
[
|
||||
{
|
||||
"Config": self.containers[args[2]],
|
||||
"Mounts": [
|
||||
{"Destination": "/app/config.toml"},
|
||||
{"Destination": "/run/secrets/api.key"},
|
||||
],
|
||||
"HostConfig": {"Tmpfs": {"/tmp": "size=16m"}}, # noqa: S108
|
||||
},
|
||||
],
|
||||
)
|
||||
if args[0] == "create":
|
||||
assert "--network" in args
|
||||
assert args[-1] == "app:tag"
|
||||
return "tag\n"
|
||||
if args[0] == "rm":
|
||||
self.removed.append(args[-1])
|
||||
return ""
|
||||
assert args[:2] == ("compose", "config")
|
||||
model = {"services": {"api": {"environment": {"APP__PORT": "8080"}}}}
|
||||
return json.dumps(model)
|
||||
|
||||
def export(
|
||||
self,
|
||||
container: str,
|
||||
places: list[str],
|
||||
) -> dict[str, tuple[Any, ...]]:
|
||||
data = _archive(self.trees[container])
|
||||
with tarfile.open(fileobj=io.BytesIO(data), mode="r|") as stream:
|
||||
return dict(same_image.tree(stream, places))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def docker(monkeypatch: pytest.MonkeyPatch) -> Docker:
|
||||
made = Docker()
|
||||
monkeypatch.setattr(same_image, "output", made.output)
|
||||
monkeypatch.setattr(same_image, "export", made.export)
|
||||
return made
|
||||
|
||||
|
||||
ARGS = ["app:tag", "one", "two"]
|
||||
|
||||
|
||||
def test_same_code_of_another_project(docker: Docker) -> None:
|
||||
"""Сценарий «Пересборка другим проектом»: метки, переменные compose, точки
|
||||
монтирования и файлы Docker — не другой код; контейнер сравнения убран."""
|
||||
assert same_image.main(ARGS) == 0
|
||||
assert docker.removed == ["tag"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("field", "value"),
|
||||
[
|
||||
("User", "root"),
|
||||
("Cmd", ["python", "-m", "other"]),
|
||||
("Entrypoint", ["sh"]),
|
||||
("WorkingDir", "/"),
|
||||
("Healthcheck", {"Test": ["NONE"]}),
|
||||
("ExposedPorts", None),
|
||||
("StopSignal", "SIGKILL"),
|
||||
("Volumes", {"/data": {}}),
|
||||
("Shell", ["bash"]),
|
||||
],
|
||||
)
|
||||
def test_another_config(
|
||||
field: str,
|
||||
value: Any,
|
||||
docker: Docker,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
docker.image[field] = value
|
||||
assert same_image.main(ARGS) == 1
|
||||
assert field in capsys.readouterr().out
|
||||
assert docker.removed == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"env",
|
||||
[
|
||||
["PATH=/usr/bin", "LANG=C", "NEW=secret-value"],
|
||||
["PATH=/usr/bin", "LANG=secret-value"],
|
||||
["PATH=/usr/bin"],
|
||||
],
|
||||
)
|
||||
def test_another_environment(
|
||||
env: list[str],
|
||||
docker: Docker,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
docker.image["Env"] = env
|
||||
assert same_image.main(ARGS) == 1
|
||||
out = capsys.readouterr().out
|
||||
assert "another environment" in out
|
||||
assert "secret-value" not in out
|
||||
|
||||
|
||||
@pytest.mark.parametrize("replica", ["one", "two"])
|
||||
@pytest.mark.parametrize(
|
||||
("name", "entry"),
|
||||
[
|
||||
("app/src/main.py", (b"CODE", 0o644)),
|
||||
("app/src/main.py", (b"code", 0o755)),
|
||||
("etc/added", (b"x", 0o644)),
|
||||
("usr/bin/tool", None),
|
||||
],
|
||||
)
|
||||
def test_another_file(
|
||||
replica: str,
|
||||
name: str,
|
||||
entry: tuple[bytes, int] | None,
|
||||
docker: Docker,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Файл другого содержания (того же размера), прав, лишний и пропавший —
|
||||
у любой реплики и в любом месте, а не только в /app."""
|
||||
if entry is None:
|
||||
del docker.trees[replica][name]
|
||||
else:
|
||||
docker.trees[replica][name] = entry
|
||||
assert same_image.main(ARGS) == 1
|
||||
assert f"another /{name}" in capsys.readouterr().out
|
||||
assert docker.removed == ["tag"]
|
||||
|
||||
|
||||
def test_extra_file_of_the_tag(docker: Docker) -> None:
|
||||
docker.trees["tag"]["usr/bin/extra"] = (b"x", 0o755)
|
||||
assert same_image.main(ARGS) == 1
|
||||
|
||||
|
||||
def test_cannot_compare(
|
||||
docker: Docker,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
capsys: pytest.CaptureFixture[str],
|
||||
) -> None:
|
||||
"""Сравнить не удалось — код 2, а не «тот же»; контейнер убран."""
|
||||
|
||||
def export(_container: str, _places: list[str]) -> dict[str, Any]:
|
||||
raise same_image.Unknown("docker export failed")
|
||||
|
||||
monkeypatch.setattr(same_image, "export", export)
|
||||
assert same_image.main(ARGS) == 2 # noqa: PLR2004
|
||||
assert "docker export failed" in capsys.readouterr().out
|
||||
assert docker.removed == ["tag"]
|
||||
|
||||
|
||||
def _fake_docker(tmp_path: Path, body: str) -> dict[str, str]:
|
||||
folder = tmp_path / "bin"
|
||||
folder.mkdir()
|
||||
script = folder / "docker"
|
||||
script.write_text("#!/bin/sh\n" + body)
|
||||
script.chmod(0o755)
|
||||
return {**os.environ, "PATH": f"{folder}:{os.environ['PATH']}"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", ["exit 1\n", "exit 0\n", "echo garbage\n"])
|
||||
def test_export_must_succeed(
|
||||
body: str,
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Отказ docker и пустой или негодный архив — «сравнить не удалось»."""
|
||||
environment = _fake_docker(tmp_path, body)
|
||||
monkeypatch.setenv("PATH", environment["PATH"])
|
||||
with pytest.raises(same_image.Unknown):
|
||||
same_image.export("one", [])
|
||||
if body == "exit 1\n":
|
||||
with pytest.raises(same_image.Unknown):
|
||||
same_image.output("image", "inspect", "x")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("label", "compare", "code"),
|
||||
[
|
||||
("sha256:same", "raise SystemExit(9)", 0),
|
||||
("sha256:other", "raise SystemExit(0)", 0),
|
||||
("sha256:other", "print('another x'); raise SystemExit(1)", 2),
|
||||
("sha256:other", "raise SystemExit(2)", 2),
|
||||
],
|
||||
)
|
||||
def test_rollout_without_build(
|
||||
label: str,
|
||||
compare: str,
|
||||
code: int,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""`ROLLOUT_BUILD=0`: манифест тот же — не сравнивается; другой — решает
|
||||
`same_image.py`, и отказ или сбой сравнения — код 2 до изменений."""
|
||||
stat = "# pxname,svname,scur,status,addr\\n"
|
||||
rows = "".join(f"api,api-{n},0,UP,10.0.0.{n}:8080\\n" for n in range(1, 4))
|
||||
environment = _fake_docker(
|
||||
tmp_path,
|
||||
f"""case "$*" in
|
||||
*"show stat"*) printf '{stat}{rows}' ;;
|
||||
*"show servers state"*) echo "# srv_admin_state srv_name" ;;
|
||||
*"show info"*) echo Uptime ;;
|
||||
"compose ps"*) printf 'aaaa\\nbbbb\\n' ;;
|
||||
*NetworkSettings*aaaa) echo 10.0.0.1 ;;
|
||||
*NetworkSettings*bbbb) echo 10.0.0.2 ;;
|
||||
*Config.Image*) echo app:tag ;;
|
||||
version*) echo linux/arm64 ;;
|
||||
"image inspect"*) echo sha256:same ;;
|
||||
*com.docker.compose.image*) echo {label} ;;
|
||||
*) echo "unexpected: $*" >&2; exit 1 ;;
|
||||
esac
|
||||
""",
|
||||
)
|
||||
python = tmp_path / "python"
|
||||
python.write_text(f"#!{sys.executable}\n{compare}\n")
|
||||
python.chmod(0o755)
|
||||
result = subprocess.run( # noqa: S603
|
||||
[str(ROLLOUT)],
|
||||
env={
|
||||
**environment,
|
||||
"PYTHON": str(python),
|
||||
"API_REPLICAS": "2",
|
||||
"ROLLOUT_BUILD": "0",
|
||||
"ROLLOUT_MIGRATE": "0",
|
||||
"ROLLOUT_CHECK": "1",
|
||||
"ROLLOUT_COMMIT": "",
|
||||
},
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert result.returncode == code, result.stdout + result.stderr
|
||||
if code:
|
||||
assert "run make run_docker or make rolling_update" in result.stderr
|
||||
Reference in New Issue
Block a user