forked from mtusi2026/mtusi2026lab7
fix: address rotation-revocation re-verify findings
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>
This commit is contained in:
@@ -50,19 +50,36 @@ FILES = {
|
||||
}
|
||||
|
||||
|
||||
def _archive(files: dict[str, tuple[bytes, int]]) -> bytes:
|
||||
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") as archive:
|
||||
folder = tarfile.TarInfo("app")
|
||||
folder.type = tarfile.DIRTYPE
|
||||
archive.addfile(folder)
|
||||
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
|
||||
archive.addfile(item, io.BytesIO(body))
|
||||
items.append((item, body))
|
||||
link = tarfile.TarInfo("app/link")
|
||||
link.type, link.linkname = tarfile.SYMTYPE, "src"
|
||||
archive.addfile(link)
|
||||
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()
|
||||
|
||||
|
||||
@@ -91,6 +108,7 @@ class Docker:
|
||||
"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:
|
||||
@@ -125,7 +143,10 @@ class Docker:
|
||||
container: str,
|
||||
places: list[str],
|
||||
) -> dict[str, tuple[Any, ...]]:
|
||||
data = _archive(self.trees[container])
|
||||
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))
|
||||
|
||||
@@ -222,6 +243,81 @@ def test_another_file(
|
||||
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
|
||||
@@ -268,6 +364,25 @@ def test_export_must_succeed(
|
||||
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"),
|
||||
[
|
||||
@@ -305,7 +420,9 @@ esac
|
||||
""",
|
||||
)
|
||||
python = tmp_path / "python"
|
||||
python.write_text(f"#!{sys.executable}\n{compare}\n")
|
||||
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)],
|
||||
@@ -323,5 +440,10 @@ esac
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user