File size: 3,566 Bytes
d980d12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Verify the complete repository payload against PACKAGE_MANIFEST.json."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path, PurePosixPath
import re
import sys


def verify(root: Path) -> int:
    root = root.resolve()
    manifest = root / "PACKAGE_MANIFEST.json"
    if manifest.is_symlink() or not manifest.is_file():
        raise ValueError("PACKAGE_MANIFEST.json must be a regular file")
    data = json.loads(manifest.read_text(encoding="utf-8"))
    if not isinstance(data, dict) or type(data.get("schema_version")) is not int or data.get("schema_version") != 1 or not isinstance(data.get("files"), list):
        raise ValueError("Unsupported manifest schema")
    expected = {}
    for record in data["files"]:
        if not isinstance(record, dict):
            raise ValueError("Invalid manifest file record")
        name = record.get("path")
        if not isinstance(name, str) or not name or "\\" in name:
            raise ValueError("Invalid manifest path")
        path = PurePosixPath(name)
        if path.is_absolute() or any(p in (".", "..") for p in path.parts) or str(path) != name:
            raise ValueError("Unsafe or noncanonical manifest path: " + name)
        if name == "PACKAGE_MANIFEST.json" or name in expected:
            raise ValueError("Duplicate or self-referencing manifest entry: " + name)
        if not re.fullmatch(r"[0-9a-f]{64}", str(record.get("sha256", ""))):
            raise ValueError("Invalid SHA-256 entry: " + name)
        size = record.get("size_bytes")
        if not isinstance(size, int) or isinstance(size, bool) or size < 0:
            raise ValueError("Invalid size entry: " + name)
        expected[name] = record
    actual = set()
    for path in root.rglob("*"):
        name = path.relative_to(root).as_posix()
        if path.is_symlink():
            raise ValueError("Symlinks are not permitted: " + name)
        if path.is_file() and name != "PACKAGE_MANIFEST.json":
            actual.add(name)
        elif not path.is_file() and not path.is_dir():
            raise ValueError("Nonregular filesystem entry: " + name)
    if actual != set(expected):
        raise ValueError("Payload mismatch; missing=" + repr(sorted(set(expected) - actual))
                         + "; unexpected=" + repr(sorted(actual - set(expected))))
    for name, record in sorted(expected.items()):
        path = root / name
        if not path.resolve().is_relative_to(root):
            raise ValueError("Path escapes repository: " + name)
        if path.stat().st_size != record["size_bytes"]:
            raise ValueError("Size mismatch: " + name)
        digest = hashlib.sha256()
        with path.open("rb") as stream:
            for chunk in iter(lambda: stream.read(1024 * 1024), b""):
                digest.update(chunk)
        if digest.hexdigest() != record["sha256"]:
            raise ValueError("SHA-256 mismatch: " + name)
    print(f"Integrity verified: {len(expected)} payload files; no unexpected files or symlinks.")
    return len(expected)


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
    args = parser.parse_args()
    try:
        verify(args.root)
    except (OSError, ValueError, TypeError, KeyError) as exc:
        print("Integrity verification failed: " + str(exc), file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())