File size: 2,596 Bytes
25824f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Verify the LIBERO-Pro asset ZIP or its extracted assets directory."""

import argparse
import hashlib
import json
import zipfile
from pathlib import Path, PurePosixPath


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


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--manifest", type=Path, required=True)
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument("--archive", type=Path)
    source.add_argument("--assets-dir", type=Path)
    args = parser.parse_args()
    manifest = json.loads(args.manifest.read_text(encoding="utf-8"))
    records = manifest["files"]
    names = [record["path"] for record in records]
    if len(records) != manifest["file_count"] or len(set(names)) != len(names):
        raise ValueError("Manifest count or unique paths mismatch")
    for name in names:
        path = PurePosixPath(name)
        if path.is_absolute() or ".." in path.parts or path.parts[0] != "assets":
            raise ValueError("Invalid manifest path: " + name)
    if args.archive:
        expected = manifest["archive"]
        if args.archive.stat().st_size != expected["bytes"] or file_hash(args.archive) != expected["sha256"]:
            raise ValueError("Archive checksum mismatch")
        with zipfile.ZipFile(args.archive) as archive:
            if len(archive.infolist()) != len(records) or set(archive.namelist()) != set(names):
                raise ValueError("Archive file inventory mismatch")
            for record in records:
                data = archive.read(record["path"])
                if len(data) != record["bytes"] or hashlib.sha256(data).hexdigest() != record["sha256"]:
                    raise ValueError("Asset checksum mismatch: " + record["path"])
    else:
        root = args.assets_dir.resolve()
        for record in records:
            path = root.joinpath(*PurePosixPath(record["path"]).parts[1:]).resolve()
            if root not in path.parents or not path.is_file():
                raise ValueError("Missing or invalid extracted asset: " + record["path"])
            if path.stat().st_size != record["bytes"] or file_hash(path) != record["sha256"]:
                raise ValueError("Extracted asset checksum mismatch: " + record["path"])
    print("Verified {} files from source commit {}".format(len(records), manifest["source_commit"]))


if __name__ == "__main__":
    main()