File size: 9,406 Bytes
0a20c7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
#!/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())