File size: 4,448 Bytes
1f56441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Replay release certificates in temporary storage; Python standard library only."""
from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile


ROOT = Path(__file__).resolve().parent


def check_integrity() -> int:
    manifest = ROOT / 'SHA256SUMS'
    if not manifest.is_file():
        raise RuntimeError('Missing SHA256SUMS; use the complete release repository.')
    count = 0
    seen = set()
    for line in manifest.read_text(encoding='utf-8').splitlines():
        if not line:
            continue
        digest, name = line.split('  ', 1)
        relative = Path(name)
        if relative.is_absolute() or '..' in relative.parts or name in seen:
            raise RuntimeError('Invalid integrity manifest entry.')
        target = (ROOT / relative).resolve()
        if not target.is_relative_to(ROOT) or not target.is_file():
            raise RuntimeError(f'Missing or unsafe release file: {name}')
        if hashlib.sha256(target.read_bytes()).hexdigest() != digest:
            raise RuntimeError(f'Checksum mismatch: {name}')
        seen.add(name)
        count += 1
    if not count:
        raise RuntimeError('Empty integrity manifest.')
    return count


def run_script(work: Path, name: str) -> str:
    result = subprocess.run(
        [sys.executable, str(work / name)],
        cwd=work, capture_output=True, text=True, timeout=180,
    )
    if result.returncode:
        raise RuntimeError(f'{name} failed ({result.returncode}):\n{result.stdout}{result.stderr}')
    return result.stdout


def identical_json(work: Path, name: str) -> dict:
    regenerated = json.loads((work / name).read_text(encoding='utf-8'))
    released = json.loads((ROOT / name).read_text(encoding='utf-8'))
    if regenerated != released:
        raise RuntimeError(f'Regenerated certificate differs: {name}')
    return regenerated


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--include-symbolic', action='store_true', help='also run optional SymPy audit')
    args = parser.parse_args()
    try:
        integrity_count = check_integrity()
        with tempfile.TemporaryDirectory(prefix='qx_nephriel_verify_') as temporary:
            work = Path(temporary)
            for name in ['verify_q7.py', 'verify_q8_q9.py', 'audit_symbolic.py']:
                shutil.copyfile(ROOT / name, work / name)
            q7_stdout = run_script(work, 'verify_q7.py')
            q89_stdout = run_script(work, 'verify_q8_q9.py')
            q7 = identical_json(work, 'exact_certificate.json')
            q89 = identical_json(work, 'q8_q9_certificate.json')
            if q7['checks_passed'] != 49:
                raise RuntimeError('Unexpected main check count.')
            interval_counts = {n: len(q89[n]['closed_intervals']) for n in ('8', '9')}
            if interval_counts != {'8': 21, '9': 12}:
                raise RuntimeError('Unexpected closed-interval counts.')
            if any(q89[n]['unresolved_intervals'] for n in ('8', '9')):
                raise RuntimeError('Unresolved intervals remain.')
            symbolic = {'status': 'not requested', 'requirements': 'requirements-audit.txt'}
            if args.include_symbolic:
                stdout = run_script(work, 'audit_symbolic.py')
                if 'PASS: 21 independent-expression' not in stdout:
                    raise RuntimeError('Unexpected symbolic audit output.')
                symbolic = {'status': 'passed', 'checks': 21, 'stdout': stdout}
            report = {
                'status': 'passed',
                'integrity_files_checked': integrity_count,
                'exact_checks': q7['checks_passed'],
                'closed_interval_counts': interval_counts,
                'unresolved_intervals': 0,
                'regenerated_certificates_match': True,
                'repository_modified': False,
                'symbolic_audit': symbolic,
                'core_stdout': {'verify_q7.py': q7_stdout, 'verify_q8_q9.py': q89_stdout},
                'complete_analytic_proof_machine_formalized': False,
            }
        print(json.dumps(report, indent=2))
        return 0
    except Exception as error:
        print(f'VERIFICATION FAILED: {error}', file=sys.stderr)
        return 1


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