verus.py

verification/tools/verus.py

verus.py313 lines← SDK documentation
1#!/usr/bin/env python32"""Install pinned Verus and check both mathematical page-authority proof suites."""3from pathlib import Path, PurePosixPath4import argparse5import datetime6import fcntl7import hashlib8import json9import os10import platform11import re12import stat13import subprocess14import sys15import tomllib16import urllib.request17import uuid18import zipfile1920import run_receipt2122ROOT = Path(__file__).resolve().parents[2]23VERIFY = ROOT / 'verification'24TEMP = VERIFY / 'tmp'25INSTALL = TEMP / 'verus-install'26TOOL = INSTALL / 'verus-x86-linux'27BUNDLE = INSTALL / 'verus.zip'28PIN = tomllib.loads(Path(__file__).with_suffix('.toml').read_text())29PROOFS = VERIFY / 'proofs/page-pool/verus'30PRODUCT = ROOT / 'cdk-rsx/crates/cdk-rsx-platform/src/memory/page_pool.rs'31SUITES = {32    'words': ('word_lemmas.rs', 'word_lemmas', PIN['word_obligations'],33              ('pair_encoding_range', 'replicated_owner', 'masked_owner_update',34               'free_pair_bit', 'allocated_pair_bit', 'allocated_word_count',35               'owner_chunk_progress', 'free_word_iff_zero_pair', 'summary_bit_write',36               'owner_mask_geometry', 'allocated_popcount_prefix', 'nonzero_has_bit',37               'free_summary_bit_write', 'popcount_prefix', 'matching_count')),38    'authority': ('authority.rs', 'authority', PIN['authority_obligations'],39                  ('unique_cover', 'append_disjoint_run', 'remove_exact_run',40                   'fresh_control_partition', 'claim_preserves_control_coverage',41                   'release_preserves_control_coverage',42                   'recovery_preserves_partition_and_other_owners',43                   'recovery_preserves_control_coverage', 'covering_runs_overlap',44                   'owner_of_cover', 'free_interval_is_disjoint', 'recovered')),45}46MUTATIONS = {47    'words': ('ensures owner_pair(word, slot) <= 3,',48              'ensures owner_pair(word, slot) <= 2,', 'postcondition not satisfied'),49    'authority': ('    ensures overlaps(a, b),\n{}',50                  '    ensures overlaps(a, b),\n{ assert(false); }', 'assertion failed'),51}525354def require(condition, message):55    if not condition:56        raise RuntimeError(message)575859def sha(path):60    return hashlib.sha256(path.read_bytes()).hexdigest()616263def git(repo, *args):64    return subprocess.check_output(['git', '-C', str(repo), *args], text=True).strip()656667def environment(*, provision=False):68    home = TEMP / 'rustup'69    require(not home.is_symlink(),70            'Prepare a private proof Rustup home before invoking Verus')71    if provision:72        home.mkdir(parents=True, exist_ok=True)73    require(home.is_dir(), 'Missing private proof Rustup home')74    if not provision:75        require((home / 'toolchains' / PIN['rust_toolchain'] / 'bin/rustc').is_file(),76                'Required Verus toolchain is absent; do not allow implicit installation')77    env = dict(os.environ)78    for key in ('RUSTC_WRAPPER', 'RUSTC_WORKSPACE_WRAPPER', 'RUSTFLAGS',79                'CARGO_ENCODED_RUSTFLAGS', 'RUSTC', 'CARGO_BUILD_TARGET',80                'VERUS_Z3_PATH', 'VERUS_Z3_VERSION', 'LD_LIBRARY_PATH'):81        env.pop(key, None)82    env.update(RUSTUP_HOME=str(home), RUSTUP_TOOLCHAIN=PIN['rust_toolchain'],83               PYTHONDONTWRITEBYTECODE='1')84    return env858687def parse_report(raw):88    def unique_object(pairs):89        value = {}90        for key, item in pairs:91            require(key not in value, 'Duplicate JSON result key: ' + key)92            value[key] = item93        return value9495    def invalid_constant(item):96        raise RuntimeError('Invalid JSON constant: ' + item)9798    try:99        value = json.loads(raw, object_pairs_hook=unique_object,100                           parse_constant=invalid_constant)101    except (ValueError, TypeError) as error:102        raise RuntimeError('Verifier did not produce one complete JSON report') from error103    require(isinstance(value, dict), 'Verifier report must be an object')104    return value105106107def validate_version(report):108    verus = report.get('verus')109    require(isinstance(verus, dict), 'Missing Verus tool identity')110    require(verus.get('profile') == 'release' and verus.get('version') == PIN['version']111            and verus.get('commit') == PIN['revision'], 'Unexpected Verus release')112    require(verus.get('platform') == {'os': 'linux', 'arch': 'x86_64'},113            'Unexpected Verus platform')114    require(verus.get('toolchain') == PIN['rust_toolchain']115            + ' (overridden by environment variable RUSTUP_TOOLCHAIN)',116            'Unexpected Verus Rust toolchain')117118119def validate_report(report, suite, exit_code, negative=False):120    require(isinstance(report, dict) and suite in SUITES, 'Invalid verification suite/report')121    validate_version(report)122    result = report.get('verification-results')123    require(isinstance(result, dict), 'Missing verification result')124    require(result.get('is-verifying-entire-crate') is True, 'Partial verification refused')125    require(result.get('encountered-vir-error') is False, 'Verifier frontend error')126    require(type(result.get('verified')) is int and type(result.get('errors')) is int,127            'Invalid obligation counts')128    expected = SUITES[suite][2]129    require(type(expected) is int and expected > 0, 'Invalid expected obligation count')130    require(type(negative) is bool, 'Invalid negative-control mode')131    require(type(exit_code) is int, 'Invalid process exit code')132    require(result.get('success') is (not negative)133            and result.get('encountered-error') is negative,134            'Unexpected verification outcome')135    require(exit_code == (1 if negative else 0)136            and result['verified'] == expected - (1 if negative else 0)137            and result['errors'] == (1 if negative else 0),138            'Missing obligations, unexpected failure, or incomplete verification')139    details = report.get('func-details')140    require(isinstance(details, dict), 'Missing per-function result details')141    crate = SUITES[suite][1]142    for name in SUITES[suite][3]:143        require(crate + '::' + name in details, 'Missing required proof: ' + name)144    for name, detail in details.items():145        require(isinstance(detail, dict) and isinstance(detail.get('failed_proof_notes'), list),146                'Malformed per-function result: ' + name)147        if not negative:148            require(not detail['failed_proof_notes'], 'Failed proof notes: ' + name)149    return result150151152def validate_negative_diagnostic(stderr, source, suite):153    diagnostic = MUTATIONS[suite][2]154    headers = re.findall(r'^error(?:\[[^\]]+\])?: (.+)$', stderr, re.MULTILINE)155    require(headers == [diagnostic, 'aborting due to 1 previous error'],156            'Negative control failed for an unexpected reason')157    location = re.search(r'^\s*--> (.+):(\d+):(\d+)\s*$', stderr, re.MULTILINE)158    require(location is not None and location[1] == str(source),159            'Negative failure does not identify its mutated source')160    marker = 'ensures owner_pair(word, slot) <= 2,' if suite == 'words' else '{ assert(false); }'161    require(marker in stderr, 'Negative failure does not identify its designated assertion')162163164def archive_members(bundle):165    require(sha(bundle) == PIN['bundle_sha256'], 'Verus release bundle hash mismatch')166    archive = zipfile.ZipFile(bundle)167    for member in archive.infolist():168        path = PurePosixPath(member.filename)169        require(not path.is_absolute() and '..' not in path.parts170                and path.parts and path.parts[0] == TOOL.name,171                'Unsafe Verus archive path')172        mode = member.external_attr >> 16173        require(stat.S_ISDIR(mode) if member.is_dir() else stat.S_ISREG(mode),174                'Unexpected Verus archive entry type')175    return archive176177178def validate_install():179    require(sys.platform == 'linux' and platform.machine() == 'x86_64',180            'This pin supports x86_64 Linux only')181    require(BUNDLE.is_file() and TOOL.is_dir(), 'Run verus.py setup first')182    with archive_members(BUNDLE) as archive:183        expected = set()184        for member in archive.infolist():185            if member.is_dir():186                continue187            installed = INSTALL / member.filename188            expected.add(installed)189            require(installed.is_file() and not installed.is_symlink()190                    and sha(installed) == hashlib.sha256(archive.read(member)).hexdigest(),191                    'Installed Verus file differs from pinned archive: ' + member.filename)192        require({p for p in TOOL.rglob('*') if p.is_file() or p.is_symlink()} == expected,193                'Unexpected installed Verus files')194    env = environment()195    proc = subprocess.run([str(TOOL / 'verus'), '--version', '--output-json'],196                          env=env, text=True, capture_output=True, check=True)197    validate_version(parse_report(proc.stdout))198    rust = subprocess.check_output(['rustup', 'run', PIN['rust_toolchain'], 'rustc', '--version'],199                                   env=env, text=True).strip()200    require(rust == PIN['rustc_version'], 'Unexpected proof Rust compiler')201202203def setup():204    require(sys.platform == 'linux' and platform.machine() == 'x86_64',205            'This pin supports x86_64 Linux only')206    INSTALL.mkdir(parents=True, exist_ok=True)207    if not BUNDLE.exists():208        partial = INSTALL / ('download-' + uuid.uuid4().hex + '.part')209        try:210            urllib.request.urlretrieve(PIN['bundle_url'], partial)211            require(sha(partial) == PIN['bundle_sha256'], 'Verus download hash mismatch')212            partial.replace(BUNDLE)213        finally:214            partial.unlink(missing_ok=True)215    with archive_members(BUNDLE) as archive:216        if not TOOL.exists():217            archive.extractall(INSTALL)218            for member in archive.infolist():219                (INSTALL / member.filename).chmod((member.external_attr >> 16) & 0o777)220    # Rustup authenticates its official distribution; no production override changes.221    subprocess.run(['rustup', 'toolchain', 'install', PIN['rust_toolchain'], '--profile', 'minimal'],222                   env=environment(provision=True), check=True)223    validate_install()224    print('Pinned Verus installed and authenticated; production compiler unchanged')225226227def mutate(source, suite):228    old, new, _ = MUTATIONS[suite]229    require(source.count(old) == 1, 'Negative-control source anchor changed: ' + suite)230    return source.replace(old, new)231232233def run(timeout):234    require(timeout > 0, 'Timeout must be positive')235    checkout = run_receipt.checkout(ROOT)236    paths = [PRODUCT, PROOFS / 'word_lemmas.rs', PROOFS / 'authority.rs',237             Path(__file__), Path(__file__).with_suffix('.toml'), *run_receipt.INPUTS]238    before = {str(p.relative_to(ROOT)): sha(p) for p in paths}239    validate_install()240    require(checkout == run_receipt.checkout(ROOT), 'Checkout changed during tool authentication')241    require(before == {str(p.relative_to(ROOT)): sha(p) for p in paths},242            'Verification input changed during tool authentication')243    stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')244    output = TEMP / ('verus-' + stamp + '-' + uuid.uuid4().hex[:8])245    output.mkdir(parents=True, exist_ok=False)246    cases = []247    for suite, (filename, crate, _, _) in SUITES.items():248        original = (PROOFS / filename).read_text()249        for negative in (False, True):250            label = suite + ('-negative' if negative else '')251            directory = output / label252            directory.mkdir()253            source = directory / filename254            source.write_text(mutate(original, suite) if negative else original)255            args = [str(TOOL / 'verus'), str(source), '--crate-type', 'lib',256                    '--crate-name', crate, '--output-json', '--no-cheating',257                    '--num-threads', '4', '--log-dir', str(directory / 'solver-logs')]258            (directory / 'command.json').write_text(json.dumps(args, indent=2) + '\n')259            cases.append((label, suite, negative, directory, source, args))260    staged = {str(p.relative_to(output)): sha(p) for p in output.rglob('*') if p.is_file()}261    receipt = run_receipt.write(ROOT, output, {262        **checkout, 'sources': before, 'staged': staged,263        'verus_revision': PIN['revision'], 'bundle_sha256': PIN['bundle_sha256'],264        'scope': 'Mathematical proofs; source identity audit is not implementation correspondence',265    })266267    def verify():268        receipt.verify()269        require(before == {str(p.relative_to(ROOT)): sha(p) for p in paths}, 'Verification input changed during run')270        validate_install()271        receipt.verify()272        require(before == {str(p.relative_to(ROOT)): sha(p) for p in paths}, 'Verification input changed during tool check')273274    verify()275    print('Verus output: ' + str(output), flush=True)276    results = {}277    for label, suite, negative, directory, source, args in cases:278        verify()279        with (directory / 'result.json').open('w') as stdout, (directory / 'stderr.log').open('w') as stderr:280            proc = subprocess.run(args, cwd=ROOT, env=environment(),281                                  stdout=stdout, stderr=stderr, timeout=timeout)282        verify()283        require(all(run_receipt.regular(directory / name) for name in ('result.json', 'stderr.log')),284                'Missing or symlinked Verus output')285        report = parse_report((directory / 'result.json').read_text())286        results[label] = validate_report(report, suite, proc.returncode, negative)287        if negative:288            validate_negative_diagnostic((directory / 'stderr.log').read_text(), source, suite)289        print(label + ': ' + ('EXPECTED_REJECTION' if negative else 'PASS')290              + ' (' + str(results[label]['verified']) + ' verified)', flush=True)291    verify()292    (output / 'summary.json').write_text(json.dumps(results, indent=2) + '\n')293    return output294295296def main():297    parser = argparse.ArgumentParser(description=__doc__)298    parser.add_argument('action', choices=['setup', 'run'])299    parser.add_argument('--timeout', type=int, default=180,300                        help='per-process timeout in seconds (default: 180)')301    options = parser.parse_args()302    TEMP.mkdir(exist_ok=True)303    with (TEMP / '.verus-runner.lock').open('w') as lock:304        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)305        setup() if options.action == 'setup' else run(options.timeout)306307308if __name__ == '__main__':309    try:310        main()311    except (RuntimeError, OSError, subprocess.SubprocessError, zipfile.BadZipFile) as error:312        print('Verification refused: ' + str(error), file=sys.stderr)313        sys.exit(1)