forked from mtusi2026/mtusi2026lab7
Name only the repeat of rotate_secret while sessions of the previous PostgreSQL password may stay open, compare KV version time with the container start when the load record is gone, refuse run_docker and rolling_update next to a running rotation, defer SIGQUIT, and name the remaining windows and cases in the trust matrix and threat model. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
450 lines
15 KiB
Python
450 lines
15 KiB
Python
"""Тот же ли код в образе тега, что у реплик (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]],
|
|
other: dict[str, dict[str, Any]],
|
|
) -> bytes:
|
|
"""Архив `docker export`: файлы, каталоги и ссылка; `other` — поля записи,
|
|
отличные от обычных."""
|
|
buffer = io.BytesIO()
|
|
with tarfile.open(
|
|
fileobj=buffer,
|
|
mode="w",
|
|
format=tarfile.PAX_FORMAT,
|
|
) as archive:
|
|
items = []
|
|
for name in ("app", "app/src"):
|
|
folder = tarfile.TarInfo(name)
|
|
folder.type, folder.mode = tarfile.DIRTYPE, 0o755
|
|
items.append((folder, b""))
|
|
for name, (body, mode) in files.items():
|
|
item = tarfile.TarInfo(name)
|
|
item.size, item.mode = len(body), mode
|
|
items.append((item, body))
|
|
link = tarfile.TarInfo("app/link")
|
|
link.type, link.linkname = tarfile.SYMTYPE, "src"
|
|
items.append((link, b""))
|
|
for item, body in items:
|
|
for field, value in other.get(item.name, {}).items():
|
|
setattr(item, field, value)
|
|
if not item.isreg():
|
|
item.size = 0
|
|
archive.addfile(item, io.BytesIO(body))
|
|
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.other: dict[str, dict[str, dict[str, Any]]] = {}
|
|
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],
|
|
self.other.get(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"]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("name", "other"),
|
|
[
|
|
("app/src/main.py", {"uid": 10001}),
|
|
("app/src/main.py", {"gid": 10001}),
|
|
# вид: жёсткая ссылка вместо символической, цель та же
|
|
("app/link", {"type": tarfile.LNKTYPE}),
|
|
("app/link", {"linkname": "bin"}),
|
|
("app/src", {"mode": 0o777}),
|
|
("app/src", {"uid": 10001}),
|
|
(
|
|
"usr/bin/tool",
|
|
{"pax_headers": {same_image.CAPABILITIES: "cap_net_admin"}},
|
|
),
|
|
],
|
|
)
|
|
def test_another_attribute(
|
|
name: str,
|
|
other: dict[str, Any],
|
|
docker: Docker,
|
|
capsys: pytest.CaptureFixture[str],
|
|
) -> None:
|
|
"""Другой владелец, вид, цель ссылки, права каталога и file capabilities —
|
|
другой код, даже если содержание то же."""
|
|
docker.other["two"] = {name: other}
|
|
assert same_image.main(ARGS) == 1
|
|
assert f"another /{name}" in capsys.readouterr().out
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("name", "code"),
|
|
[
|
|
# точка монтирования и всё под ней, но не соседний путь с тем же началом
|
|
("app/config.toml.bak", 1),
|
|
("tmp2/file", 1),
|
|
("tmp/deep/file", 0),
|
|
("run/secrets/api.key2", 1),
|
|
("devices/file", 1),
|
|
],
|
|
)
|
|
def test_mount_points(name: str, code: int, docker: Docker) -> None:
|
|
docker.trees["one"][name] = (b"x", 0o644)
|
|
assert same_image.main(ARGS) == code
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("name", "code"),
|
|
[
|
|
("opt/new", 1),
|
|
# каталог на пути к точке монтирования мог создать runtime
|
|
("run/secrets", 0),
|
|
("run", 0),
|
|
("run/other", 1),
|
|
# начало имени — ещё не каталог на пути
|
|
("ru", 1),
|
|
],
|
|
)
|
|
def test_new_directory(name: str, code: int, docker: Docker) -> None:
|
|
docker.trees["two"][name] = (b"", 0o755)
|
|
docker.other["two"] = {name: {"type": tarfile.DIRTYPE}}
|
|
assert same_image.main(ARGS) == code
|
|
|
|
|
|
def test_file_on_the_way_to_a_mount_point(docker: Docker) -> None:
|
|
"""Не в счёт только каталоги пути: файл с таким именем — другой код."""
|
|
docker.trees["two"]["run"] = (b"x", 0o644)
|
|
assert same_image.main(ARGS) == 1
|
|
|
|
|
|
@pytest.mark.parametrize("replica", ["one", "two"])
|
|
def test_every_replica_config(replica: str, docker: Docker) -> None:
|
|
docker.containers[replica]["User"] = "root"
|
|
assert same_image.main(ARGS) == 1
|
|
|
|
|
|
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("code", [0, 1])
|
|
def test_export_code(
|
|
code: int,
|
|
tmp_path: Path,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""Оборванный `docker export` (архив читается, код не 0) — «сравнить не
|
|
удалось», а не сравнение с половиной файлов."""
|
|
archive = tmp_path / "export.tar"
|
|
archive.write_bytes(_archive(FILES, {}))
|
|
environment = _fake_docker(tmp_path, f"cat '{archive}'\nexit {code}\n")
|
|
monkeypatch.setenv("PATH", environment["PATH"])
|
|
if code:
|
|
with pytest.raises(same_image.Unknown):
|
|
same_image.export("one", [])
|
|
else:
|
|
assert "app/src/main.py" in same_image.export("one", [])
|
|
|
|
|
|
@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"
|
|
seen = tmp_path / "seen"
|
|
record = f"import sys; open({str(seen)!r}, 'w').write(str(sys.argv[1:]))"
|
|
python.write_text(f"#!{sys.executable}\n{record}\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 label == "sha256:same":
|
|
assert not seen.exists()
|
|
else:
|
|
assert seen.read_text().endswith("'app:tag', 'aaaa', 'bbbb']")
|
|
if code:
|
|
assert "run make run_docker or make rolling_update" in result.stderr
|