Download research/release_candidate/audit.py from Helinity/python-security-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 9.04 kB
-
https://huggingface.co/datasets/Helinity/python-security-benchmark/resolve/main/research/release_candidate/audit.py
- Command line
-
hf download hf://datasets/Helinity/python-security-benchmark/research/release_candidate/audit.py
-
curl -L -o audit.py https://huggingface.co/datasets/Helinity/python-security-benchmark/resolve/main/research/release_candidate/audit.py
9.04 kB
| """Reconcile existing releases without editing or reclassifying historical records.""" | |
| import ast | |
| from collections import Counter, defaultdict | |
| from hashlib import sha256 | |
| import json | |
| from pathlib import Path | |
| from research.build import json_bytes | |
| from research.check_hf import FILES | |
| from research.leakage import similarity | |
| ROOT = Path(__file__).resolve().parents[2] | |
| VERSION = 'v0.1.0' | |
| RELEASE = ROOT / 'releases' / VERSION | |
| SPLITS = ('train', 'validation', 'test') | |
| def read_json(path): | |
| return json.loads((ROOT / path).read_text(encoding='utf-8')) | |
| def records(scope): | |
| return [json.loads(line) for split in SPLITS | |
| for line in (ROOT / scope / f'{split}.jsonl').read_text(encoding='utf-8').splitlines()] | |
| def resolve_evidence(reference): | |
| path, pointer = reference.split('::', 1) | |
| resolved = (ROOT / path).resolve() | |
| if not resolved.is_relative_to(ROOT): | |
| raise ValueError('Evidence escapes the repository') | |
| value = json.loads(resolved.read_text(encoding='utf-8')) | |
| for part in pointer.split('/'): | |
| value = value[part] | |
| return value | |
| def check_history(): | |
| lock = read_json('releases/v0.1.0/historical-lock.json') | |
| for path, expected in lock.items(): | |
| if sha256((ROOT / path).read_bytes()).hexdigest() != expected: | |
| raise ValueError('Historical file changed: ' + path) | |
| return len(lock) | |
| def reconcile(): | |
| history_count = check_history() | |
| legacy = records('data/research/corpus') | |
| expansion = records('data/research/v3c1/corpus') | |
| rows = legacy + expansion | |
| by_id = {r['sample_id']: r for r in rows} | |
| if len(legacy) != 84 or len(expansion) != 70 or len(by_id) != 154: | |
| raise ValueError('Record populations differ from frozen releases') | |
| original = [json.loads(line) for line in (ROOT / 'data/examples.jsonl').read_text().splitlines()] | |
| if len(original) != 64 or any(any(by_id[r['id']][k] != v for k, v in r.items()) for r in original): | |
| raise ValueError('Original records or IDs changed') | |
| old_notes = read_json('data/research/v3b2/annotations.json') | |
| new_notes = read_json('data/research/v3c1/eligibility.json') | |
| if {n['sample_id'] for n in old_notes} != {r['sample_id'] for r in legacy}: | |
| raise ValueError('Incomplete historical eligibility') | |
| if {n['sample_id'] for n in new_notes} != {r['sample_id'] for r in expansion}: | |
| raise ValueError('Incomplete new eligibility') | |
| old_accepted = {n['sample_id'] for n in old_notes if n['score_eligible']} | |
| new_accepted = {n['sample_id'] for n in new_notes if n['eligible']} | |
| official_old = records('data/research/v3b2/official') | |
| official_new = records('data/research/v3c1/official') | |
| if old_accepted != {r['sample_id'] for r in official_old} or len(old_accepted) != 49: | |
| raise ValueError('Historical official subset changed') | |
| if new_accepted != {r['sample_id'] for r in official_new} or len(new_accepted) != 66: | |
| raise ValueError('New official subset changed') | |
| accepted = old_accepted | new_accepted | |
| scoped_notes = {n['sample_id']: n for n in old_notes} | |
| scoped_notes.update({n['sample_id']: n for n in new_notes}) | |
| methods = Counter() | |
| manifest = [] | |
| for row in rows: | |
| sid = row['sample_id'] | |
| old = sid in {r['sample_id'] for r in legacy} | |
| note = scoped_notes[sid] | |
| reference = note['evidence_reference'] if old else row['evidence_reference'] | |
| if reference: | |
| resolve_evidence(reference) | |
| if sid in accepted and not reference: | |
| raise ValueError('Eligible sample lacks evidence') | |
| if row['label'] not in {'secure', 'insecure'}: | |
| raise ValueError('Invalid label') | |
| paths = {} | |
| for item in row['code_files']: | |
| ast.parse(item['code']) | |
| if item['path'] in paths or Path(item['path']).is_absolute() or '..' in Path(item['path']).parts: | |
| raise ValueError('Invalid source path') | |
| paths[item['path']] = item['code'].splitlines() | |
| for location in [row['source_location'], row['sink_location'], *row['vulnerable_lines']]: | |
| if location is not None and not (location['path'] in paths and 1 <= location['start_line'] <= location['end_line'] <= len(paths[location['path']])): | |
| raise ValueError('Invalid code location') | |
| if row['label'] == 'secure' and row['vulnerable_lines']: | |
| raise ValueError('Secure sample has vulnerability findings') | |
| if old: | |
| if note['record_sha256'] != sha256(json_bytes(row)).hexdigest(): | |
| raise ValueError('Historical annotation hash mismatch') | |
| method = ('docker_runtime' if reference and 'critical-runtime' in reference | |
| else 'controlled_local_process' if sid in accepted | |
| else 'insufficient_or_unverified') | |
| else: | |
| digest = sha256(json_bytes(row['code_files'])).hexdigest() | |
| if note['code_sha256'] != digest: | |
| raise ValueError('Expansion source hash mismatch') | |
| evidence = resolve_evidence(reference) | |
| if sid in accepted and not (row['full_behavior_contract'] and evidence['code_sha256'] == digest | |
| and evidence['normal_passed'] is True and evidence['adversarial_passed'] is True | |
| and evidence['method'] == 'isolated_linux_runtime'): | |
| raise ValueError('Unsupported expansion eligibility') | |
| method = 'docker_runtime' if sid in accepted else 'docker_serialization_only' | |
| if sid in accepted: | |
| methods[method] += 1 | |
| manifest.append(dict(sample_id=sid, release='phase3b' if old else 'phase3c1', | |
| eligible=sid in accepted, split=row['split'], | |
| cwe_id=row['cwe_id'], framework=row['framework'], | |
| evidence_method=method, evidence_reference=reference, | |
| independent_review='awaiting_independent_human_review', | |
| record_sha256=sha256(json_bytes(row)).hexdigest())) | |
| for subset in (rows, official_old, official_new): | |
| boundaries = defaultdict(set) | |
| pairs = defaultdict(set) | |
| for row in subset: | |
| for key in ('scenario_family_id', 'pair_id', 'leakage_group_id'): | |
| if row[key]: | |
| boundaries[(key, row[key])].add(row['split']) | |
| if row['pair_id']: | |
| pairs[row['pair_id']].add(row['label']) | |
| if any(len(s) != 1 for s in boundaries.values()) or any(labels != {'secure', 'insecure'} for labels in pairs.values()): | |
| raise ValueError('Split or pair integrity failure') | |
| leakage = similarity(rows) | |
| if leakage['exact_text'] or leakage['exact_ast']: | |
| raise ValueError('Exact duplicate records') | |
| if any(by_id[e['left']]['split'] != by_id[e['right']]['split'] for e in leakage['near_matches']): | |
| raise ValueError('Cross-split near match') | |
| configs = {} | |
| for config, split_files in FILES.items(): | |
| configs[config] = {split: len((ROOT / path).read_text().splitlines()) for split, path in split_files.items()} | |
| def stratify(key): | |
| result = {} | |
| for value in sorted({str(r[key]) if r[key] is not None else 'unspecified' for r in rows}): | |
| group = [r for r in rows if (str(r[key]) if r[key] is not None else 'unspecified') == value] | |
| result[value] = dict(samples=len(group), eligible=sum(r['sample_id'] in accepted for r in group), | |
| labels=dict(Counter(r['label'] for r in group)), | |
| authored_families=len({r['scenario_family_id'] for r in group})) | |
| return result | |
| return dict(version=VERSION, unique_records=154, original_records=64, | |
| eligible_records=len(accepted), excluded_records=154-len(accepted), | |
| eligible_by_release={'phase3b': len(old_accepted), 'phase3c1': len(new_accepted)}, | |
| eligible_evidence_methods=dict(methods), configurations=configs, | |
| labels=dict(Counter(r['label'] for r in rows)), | |
| per_cwe=stratify('cwe_id'), per_framework=stratify('framework'), | |
| authored_scenario_families=len({r['scenario_family_id'] for r in rows}), | |
| historical_files_preserved=history_count, independent_human_reviews=0, | |
| leakage={**leakage, 'cross_split_matches': 0}, eligibility=sorted(manifest, key=lambda r:r['sample_id'])) | |
| def main(): | |
| result = reconcile() | |
| (RELEASE / 'statistics.json').write_bytes(json_bytes({k:v for k,v in result.items() if k not in {'eligibility', 'leakage'}})) | |
| (RELEASE / 'eligibility.json').write_bytes(json_bytes(result['eligibility'])) | |
| (RELEASE / 'leakage.json').write_bytes(json_bytes(result['leakage'])) | |
| print(f"Reconciled {result['unique_records']} records; {result['eligible_records']} eligible, {result['excluded_records']} excluded.") | |
| if __name__ == '__main__': | |
| main() | |