"""Read and atomically replace the two application image references.""" from __future__ import annotations import os import re import tempfile from pathlib import Path KEYS = {"BACKEND_IMAGE", "OPENSEARCH_IMAGE"} IMAGE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/-]*(?:@sha256:[0-9a-f]{64})?\Z") def read_images(path: Path) -> tuple[str, dict[str, str]]: if path.is_symlink() or not path.is_file(): raise ValueError("production env must be a regular non-symlink file") text = path.read_text(encoding="utf-8") values: dict[str, str] = {} lines = text.splitlines(keepends=True) for line in lines: if not re.match(r"^\s*(?:export\s+)?(?:BACKEND_IMAGE|OPENSEARCH_IMAGE)\b", line): continue match = re.fullmatch(r"(BACKEND_IMAGE|OPENSEARCH_IMAGE)=([^\r\n]+)(\r?\n)?", line) if not match: raise ValueError("application image assignments must use plain KEY=value syntax") key, value = match.group(1), match.group(2) if key in values or not IMAGE.fullmatch(value): raise ValueError(f"invalid or duplicate {key} in production env") values[key] = value if set(values) != KEYS: raise ValueError("production env must define exactly one backend and OpenSearch image") return text, values def replace_images( path: Path, expected: dict[str, str], replacement: dict[str, str], *, require_root: bool = True, ) -> None: if set(expected) != KEYS or set(replacement) != KEYS: raise ValueError("both complete application image references are required") if any(not isinstance(value, str) or not IMAGE.fullmatch(value) for value in (*expected.values(), *replacement.values())): raise ValueError("invalid application image reference") text, current = read_images(path) info = path.stat() if require_root and (os.geteuid() != 0 or info.st_uid != 0 or info.st_mode & 0o777 != 0o600): raise ValueError("production env must be root-owned mode 0600 before a release switch") if current != expected: raise ValueError("production image references changed; refusing partial or stale release switch") lines = text.splitlines(keepends=True) updated = [] for line in lines: if not re.match(r"^\s*(?:export\s+)?(?:BACKEND_IMAGE|OPENSEARCH_IMAGE)\b", line): updated.append(line) continue match = re.fullmatch(r"(BACKEND_IMAGE|OPENSEARCH_IMAGE)=([^\r\n]+)(\r?\n)?", line) if match: newline = match.group(3) or "" updated.append(f"{match.group(1)}={replacement[match.group(1)]}{newline}") else: raise ValueError("application image assignments must use plain KEY=value syntax") target = path.parent with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=target, prefix=f".{path.name}.", delete=False) as stream: temporary = Path(stream.name) stream.write("".join(updated)) stream.flush() os.fsync(stream.fileno()) try: os.chmod(temporary, path.stat().st_mode & 0o777) os.replace(temporary, path) directory_fd = os.open(target, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) try: os.fsync(directory_fd) finally: os.close(directory_fd) finally: temporary.unlink(missing_ok=True)