enterprise-range-harborized-v1-1127 / docs /restore-executable-bits.py
xxyyue's picture
Add enterprise-range-harborized-v1-1127 files (batch 1/11)
0a20c7e verified
Raw History Blame Contribute Delete
9.41 kB
#!/usr/bin/env python3
"""Restore recorded execute bits after an HTTP dataset download.
Run from a downloaded repository with regular files, after verifying SHA256SUMS.
Default: verify and report only. --apply changes file permissions, never content.
Uses a bounded-FD two-pass strategy so repositories with tens of thousands of
scripts never exhaust OS open-file limits (EMFILE).
Copyright (c) 2026 AstralEdge contributors. SPDX-License-Identifier: MIT
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import stat
import sys
MANIFEST = "docs/executable-files.json"
SELF = "docs/restore-executable-bits.py"
FORBIDDEN = {MANIFEST, SELF, "SHA256SUMS"}
MAX_MANIFEST_BYTES = 16 * 1024 * 1024
class ValidationError(Exception):
pass
def reject(code: str) -> None:
raise ValidationError(code)
def relative_path(value: object) -> str:
if not isinstance(value, str) or not value:
reject("invalid_relative_path")
path = PurePosixPath(value)
if (
not path.parts
or value in {".", ".."}
or path.is_absolute()
or value != path.as_posix()
or value.strip() != value
or ".." in path.parts
or "\\" in value
or any(ord(char) < 32 for char in value)
or value in FORBIDDEN
):
reject("unsafe_relative_path")
return value
def open_regular(root_fd: int, name: str) -> int:
"""Open below root using no-follow directory handles; never open a symlink."""
directory = os.dup(root_fd)
try:
parts = PurePosixPath(name).parts
for part in parts[:-1]:
info = os.stat(part, dir_fd=directory, follow_symlinks=False)
if not stat.S_ISDIR(info.st_mode):
reject("symlink_or_non_directory_component")
child = os.open(
part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory
)
os.close(directory)
directory = child
info = os.stat(parts[-1], dir_fd=directory, follow_symlinks=False)
if not stat.S_ISREG(info.st_mode):
reject("symlink_or_special_file")
descriptor = os.open(
parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory
)
actual = os.fstat(descriptor)
if not stat.S_ISREG(actual.st_mode):
os.close(descriptor)
reject("special_file")
if (actual.st_dev, actual.st_ino) != (info.st_dev, info.st_ino):
os.close(descriptor)
reject("file_changed_during_open")
return descriptor
finally:
os.close(directory)
def fd_hash(descriptor: int) -> str:
os.lseek(descriptor, 0, os.SEEK_SET)
digest = hashlib.sha256()
while True:
block = os.read(descriptor, 1024 * 1024)
if not block:
return digest.hexdigest()
digest.update(block)
def identity(info: os.stat_result) -> tuple[int, int, int, int]:
return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns
@dataclass
class Entry:
path: str
sha256: str
execute_bits: int
original_mode: int
original_identity: tuple[int, int, int, int]
@property
def desired_mode(self) -> int:
# Preserve current read/write bits, restore only recorded execute bits,
# and never restore setuid, setgid or sticky bits.
return (self.original_mode & 0o666) | self.execute_bits
def read_manifest(root_fd: int) -> list[dict]:
descriptor = open_regular(root_fd, MANIFEST)
try:
size = os.fstat(descriptor).st_size
if size > MAX_MANIFEST_BYTES:
reject("manifest_too_large")
data = bytearray()
while True:
block = os.read(descriptor, 65536)
if not block:
break
data.extend(block)
if len(data) > MAX_MANIFEST_BYTES:
reject("manifest_too_large")
try:
manifest = json.loads(data.decode("utf-8"))
except (ValueError, UnicodeError):
reject("invalid_manifest_json")
finally:
os.close(descriptor)
if (
not isinstance(manifest, dict)
or type(manifest.get("schema_version")) is not int
or manifest.get("schema_version") != 1
):
reject("invalid_manifest_schema")
files = manifest.get("files")
if (
not isinstance(files, list)
or not files
or len(files) > 200000
or type(manifest.get("file_count")) is not int
or manifest["file_count"] != len(files)
):
reject("invalid_manifest_file_count")
return files
def restore(root: Path, *, apply: bool = False) -> dict:
"""Validate every entry first, then apply per-file with re-verification and bounded FDs."""
if not hasattr(os, "O_NOFOLLOW") or not hasattr(os, "O_DIRECTORY"):
reject("posix_no_follow_support_required")
if root.is_symlink() or not root.is_dir():
reject("invalid_repository_root")
root_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
entries: list[Entry] = []
changed: list[Entry] = []
try:
seen = set()
# Pass 1: validate every manifest entry and verify full SHA-256 (closing each FD immediately)
for item in read_manifest(root_fd):
if not isinstance(item, dict):
reject("invalid_manifest_entry")
name = relative_path(item.get("path"))
expected = item.get("sha256")
bits = item.get("execute_bits")
if name in seen:
reject("duplicate_manifest_path")
seen.add(name)
if not isinstance(expected, str) or not re.fullmatch(r"[0-9a-f]{64}", expected):
reject("invalid_expected_sha256")
if type(bits) is not int or bits <= 0 or bits & ~0o111:
reject("invalid_execute_bits")
descriptor = open_regular(root_fd, name)
try:
info = os.fstat(descriptor)
if fd_hash(descriptor) != expected:
reject("file_sha256_mismatch")
if identity(os.fstat(descriptor)) != identity(info):
reject("file_changed_during_verification")
entries.append(
Entry(
name,
expected,
bits,
stat.S_IMODE(info.st_mode),
identity(info),
)
)
finally:
os.close(descriptor)
pending = sum(entry.original_mode != entry.desired_mode for entry in entries)
# Pass 2: if --apply, reopen each pending file safely, re-check identity & SHA-256, and fchmod
if apply:
try:
for entry in entries:
if entry.original_mode == entry.desired_mode:
continue
descriptor = open_regular(root_fd, entry.path)
try:
cur_info = os.fstat(descriptor)
if identity(cur_info) != entry.original_identity:
reject("file_changed_before_apply")
if fd_hash(descriptor) != entry.sha256:
reject("file_sha256_mismatch_before_apply")
os.fchmod(descriptor, entry.desired_mode)
changed.append(entry)
finally:
os.close(descriptor)
except (OSError, ValidationError):
rollback_failures = 0
for previous in reversed(changed):
try:
fd = open_regular(root_fd, previous.path)
try:
os.fchmod(fd, previous.original_mode & 0o777)
finally:
os.close(fd)
except (OSError, ValidationError):
rollback_failures += 1
reject(
"chmod_failed_with_rollback_errors"
if rollback_failures
else "chmod_failed_changes_rolled_back"
)
return {
"verified": len(entries),
"pending_changes": pending,
"applied": len(changed),
"dry_run": not apply,
}
finally:
os.close(root_fd)
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--apply", action="store_true", help="Restore verified execute bits"
)
args = parser.parse_args(argv)
script = Path(os.path.abspath(__file__))
try:
if script.is_symlink() or script.parent.is_symlink():
reject("script_or_docs_directory_is_symlink")
result = restore(script.parent.parent, apply=args.apply)
print(json.dumps(result))
return 0
except ValidationError as error:
print(json.dumps({"error": str(error), "applied": False}))
return 2
except OSError as error:
print(json.dumps({"error": type(error).__name__, "applied": False}))
return 2
if __name__ == "__main__":
sys.exit(main())