Files
lmxopcua/scripts/validation/grpc-data/run-p11-adversarial.py
T
2026-11-23 09:55:04 -05:00

241 lines
14 KiB
Python

#!/usr/bin/env python3
"""Run only the exact deterministic selectors required before P11 measurement.
A registry entry declares an obligation, not a pass. Missing source/selection,
failed or skipped theory rows, stale inputs and altered TRX all fail closed.
This runner never runs a solution command or starts Docker/fixtures.
"""
import argparse
from datetime import datetime, timezone
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
import xml.etree.ElementTree as ET
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
REGISTRY = HERE / 'p11-adversarial-evidence.json'
REQUIRED = {'authority-isolation', 'producer-array-reuse', 'ingress-saturation', 'revocation-during-encoding',
'reconnect-storm-after-active-loss', 'source-readiness-invalidation', 'catch-up-memory', 'concurrent-browse',
'quiet-hot-fairness', 'stalled-writer-snapshot', 'legacy-physical-sharing', 'consumer-role-continuity'}
spec = importlib.util.spec_from_file_location('p11_unit_environment', HERE / 'run-unit-phase.py')
phase = importlib.util.module_from_spec(spec)
spec.loader.exec_module(phase)
class AdversarialError(RuntimeError):
pass
def digest(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def private_json(path, value):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'w') as stream:
json.dump(value, stream, indent=2)
stream.write('\n')
def registry(path=REGISTRY, root=ROOT):
document = json.loads(Path(path).read_text())
rows = document.get('obligations')
if document.get('schema_version') != 1 or not isinstance(rows, list) or len(rows) != len(REQUIRED) or {row.get('id') for row in rows} != REQUIRED:
raise AdversarialError('every required adversarial obligation must be registered exactly once')
for row in rows:
if not isinstance(row.get('description'), str) or not row['description'] or not isinstance(row.get('tests'), list) or not row['tests']:
raise AdversarialError('each obligation needs exact test selectors and a description')
for case in row['tests']:
if set(case) != {'source', 'project', 'selector'} or not re.fullmatch(r'[A-Za-z_]\w*(?:\.[A-Za-z_]\w*){2,}', case['selector']):
raise AdversarialError('only exact fully qualified method selectors are permitted')
for name, suffix in (('source', '.cs'), ('project', '.csproj')):
relative = Path(case[name])
if relative.is_absolute() or '..' in relative.parts or not case[name].startswith('tests/') or relative.suffix != suffix:
raise AdversarialError('test inputs must be exact repository-relative source/project paths')
return document
def source_gaps(document, root=ROOT):
missing = []
for obligation in document['obligations']:
for case in obligation['tests']:
source, project = root / case['source'], root / case['project']
cls, method = case['selector'].rsplit('.', 2)[-2:]
if not source.is_file() or not project.is_file() or not re.search(r'\bclass\s+' + re.escape(cls) + r'\b', source.read_text()) or not re.search(r'\b' + re.escape(method) + r'\s*\(', source.read_text()):
missing.append({'obligation': obligation['id'], **case, 'reason': 'required exact test source/project/method is absent'})
return missing
def input_identity(root=ROOT):
result = subprocess.run(['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z'], cwd=root, capture_output=True, check=True)
names = sorted(set(filter(None, result.stdout.decode().split('\0'))))
files = {}
for name in names:
path = root / name
included = name.startswith(('src/', 'tests/')) or name.startswith('scripts/validation/grpc-data/') or name == 'scripts/ci/ci.runsettings' or '/' not in name and path.suffix in {'.json', '.props', '.targets', '.rsp', '.slnx', '.config'}
if included and path.is_file() and not path.is_symlink() and path.suffix in {'.cs', '.csproj', '.props', '.targets', '.rsp', '.slnx', '.json', '.config', '.runsettings', '.py', '.sh', '.proto', '.razor', '.css', '.js', '.resx'}:
files[name] = digest(path)
if not files:
raise AdversarialError('candidate input inventory is empty')
combined = hashlib.sha256(json.dumps(files, sort_keys=True, separators=(',', ':')).encode()).hexdigest()
import rig
return {'input_sha256': combined, 'files': files, 'runtime_source_tree_hash': rig.source_tree_hash()}
def selector_filter(cases):
return '|'.join('FullyQualifiedName=' + selector for selector in sorted({case['selector'] for case in cases}))
def commands(project, cases, directory):
base = ['dotnet', 'test', project, '-c', 'Release', '-m:1', '-p:TestTfmsInParallel=false', '--settings', 'scripts/ci/ci.runsettings', '--filter', selector_filter(cases)]
return base + ['--list-tests'], base + ['--no-build', '--logger', 'trx', '--results-directory', str(directory)]
def result_rows(directory):
rows = []
directory = Path(directory)
for path in ([directory] if directory.is_file() else sorted(directory.rglob('*.trx'))):
tree = ET.parse(path).getroot()
methods = {}
for definition in tree.findall('.//{*}UnitTest'):
method = definition.find('{*}TestMethod')
if method is not None:
methods[definition.get('id')] = method.get('className', '').split(',')[0] + '.' + method.get('name', '')
for result in tree.findall('{*}Results/{*}UnitTestResult'):
selector = methods.get(result.get('testId'))
if not selector or selector.endswith('.'):
raise AdversarialError('TRX row has no exact method identity')
message = result.find('.//{*}Message')
rows.append({'selector': selector, 'test': result.get('testName') or selector, 'outcome': result.get('outcome'),
'reason': message.text if message is not None else None, 'trx': str(path.resolve()), 'trx_sha256': digest(path)})
return rows
def reconcile(document, discovered, rows, root=ROOT):
obligations = []
required_selectors = {case['selector'] for item in document['obligations'] for case in item['tests']}
unexpected = [row for row in rows if row['selector'] not in required_selectors]
for item in document['obligations']:
evidence = []
for case in item['tests']:
selected = [row for row in rows if row['selector'] == case['selector']]
names = discovered.get(case['selector'], [])
# Discovery owns concrete theory names; all discovered rows must run.
passed = bool(names) and len(selected) == len(names) and {row['test'] for row in selected} == set(names) and all(row['outcome'] == 'Passed' for row in selected)
evidence.append({**case, 'source_sha256': digest(root / case['source']) if (root / case['source']).is_file() else None,
'discovered': names, 'result_count': len(selected), 'results': selected, 'passed': passed})
obligations.append({'id': item['id'], 'description': item['description'], 'tests': evidence, 'passed': all(case['passed'] for case in evidence)})
gaps = source_gaps(document, root)
return {'obligations': obligations, 'source_gaps': gaps, 'unexpected_results': unexpected,
'executed': sum(row['outcome'] != 'NotExecuted' for row in rows), 'skipped': sum(row['outcome'] == 'NotExecuted' for row in rows),
'passed': not gaps and not unexpected and all(item['passed'] for item in obligations)}
def checked_packet(path, registry_path=REGISTRY):
"""Independently re-read current inputs and TRXs; never trust a passed bit."""
path = Path(path).resolve()
if not path.is_file() or path.is_symlink() or os.name != 'nt' and path.stat().st_mode & 0o077:
raise AdversarialError('restricted passing adversarial packet is required before performance sampling')
packet = json.loads(path.read_text())
document = registry(registry_path)
if packet.get('schema_version') != 1 or packet.get('passed') is not True or packet.get('registry_sha256') != digest(registry_path) or packet.get('identity') != input_identity():
raise AdversarialError('adversarial packet is incomplete or belongs to another candidate')
discovered = packet.get('discovery')
selectors = {case['selector'] for item in document['obligations'] for case in item['tests']}
if not isinstance(discovered, dict) or set(discovered) != selectors or any(not isinstance(names, list) or not names or len(set(names)) != len(names) or any(name.split('(', 1)[0] != selector for name in names) for selector, names in discovered.items()):
raise AdversarialError('adversarial packet discovery is missing')
projects = {case['project'] for item in document['obligations'] for case in item['tests']}
expected_exits = {str(index) + '-' + label for index in range(len(projects)) for label in ('discovery', 'test')}
exits = packet.get('command_exit_codes')
if not isinstance(exits, dict) or set(exits) != expected_exits or any(type(value) is not int or value != 0 for value in exits.values()):
raise AdversarialError('adversarial packet command completion evidence is missing or failed')
rows = []
files = packet.get('trx_files')
if not isinstance(files, dict) or not files:
raise AdversarialError('adversarial packet needs actual TRX evidence')
for name, sha in files.items():
trx = Path(name)
if not trx.is_absolute() or not trx.resolve().is_relative_to(path.parent) or trx.is_symlink() or not trx.is_file() or digest(trx) != sha:
raise AdversarialError('adversarial TRX is missing, changed or outside the packet')
rows.extend(result_rows(trx))
# A new result beside frozen files is not silently omitted from reconciliation.
if {str(trx.resolve()) for trx in path.parent.rglob('*.trx')} != set(files):
raise AdversarialError('adversarial TRX inventory changed')
actual_files = {row['trx']: row['trx_sha256'] for row in rows}
if actual_files != files:
raise AdversarialError('adversarial TRX inventory changed')
report = reconcile(document, discovered, rows)
if not report['passed'] or report['executed'] < 1 or report['skipped'] or any(packet.get('command_exit_codes', {}).values()):
raise AdversarialError('required adversarial cases did not all execute and pass')
return {'path': str(path), 'sha256': digest(path), 'input_sha256': packet['identity']['input_sha256'],
'runtime_source_tree_hash': packet['identity']['runtime_source_tree_hash'], 'executed': report['executed'],
'obligations': [row['id'] for row in report['obligations']], 'passed': True}
def run(run_id, registry_path=REGISTRY):
import rig
from processes import run_process
if not rig._RUN_PATTERN.fullmatch(run_id):
raise AdversarialError('safe unique run id required')
os.umask(0o077)
directory = ROOT / 'artifacts/grpc-data/runs' / run_id / 'adversarial-evidence'
directory.mkdir(parents=True, mode=0o700, exist_ok=False)
document = registry(registry_path)
identity = input_identity()
grouped = {}
for item in document['obligations']:
for case in item['tests']:
if not any(gap['selector'] == case['selector'] for gap in source_gaps(document)):
grouped.setdefault(case['project'], {})[case['selector']] = case
discovered = {}; rows = []; exits = {}
started = time.monotonic()
for index, (project, cases) in enumerate(sorted(grouped.items())):
target = directory / str(index); target.mkdir(mode=0o700)
discover, execute = commands(project, cases.values(), target / 'trx')
for label, command in (('discovery', discover), ('test', execute)):
private_json(target / (label + '.command.json'), command)
result = run_process(command, timeout=1800, cwd=ROOT, environment=phase.unit_environment(), max_output_bytes=32 * 1024 * 1024)
for suffix, value in (('stdout', result.stdout), ('stderr', result.stderr)):
fd = os.open(target / (label + '.' + suffix + '.log'), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'w') as stream: stream.write(value)
exits[str(index) + '-' + label] = result.returncode or int(result.timed_out or result.truncated)
if label == 'discovery':
names = phase.discover_names(result.stdout)
for selector in cases:
discovered[selector] = [name for name in names if name.split('(', 1)[0] == selector]
if exits[str(index) + '-' + label] or any(not discovered[name] for name in cases):
break
rows.extend(result_rows(target / 'trx'))
report = reconcile(document, discovered, rows)
report.update(schema_version=1, run_id=run_id, identity=identity, registry_sha256=digest(registry_path),
discovery=discovered, command_exit_codes=exits, duration_seconds=time.monotonic() - started,
completed_at_utc=datetime.now(timezone.utc).isoformat(), trx_files={row['trx']: row['trx_sha256'] for row in rows})
report['passed'] = report['passed'] and not any(exits.values()) and identity == input_identity()
private_json(directory / 'packet.json', report)
return directory / 'packet.json', report
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--run-id', required=True)
parser.add_argument('--registry', type=Path, default=REGISTRY)
args = parser.parse_args(argv)
try:
path, report = run(args.run_id, args.registry)
print(json.dumps({'packet': str(path), 'passed': report['passed'], 'executed': report['executed'], 'missing_source': len(report['source_gaps'])}))
return 0 if report['passed'] else 1
except Exception as error:
print('P11 adversarial gate failed: ' + type(error).__name__ + '; inspect restricted evidence', file=sys.stderr)
return 2
if __name__ == '__main__':
raise SystemExit(main())