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>
227 lines
7.6 KiB
Python
227 lines
7.6 KiB
Python
#!/usr/bin/env python3
|
||
"""Тот же ли код в образе тега, что у работающих контейнеров (change
|
||
rotation-revocation, design, «Уточнения verify»; правило
|
||
.claude/rules/rotation.md).
|
||
|
||
same_image.py <образ> <контейнер>…
|
||
|
||
Зовёт scripts/rolling-update.sh с ROLLOUT_BUILD=0, когда манифест тега — не
|
||
манифест реплик: сборка другим проектом compose меняет только метки образа, а
|
||
другой код поочерёдная замена молча выкатила бы. Образ, с которого работает
|
||
контейнер, после переезда тега по имени и digest недоступен («No such image»),
|
||
поэтому сравнивается то, что есть у контейнера:
|
||
|
||
- файлы и каталоги корневой файловой системы целиком — путь, вид, права,
|
||
владелец, содержимое, file capabilities (`docker export`): у реплики корень
|
||
только на чтение, он равен образу. Контейнер тега только создаётся (`docker
|
||
create`), не запускается, и удаляется. Точки монтирования, каталоги на пути
|
||
к ним и файлы, которые Docker кладёт сам, — не в счёт;
|
||
- Config: пользователь, команда, точка входа, каталог, порты, тома,
|
||
healthcheck, сигнал остановки и окружение, кроме переменных, заданных в
|
||
compose.
|
||
|
||
Только stdlib и синтаксис Python 3.9; значения не печатаются. Коды: 0 — тот же
|
||
код; 1 — другой (строка с причиной); 2 — сравнить не удалось.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import subprocess
|
||
import sys
|
||
import tarfile
|
||
|
||
FIELDS = (
|
||
"User",
|
||
"Cmd",
|
||
"Entrypoint",
|
||
"WorkingDir",
|
||
"ExposedPorts",
|
||
"Volumes",
|
||
"Healthcheck",
|
||
"StopSignal",
|
||
"Shell",
|
||
)
|
||
# кладёт сам Docker в любой контейнер
|
||
DOCKER_FILES = (
|
||
".dockerenv",
|
||
"etc/hostname",
|
||
"etc/hosts",
|
||
"etc/mtab",
|
||
"etc/resolv.conf",
|
||
)
|
||
DOCKER_DIRS = ("dev", "proc", "sys")
|
||
# file capabilities в архиве docker export
|
||
CAPABILITIES = "SCHILY.xattr.security.capability"
|
||
|
||
|
||
class Unknown(Exception):
|
||
"""Сравнить не удалось."""
|
||
|
||
|
||
def output(*args: str) -> str:
|
||
result = subprocess.run(
|
||
["docker", *args],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
if result.returncode != 0:
|
||
raise Unknown(f"docker {' '.join(args[:2])}: exit {result.returncode}")
|
||
return result.stdout
|
||
|
||
|
||
def inspect(kind: str, name: str) -> dict:
|
||
return dict(json.loads(output(kind, "inspect", name))[0])
|
||
|
||
|
||
def mounts(container: dict) -> list[str]:
|
||
"""Точки монтирования без начального `/`."""
|
||
found = [item["Destination"] for item in container.get("Mounts") or []]
|
||
found += list((container.get("HostConfig") or {}).get("Tmpfs") or {})
|
||
return [path.lstrip("/") for path in found]
|
||
|
||
|
||
def skipped(name: str, places: list[str]) -> bool:
|
||
return name in DOCKER_FILES or any(
|
||
name == place or name.startswith(place + "/")
|
||
for place in (*DOCKER_DIRS, *places)
|
||
)
|
||
|
||
|
||
def on_the_way(name: str, places: list[str]) -> bool:
|
||
"""Каталог на пути к точке монтирования: его мог создать runtime."""
|
||
return any(place.startswith(name + "/") for place in places)
|
||
|
||
|
||
def tree(stream: tarfile.TarFile, places: list[str]) -> dict[str, tuple]:
|
||
"""Файлы, ссылки и каталоги архива."""
|
||
found: dict[str, tuple] = {}
|
||
for item in stream:
|
||
name = item.name[2:] if item.name.startswith("./") else item.name
|
||
if skipped(name, places):
|
||
continue
|
||
if item.isdir() and on_the_way(name, places):
|
||
continue
|
||
digest = ""
|
||
body = stream.extractfile(item) if item.isreg() else None
|
||
if body is not None:
|
||
digest = hashlib.sha256(body.read()).hexdigest()
|
||
found[name] = (
|
||
item.type,
|
||
item.mode,
|
||
item.uid,
|
||
item.gid,
|
||
item.linkname,
|
||
digest,
|
||
item.pax_headers.get(CAPABILITIES, ""),
|
||
)
|
||
return found
|
||
|
||
|
||
def export(container: str, places: list[str]) -> dict[str, tuple]:
|
||
proc = subprocess.Popen(
|
||
["docker", "export", container],
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.DEVNULL,
|
||
)
|
||
try:
|
||
with tarfile.open(fileobj=proc.stdout, mode="r|") as stream:
|
||
found = tree(stream, places)
|
||
except tarfile.TarError:
|
||
found = {}
|
||
finally:
|
||
if proc.stdout is not None:
|
||
proc.stdout.close()
|
||
code = proc.wait()
|
||
if code != 0 or not found:
|
||
raise Unknown("docker export failed")
|
||
return found
|
||
|
||
|
||
def environment(config: dict, hidden: set[str]) -> dict[str, str]:
|
||
pairs = (item.partition("=") for item in config.get("Env") or [])
|
||
return {name: value for name, _, value in pairs if name not in hidden}
|
||
|
||
|
||
def config_difference(
|
||
image: dict,
|
||
container: dict,
|
||
hidden: set[str],
|
||
) -> str | None:
|
||
for field in FIELDS:
|
||
if (image.get(field) or None) != (container.get(field) or None):
|
||
return f"another {field}"
|
||
if environment(image, hidden) != environment(container, hidden):
|
||
return "another environment"
|
||
return None
|
||
|
||
|
||
def files_difference(
|
||
expected: dict[str, tuple],
|
||
running: dict[str, tuple],
|
||
) -> str | None:
|
||
for name in sorted(set(expected) | set(running)):
|
||
if expected.get(name) != running.get(name):
|
||
return f"another /{name}"
|
||
return None
|
||
|
||
|
||
def compose_variables() -> set[str]:
|
||
"""Имена переменных сервиса api в модели compose: их задаёт не образ."""
|
||
model = json.loads(output("compose", "config", "--format", "json"))
|
||
values = model["services"]["api"].get("environment") or {}
|
||
return set(values)
|
||
|
||
|
||
def difference(image: str, containers: list[str]) -> str | None:
|
||
hidden = compose_variables()
|
||
tag = inspect("image", image)["Config"]
|
||
described = [inspect("container", item) for item in containers]
|
||
for item in described:
|
||
found = config_difference(tag, item["Config"], hidden)
|
||
if found:
|
||
return found
|
||
places = sorted({place for item in described for place in mounts(item)})
|
||
created = output(
|
||
"create",
|
||
"--network",
|
||
"none",
|
||
"--read-only",
|
||
"--cap-drop",
|
||
"ALL",
|
||
"--security-opt",
|
||
"no-new-privileges",
|
||
image,
|
||
).strip()
|
||
try:
|
||
expected = export(created, places)
|
||
finally:
|
||
output("rm", "-f", created)
|
||
for container in containers:
|
||
found = files_difference(expected, export(container, places))
|
||
if found:
|
||
return found
|
||
return None
|
||
|
||
|
||
def main(argv: list[str]) -> int:
|
||
image, *containers = argv
|
||
try:
|
||
found = difference(image, containers)
|
||
except (Unknown, OSError, ValueError, KeyError, IndexError) as error:
|
||
text = str(error) if isinstance(error, Unknown) else ""
|
||
print(f"cannot compare {image}: {text or type(error).__name__}")
|
||
return 2
|
||
if found:
|
||
print(found)
|
||
return 1
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../.."))
|
||
sys.exit(main(sys.argv[1:]))
|