Support issue-linked demo source changes
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
"""Verify an immutable import plus an optional downstream change record.
|
||||
|
||||
File identity is distinct from issue existence, peer approval and build success.
|
||||
Reviewed-main selection remains the Jenkins job's separate trust boundary.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
BASELINE_SHA256 = 'a86656744d5d700aa21834fc03b0a54dfe5b5fd4e8b32ccecc40c6ae7553df2d'
|
||||
UPSTREAM_COMMIT = 'f4e3193d49a98efcf2f16c2aa22d6085ebe70f36'
|
||||
APPLICATION_BASELINE = '0.1.4-alpha'
|
||||
ISSUE_PATTERN = r'https://git\.yebilly\.me/ssw590-group1/vpn-dns-gateway/issues/[1-9][0-9]*'
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise ValueError(message)
|
||||
|
||||
|
||||
def strict_json(data):
|
||||
def object_pairs(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
require(key not in result, f'Duplicate JSON key: {key}')
|
||||
result[key] = value
|
||||
return result
|
||||
return json.loads(data, object_pairs_hook=object_pairs)
|
||||
|
||||
|
||||
def identity(data, mode='100644'):
|
||||
return dict(mode=mode, bytes=len(data), sha256=hashlib.sha256(data).hexdigest(),
|
||||
git_blob=hashlib.sha1(b'blob ' + str(len(data)).encode() + b'\0' + data).hexdigest())
|
||||
|
||||
|
||||
def is_link(path):
|
||||
return path.is_symlink() or getattr(path, 'is_junction', lambda: False)()
|
||||
|
||||
|
||||
def safe_path(name):
|
||||
require(isinstance(name, str) and bool(name), 'Expected a nonempty relative path')
|
||||
path = PurePosixPath(name)
|
||||
require(not path.is_absolute() and str(path) == name and '\\' not in name
|
||||
and all(part.casefold() not in {'.', '..', '.git'} and ':' not in part
|
||||
and not part.endswith((' ', '.')) for part in path.parts),
|
||||
f'Unsafe source path: {name}')
|
||||
return name
|
||||
|
||||
|
||||
def expected_files(manifest, change):
|
||||
"""Derive the complete expected tree without modifying the baseline manifest."""
|
||||
expected = dict(manifest['files'])
|
||||
if change is None:
|
||||
return expected
|
||||
require(isinstance(change, dict) and set(change) == {
|
||||
'schema_version', 'upstream_commit', 'baseline_manifest_sha256',
|
||||
'change_id', 'issue_url', 'description', 'changes'}, 'Invalid change record fields')
|
||||
require(type(change['schema_version']) is int and change['schema_version'] == 1,
|
||||
'Unsupported change schema')
|
||||
require(change['upstream_commit'] == UPSTREAM_COMMIT
|
||||
and change['baseline_manifest_sha256'] == BASELINE_SHA256,
|
||||
'Change record must reference the original baseline')
|
||||
require(isinstance(change['change_id'], str)
|
||||
and re.fullmatch(r'[a-z0-9]+(?:-[a-z0-9]+)*', change['change_id'])
|
||||
and len(change['change_id']) <= 100, 'Invalid change identifier')
|
||||
require(isinstance(change['issue_url'], str)
|
||||
and re.fullmatch(ISSUE_PATTERN, change['issue_url']), 'Expected a project issue URL')
|
||||
require(isinstance(change['description'], str)
|
||||
and 1 <= len(change['description'].strip()) <= 2000, 'Invalid change description')
|
||||
require(isinstance(change['changes'], list) and bool(change['changes']), 'Empty change record')
|
||||
removed, replacements = set(), {}
|
||||
for row in change['changes']:
|
||||
require(isinstance(row, dict) and set(row) == {'before', 'after'}, 'Invalid change entry')
|
||||
before, after = row['before'], row['after']
|
||||
require(before is not None or after is not None, 'Empty change entry')
|
||||
if before is not None:
|
||||
safe_path(before)
|
||||
require(before in expected and before not in removed, f'Unknown/repeated original: {before}')
|
||||
removed.add(before)
|
||||
if after is not None:
|
||||
require(isinstance(after, dict) and set(after) == {
|
||||
'path', 'mode', 'git_blob', 'sha256', 'bytes'}, 'Invalid replacement identity')
|
||||
name = safe_path(after['path'])
|
||||
require(name not in replacements, f'Repeated replacement: {name}')
|
||||
require(isinstance(after['mode'], str) and after['mode'] in {'100644', '100755'}, 'Invalid file mode')
|
||||
require(type(after['bytes']) is int and after['bytes'] >= 0, 'Invalid byte count')
|
||||
for key, length in [('git_blob', 40), ('sha256', 64)]:
|
||||
require(isinstance(after[key], str) and re.fullmatch('[0-9a-f]{'+str(length)+'}', after[key]),
|
||||
f'Invalid {key}')
|
||||
replacement = {key: after[key] for key in ('mode', 'git_blob', 'sha256', 'bytes')}
|
||||
require(before != name or replacement != expected[before], f'No-op change: {name}')
|
||||
replacements[name] = replacement
|
||||
for name in removed:
|
||||
del expected[name]
|
||||
require(not (set(replacements) & set(expected)), 'Replacement collides with unchanged original')
|
||||
expected.update(replacements)
|
||||
require(expected != manifest['files'], 'Change record leaves the baseline tree unchanged')
|
||||
require(len({name.casefold() for name in expected}) == len(expected), 'Case-insensitive path collision')
|
||||
folded_names = {name.casefold() for name in expected}
|
||||
for name in expected:
|
||||
require(not any(str(parent).casefold() in folded_names for parent in PurePosixPath(name).parents),
|
||||
f'File/directory collision: {name}')
|
||||
return expected
|
||||
|
||||
|
||||
def load_definition(demo):
|
||||
manifest_path = demo / 'snapshot.json'
|
||||
require(not is_link(manifest_path), 'Baseline manifest must not be a link')
|
||||
data = manifest_path.read_bytes()
|
||||
require(hashlib.sha256(data).hexdigest() == BASELINE_SHA256, 'Original baseline manifest changed')
|
||||
manifest = strict_json(data)
|
||||
require(manifest['upstream_commit'] == UPSTREAM_COMMIT
|
||||
and manifest['application_baseline'] == APPLICATION_BASELINE, 'Wrong baseline identity')
|
||||
change_path = demo / 'source-change.json'
|
||||
require(not is_link(change_path), 'Change record must not be a link')
|
||||
change_data = change_path.read_bytes() if change_path.exists() else None
|
||||
change = strict_json(change_data) if change_data is not None else None
|
||||
require(change_data is None or change is not None, 'A present change record cannot be null')
|
||||
return manifest, change, change_data, expected_files(manifest, change)
|
||||
|
||||
|
||||
def verify_source(demo, require_tracked=False):
|
||||
demo = Path(demo).resolve()
|
||||
manifest, change, change_data, expected = load_definition(demo)
|
||||
source = demo / 'tikzrefinery'
|
||||
require(not is_link(source), 'Source root must not be a link')
|
||||
actual = set()
|
||||
for path in source.rglob('*'):
|
||||
require(not is_link(path), f'Source link rejected: {path}')
|
||||
if path.is_file():
|
||||
actual.add(path.relative_to(source).as_posix())
|
||||
else:
|
||||
require(path.is_dir(), f'Unexpected source entry: {path}')
|
||||
require(actual == set(expected), f'Source tree differs: missing={sorted(set(expected)-actual)}, '
|
||||
f'extra={sorted(actual-set(expected))}')
|
||||
for name, wanted in expected.items():
|
||||
require(identity((source / name).read_bytes(), wanted['mode']) == wanted,
|
||||
f'Source identity differs: {name}')
|
||||
if require_tracked:
|
||||
rows = subprocess.check_output(['git', 'ls-files', '--stage', '-z', '--',
|
||||
'demo/tikzrefinery', 'demo/snapshot.json', 'demo/source-change.json'],
|
||||
cwd=demo.parent).decode('utf-8').split('\0')
|
||||
tracked = {}
|
||||
for row in filter(None, rows):
|
||||
metadata, path = row.split('\t', 1)
|
||||
mode, blob, stage = metadata.split()
|
||||
require(stage == '0', f'Unresolved index entry: {path}')
|
||||
tracked[path] = (mode, blob)
|
||||
wanted_index = {'demo/tikzrefinery/' + name: (item['mode'], item['git_blob'])
|
||||
for name, item in expected.items()}
|
||||
wanted_index['demo/snapshot.json'] = ('100644', identity((demo / 'snapshot.json').read_bytes())['git_blob'])
|
||||
if change_data is not None:
|
||||
wanted_index['demo/source-change.json'] = ('100644', identity(change_data)['git_blob'])
|
||||
require(tracked == wanted_index, 'Git index differs from verified source/manifest/change record; '
|
||||
'stage the exact intended files, including new assets and the change record')
|
||||
return dict(result='passed', upstream_commit=UPSTREAM_COMMIT,
|
||||
application_baseline=APPLICATION_BASELINE, baseline_manifest_sha256=BASELINE_SHA256,
|
||||
source_state='frozen-baseline' if change is None else 'recorded-change',
|
||||
verified_files=len(expected), git_index_verified=require_tracked,
|
||||
source_change_record=change,
|
||||
source_change_sha256=hashlib.sha256(change_data).hexdigest() if change_data is not None else None)
|
||||
|
||||
|
||||
def verify_packaged_provenance(record, manifest):
|
||||
"""Check metadata consistency; this alone does not rebuild or retest a binary."""
|
||||
proof = record['source_verification']
|
||||
expected = expected_files(manifest, proof['source_change_record'])
|
||||
require(proof['result'] == 'passed' and proof['upstream_commit'] == UPSTREAM_COMMIT
|
||||
and proof['application_baseline'] == APPLICATION_BASELINE
|
||||
and proof['baseline_manifest_sha256'] == BASELINE_SHA256
|
||||
and proof['verified_files'] == len(expected), 'Invalid packaged source verification')
|
||||
changed = proof['source_change_record'] is not None
|
||||
require(proof['source_state'] == ('recorded-change' if changed else 'frozen-baseline'), 'Wrong source state')
|
||||
hashes = record['source_sha256']
|
||||
require(hashes['snapshot.json'] == BASELINE_SHA256, 'Wrong packaged baseline hash')
|
||||
require(record['upstream_commit'] == UPSTREAM_COMMIT
|
||||
and record['application_baseline'] == APPLICATION_BASELINE, 'Wrong package identity')
|
||||
require(type(proof['git_index_verified']) is bool, 'Invalid tracked-source flag')
|
||||
require(record['execution'] != 'Jenkins' or proof['git_index_verified'], 'Jenkins requires indexed source')
|
||||
if changed:
|
||||
require(isinstance(proof['source_change_sha256'], str)
|
||||
and re.fullmatch(r'[0-9a-f]{64}', proof['source_change_sha256'])
|
||||
and hashes['source-change.json'] == proof['source_change_sha256'], 'Wrong change record hash')
|
||||
else:
|
||||
require(proof['source_change_sha256'] is None and 'source-change.json' not in hashes,
|
||||
'Unexpected baseline change record')
|
||||
product_hashes = {name.removeprefix('tikzrefinery/'): value for name, value in hashes.items()
|
||||
if name.startswith('tikzrefinery/')}
|
||||
require(product_hashes == {name: item['sha256'] for name, item in expected.items()},
|
||||
'Packaged source inventory differs from declared tree')
|
||||
Reference in New Issue
Block a user