Files
akyldash/infra/runner/secure-runner-image.py
agent d8a0646829
CI / tests-and-images (pull_request) Has been cancelled
Runner smoke test / runner-smoke (pull_request) Has been cancelled
Protect runner mount image from CI path replacement
2026-10-12 02:16:13 +03:00

105 lines
3.6 KiB
Python

#!/usr/bin/env python3
"""Create or validate the runner image without following replaceable paths."""
import os
import stat
import subprocess
import sys
def open_directory(path: str) -> int:
current = os.open("/", os.O_RDONLY | os.O_DIRECTORY)
try:
for component in path.strip("/").split("/"):
if not component:
continue
next_fd = os.open(
component,
os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
dir_fd=current,
)
os.close(current)
current = next_fd
return current
except BaseException:
os.close(current)
raise
def filesystem_type(fd: int) -> str:
result = subprocess.run(
["blkid", "-p", "-s", "TYPE", "-o", "value", f"/proc/self/fd/{fd}"],
check=False,
capture_output=True,
text=True,
pass_fds=(fd,),
)
return result.stdout.strip() if result.returncode == 0 else ""
def main() -> int:
image, bytes_text, parent_uid_text, parent_mode_text = sys.argv[1:]
image = os.path.abspath(image)
parent_path, name = os.path.split(image)
if not name or name in {".", ".."}:
raise ValueError("invalid image filename")
parent_fd = open_directory(parent_path)
image_fd = -1
try:
parent_stat = os.fstat(parent_fd)
if parent_stat.st_uid != int(parent_uid_text) or stat.S_IMODE(parent_stat.st_mode) != int(parent_mode_text, 8):
raise RuntimeError("image parent has unexpected owner or permissions")
created = False
try:
image_fd = os.open(
name,
os.O_RDWR | os.O_NOFOLLOW | os.O_CLOEXEC,
dir_fd=parent_fd,
)
except FileNotFoundError:
image_fd = os.open(
name,
os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC,
0o600,
dir_fd=parent_fd,
)
created = True
image_stat = os.fstat(image_fd)
if not stat.S_ISREG(image_stat.st_mode) or image_stat.st_uid != os.geteuid() or image_stat.st_nlink != 1:
raise RuntimeError("image must be a singly-linked regular file owned by the installer")
if not created and image_stat.st_mode & 0o022:
raise RuntimeError("existing image is writable by group or other users")
if created:
os.posix_fallocate(image_fd, 0, int(bytes_text))
subprocess.run(
["mkfs.ext4", "-F", "-q", f"/proc/self/fd/{image_fd}"],
check=True,
pass_fds=(image_fd,),
)
image_stat = os.fstat(image_fd)
if image_stat.st_size != int(bytes_text):
raise RuntimeError(f"image size is {image_stat.st_size} bytes, expected {bytes_text}; refusing to resize or format")
if filesystem_type(image_fd) != "ext4":
raise RuntimeError("image does not contain ext4; refusing to format")
path_stat = os.stat(name, dir_fd=parent_fd, follow_symlinks=False)
if not stat.S_ISREG(path_stat.st_mode) or (path_stat.st_dev, path_stat.st_ino) != (image_stat.st_dev, image_stat.st_ino):
raise RuntimeError("image path changed during validation")
return 0
finally:
if image_fd >= 0:
os.close(image_fd)
os.close(parent_fd)
if __name__ == "__main__":
try:
raise SystemExit(main())
except (OSError, RuntimeError, ValueError, subprocess.CalledProcessError) as error:
print(f"ERROR: {error}", file=sys.stderr)
raise SystemExit(1)