File size: 3,197 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Freeze an explicitly reviewed source delta without losing the parent inventory."""
import argparse
import hashlib
import json
from pathlib import Path


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def freeze(root, parent, allowed):
    root, parent = Path(root).resolve(), Path(parent).resolve()
    if root == parent or parent in root.parents or root in parent.parents:
        raise ValueError('A separate derivative and immutable parent are required')
    receipt_path = root / 'REPAIR_V2_REVISION.json'
    if receipt_path.exists():
        raise FileExistsError('Revision is already frozen')
    raw = (parent / 'BASE_SHA256SUMS').read_bytes()
    entries = {}
    for line in raw.decode().splitlines():
        expected, name = line.split('  ', 1)
        relative = Path(name)
        if relative.is_absolute() or '..' in relative.parts or relative.parts[0] != 'source':
            raise ValueError('Invalid parent inventory path')
        if digest(parent / relative) != expected:
            raise ValueError('Parent source changed: ' + name)
        entries[name] = expected
    current = {str(path.relative_to(root)): digest(path)
               for path in sorted((root / 'source').rglob('*'))
               if path.is_file() and '__pycache__' not in path.parts
               and path.suffix != '.pyc'}
    removed = sorted(entries.keys() - current.keys())
    changed = {name: {'before': entries.get(name), 'after': value}
               for name, value in current.items() if entries.get(name) != value}
    if removed or set(changed) != set(allowed):
        raise ValueError('Reviewed source delta differs: ' + json.dumps(
            {'removed': removed, 'actual_changes': sorted(changed), 'allowed': sorted(allowed)}))
    snapshot = root / 'REPAIR_V2_PARENT_SHA256SUMS'
    if snapshot.exists():
        raise FileExistsError('Parent snapshot already exists')
    snapshot.write_bytes(raw)
    inventory = ''.join(value + '  ' + name + '\n' for name, value in sorted(current.items()))
    receipt = dict(schema='rhg.repair-v2-source-revision.v1', parent=str(parent),
        parent_inventory_sha256=hashlib.sha256(raw).hexdigest(),
        source_changes=changed, removed_files=removed,
        inventory_sha256=hashlib.sha256(inventory.encode()).hexdigest(),
        implementation_sha256={str(p.relative_to(root)): digest(p)
            for p in sorted(root.rglob('*.py'))
            if not any(part in {'inputs', 'runtime_site', 'supervisor_site', 'vendor',
                               'runs', 'evidence', '__pycache__'} for part in p.relative_to(root).parts)},
        qualification_claimed=False)
    (root / 'BASE_SHA256SUMS').write_text(inventory)
    receipt_path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + '\n')
    return receipt


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root', required=True, type=Path)
    parser.add_argument('--parent', required=True, type=Path)
    parser.add_argument('--allow', action='append', default=[])
    args = parser.parse_args()
    print(json.dumps(freeze(args.root, args.parent, args.allow), indent=2))