File size: 3,712 Bytes
f7ed292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Verify this HF packaging release using only the Python standard library."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path, PurePosixPath
import re
import sys


def sha256(path):
    h = hashlib.sha256()
    with path.open('rb') as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b''):
            h.update(block)
    return h.hexdigest()


def safe_path(root, name):
    if not isinstance(name, str) or '\\' in name or ':' in name:
        raise ValueError(f'Invalid relative path: {name!r}')
    p = PurePosixPath(name)
    if p.is_absolute() or not p.parts or p.as_posix() != name or any(x in {'.', '..'} for x in p.parts):
        raise ValueError(f'Unsafe path: {name!r}')
    target = root.joinpath(*p.parts)
    if any(root.joinpath(*p.parts[:i]).is_symlink() for i in range(1, len(p.parts) + 1)):
        raise ValueError(f'Symlink is not a release file: {name}')
    if not target.resolve().is_relative_to(root):
        raise ValueError(f'Path escapes release: {name}')
    return target


def verify(root):
    root = Path(root).resolve()
    manifest = json.loads((root / 'release_files.json').read_text(encoding='utf-8'))
    records = manifest.get('files')
    if manifest.get('schema_version') != 1 or not isinstance(records, dict) or not records:
        raise ValueError('Expected schema_version 1 and a nonempty files mapping')
    if {'release_files.json', 'SHA256SUMS.txt'} & records.keys():
        raise ValueError('Integrity metadata must be self-excluded from payload map')
    sums = {}
    for line in (root / 'SHA256SUMS.txt').read_text(encoding='utf-8').splitlines():
        match = re.fullmatch(r'([0-9a-f]{64})  (.+)', line)
        if not match:
            raise ValueError('Invalid SHA256SUMS.txt entry')
        digest, name = match.groups()
        if name in sums:
            raise ValueError(f'Duplicate checksum path: {name}')
        safe_path(root, name)
        sums[name] = digest
    if set(sums) != set(records) | {'release_files.json'}:
        raise ValueError('Checksum entries and allowlist disagree')
    for name, record in records.items():
        if not isinstance(record, dict) or not re.fullmatch(r'[0-9a-f]{64}', str(record.get('sha256', ''))):
            raise ValueError(f'Invalid hash record: {name}')
        size = record.get('bytes')
        if not isinstance(size, int) or isinstance(size, bool) or size < 0:
            raise ValueError(f'Invalid size: {name}')
        p = safe_path(root, name)
        if not p.is_file() or p.stat().st_size != size:
            raise ValueError(f'Missing file or wrong size: {name}')
        if sums[name] != record['sha256']:
            raise ValueError(f'Checksum metadata disagree: {name}')
    for name, expected in sums.items():
        p = safe_path(root, name)
        if not p.is_file() or sha256(p) != expected:
            raise ValueError(f'Checksum mismatch: {name}')
    return {'status': 'PASS', 'payload_files': len(records), 'checksum_files': len(sums),
            'payload_bytes': sum(v['bytes'] for v in records.values()),
            'scope': 'HF release payload integrity; not a signature or a scientific proof'}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[1])
    args = parser.parse_args()
    try:
        print(json.dumps(verify(args.root), indent=2))
        return 0
    except (OSError, ValueError, KeyError, TypeError) as exc:
        print(f'Release verification failed: {exc}', file=sys.stderr)
        return 1


if __name__ == '__main__':
    sys.exit(main())