Support issue-linked demo source changes
This commit is contained in:
@@ -16,7 +16,8 @@ $repository = (Resolve-Path (Join-Path $PSScriptRoot '../..')).Path
|
||||
if ($DeliveryVersion -notmatch '^\d+\.\d+\.\d+$') { throw 'Use major.minor.changelist' }
|
||||
Push-Location $repository
|
||||
try {
|
||||
& $PythonExecutable demo/ci/verify-snapshot.py
|
||||
$sourceVerification = (& $PythonExecutable demo/ci/verify-snapshot.py) -join "`n" | ConvertFrom-Json
|
||||
$sourceVerification | ConvertTo-Json -Depth 12 | Write-Output
|
||||
$output = (New-Item -ItemType Directory -Force $OutputDirectory).FullName
|
||||
$build = if ($BuildDirectory) { [IO.Path]::GetFullPath($BuildDirectory) } else { Join-Path $output 'build' }
|
||||
$package = Join-Path $output "TikZRefinery-windows-$DeliveryVersion"
|
||||
@@ -39,17 +40,21 @@ try {
|
||||
Copy-Item "$QtKit/plugins/platforms/qoffscreen.dll" "$package/platforms"
|
||||
Copy-Item "$build/build-info.json" $package
|
||||
Copy-Item demo/snapshot.json "$package/upstream-snapshot.json"
|
||||
if ($null -ne $sourceVerification.source_change_record) {
|
||||
Copy-Item demo/source-change.json "$package/source-change.json"
|
||||
}
|
||||
Copy-Item demo/tikzrefinery/code/examples "$package/examples" -Recurse
|
||||
$downstream = (& git rev-parse HEAD).Trim()
|
||||
$state = (& git status --porcelain --untracked-files=normal) -join "`n"
|
||||
[ordered]@{
|
||||
delivery_version = $DeliveryVersion
|
||||
upstream_commit = 'f4e3193d49a98efcf2f16c2aa22d6085ebe70f36'
|
||||
application_baseline = '0.1.4-alpha'
|
||||
upstream_commit = $sourceVerification.upstream_commit
|
||||
application_baseline = $sourceVerification.application_baseline
|
||||
source_verification = $sourceVerification
|
||||
downstream_commit = $downstream
|
||||
downstream_modified = [bool]$state
|
||||
execution = 'Windows command-line rehearsal; not a Jenkins run'
|
||||
} | ConvertTo-Json | Set-Content "$package/delivery-info.json" -Encoding utf8
|
||||
} | ConvertTo-Json -Depth 12 | Set-Content "$package/delivery-info.json" -Encoding utf8
|
||||
& $PythonExecutable demo/ci/verify-snapshot.py
|
||||
Compress-Archive -LiteralPath $package -DestinationPath "$package.zip"
|
||||
Get-FileHash "$package.zip" -Algorithm SHA256 | Format-List
|
||||
|
||||
@@ -9,6 +9,10 @@ import subprocess
|
||||
import tarfile
|
||||
import xml.etree.ElementTree as ET
|
||||
import zipfile
|
||||
import sys
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from source_provenance import verify_source
|
||||
|
||||
root = Path.cwd()
|
||||
out = root / 'build/demo'
|
||||
@@ -33,6 +37,7 @@ assert (out / 'artifacts/TikZRefinery-report.pdf').is_file()
|
||||
assert (out / 'architecture/html/index.html').is_file()
|
||||
snapshot = json.loads((root / 'demo/snapshot.json').read_text())
|
||||
jenkins = bool(os.environ.get('BUILD_URL'))
|
||||
source_verification = verify_source(root / 'demo', require_tracked=jenkins)
|
||||
try:
|
||||
downstream = run('git', 'rev-parse', 'HEAD')
|
||||
modified = bool(run('git', 'status', '--porcelain', '--untracked-files=normal'))
|
||||
@@ -47,6 +52,7 @@ record = dict(delivery_version=version, application_baseline=snapshot['applicati
|
||||
downstream_commit_or_parent=downstream, downstream_modified=modified,
|
||||
execution='Jenkins' if jenkins else 'SSH command-line rehearsal; not a Jenkins run',
|
||||
build_url=os.environ.get('BUILD_URL'), source_sha256=source_hashes,
|
||||
source_verification=source_verification,
|
||||
toolchain=json.loads((root / 'demo/toolchain.json').read_text()))
|
||||
bundle = out / 'application-bundle'
|
||||
bundle.mkdir(exist_ok=True)
|
||||
@@ -56,6 +62,11 @@ for source, destination in [(out/'native/TikZRefinery',bundle/'TikZRefinery'),
|
||||
(out/'native/build-info.json',bundle/'build-info.json'),
|
||||
(root/'demo/snapshot.json',bundle/'upstream-snapshot.json')]:
|
||||
shutil.copy2(source, destination)
|
||||
if source_verification['source_change_record'] is not None:
|
||||
shutil.copy2(root / 'demo/source-change.json', bundle / 'source-change.json')
|
||||
else:
|
||||
# This generated staging directory can survive a previous changed-source run.
|
||||
(bundle / 'source-change.json').unlink(missing_ok=True)
|
||||
(bundle / 'delivery-info.json').write_text(json.dumps(record, indent=2) + '\n')
|
||||
image = ('ssw590-tikzrefinery' if jenkins else 'ssw590-tikzrefinery-rehearsal') + ':' + version
|
||||
exists = subprocess.run(['docker','image','inspect',image], stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode == 0
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Record the current intentional tree diff; review it before staging or committing.
|
||||
|
||||
This creates metadata only. It never edits product source, stages files, verifies
|
||||
issue existence, or grants approval. A content-changing rename is a delete/add.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from source_provenance import BASELINE_SHA256, UPSTREAM_COMMIT, expected_files, identity, is_link, load_definition, verify_source
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--issue-url', required=True)
|
||||
parser.add_argument('--change-id', required=True)
|
||||
parser.add_argument('--description', required=True)
|
||||
args = parser.parse_args()
|
||||
demo = Path(__file__).resolve().parents[1]
|
||||
target = demo / 'source-change.json'
|
||||
try:
|
||||
manifest, existing, _, _ = load_definition(demo)
|
||||
if existing is not None:
|
||||
raise ValueError('Preserve existing source-change.json; inspect it before replacing it')
|
||||
source = demo / 'tikzrefinery'
|
||||
if is_link(source):
|
||||
raise ValueError('Source root must not be a link')
|
||||
actual = {}
|
||||
for path in sorted(source.rglob('*')):
|
||||
if is_link(path):
|
||||
raise ValueError(f'Source link rejected: {path}')
|
||||
if path.is_file():
|
||||
name = path.relative_to(source).as_posix()
|
||||
# Preserve original modes. New source/docs default to ordinary files;
|
||||
# review executable additions and their index modes explicitly.
|
||||
mode = manifest['files'].get(name, {}).get('mode', '100644')
|
||||
actual[name] = identity(path.read_bytes(), mode)
|
||||
changes = []
|
||||
for name in sorted(set(manifest['files']) | set(actual)):
|
||||
before, after = manifest['files'].get(name), actual.get(name)
|
||||
if before != after:
|
||||
changes.append(dict(before=name if before is not None else None,
|
||||
after=dict(path=name, **after) if after is not None else None))
|
||||
record = dict(schema_version=1, upstream_commit=UPSTREAM_COMMIT,
|
||||
baseline_manifest_sha256=BASELINE_SHA256, change_id=args.change_id,
|
||||
issue_url=args.issue_url, description=args.description, changes=changes)
|
||||
expected_files(manifest, record)
|
||||
with target.open('x', encoding='utf-8', newline='\n') as stream:
|
||||
stream.write(json.dumps(record, indent=2) + '\n')
|
||||
print(json.dumps(verify_source(demo), indent=2))
|
||||
except (ValueError, OSError) as error:
|
||||
parser.exit(1, f'Change recording failed: {error}\n')
|
||||
@@ -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')
|
||||
@@ -0,0 +1,278 @@
|
||||
"""Exercise real file/index boundaries in one disposable, local-only Git fixture."""
|
||||
import copy
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import tarfile
|
||||
import unittest
|
||||
import zipfile
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from source_provenance import (BASELINE_SHA256, UPSTREAM_COMMIT, expected_files, identity,
|
||||
strict_json, verify_packaged_provenance, verify_source)
|
||||
|
||||
REPOSITORY = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
class SourceProvenanceTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
workspace = (REPOSITORY / 'work/demo-source-change-tests').resolve()
|
||||
workspace.mkdir(parents=True, exist_ok=True)
|
||||
cls.scratch = tempfile.TemporaryDirectory(prefix='fixture-', dir=workspace)
|
||||
cls.root = Path(cls.scratch.name).resolve()
|
||||
assert cls.root.is_relative_to(workspace) and cls.root != workspace
|
||||
cls.demo = cls.root / 'demo'
|
||||
cls.demo.mkdir()
|
||||
shutil.copyfile(REPOSITORY / 'demo/snapshot.json', cls.demo / 'snapshot.json')
|
||||
shutil.copytree(REPOSITORY / 'demo/tikzrefinery', cls.demo / 'tikzrefinery')
|
||||
(cls.demo / 'ci').mkdir()
|
||||
for name in ['source_provenance.py', 'record-source-change.py']:
|
||||
shutil.copyfile(REPOSITORY / 'demo/ci' / name, cls.demo / 'ci' / name)
|
||||
cls.manifest = strict_json((cls.demo / 'snapshot.json').read_bytes())
|
||||
cls.original = {name: (cls.demo / 'tikzrefinery' / name).read_bytes()
|
||||
for name in cls.manifest['files']}
|
||||
cls.git('init', '-q')
|
||||
cls.git('config', 'core.autocrlf', 'false')
|
||||
cls.git('add', '-f', 'demo')
|
||||
# Git for Windows may not infer executable bits. Restore pinned modes.
|
||||
for name, item in cls.manifest['files'].items():
|
||||
if item['mode'] == '100755':
|
||||
cls.git('update-index', '--chmod=+x', 'demo/tikzrefinery/' + name)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
# Absolute scratch target was validated under this task's workspace above.
|
||||
cls.scratch.cleanup()
|
||||
|
||||
@classmethod
|
||||
def git(cls, *args):
|
||||
return subprocess.check_output(['git', *args], cwd=cls.root, stderr=subprocess.STDOUT)
|
||||
|
||||
def setUp(self):
|
||||
self.record_path = self.demo / 'source-change.json'
|
||||
self.record_path.unlink(missing_ok=True)
|
||||
for path in (self.demo / 'tikzrefinery').rglob('*'):
|
||||
if path.is_file() and path.relative_to(self.demo / 'tikzrefinery').as_posix() not in self.original:
|
||||
path.unlink()
|
||||
for name, data in self.original.items():
|
||||
path = self.demo / 'tikzrefinery' / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
shutil.copyfile(REPOSITORY / 'demo/snapshot.json', self.demo / 'snapshot.json')
|
||||
self.git('add', '-f', '-A', 'demo')
|
||||
for name, item in self.manifest['files'].items():
|
||||
if item['mode'] == '100755':
|
||||
self.git('update-index', '--chmod=+x', 'demo/tikzrefinery/' + name)
|
||||
|
||||
def modification(self):
|
||||
name = 'README.md'
|
||||
data = self.original[name] + b'\nTest fixture change only.\n'
|
||||
(self.demo / 'tikzrefinery' / name).write_bytes(data)
|
||||
return self.record([dict(before=name, after=dict(path=name, **identity(data)))])
|
||||
|
||||
def record(self, changes):
|
||||
record = dict(schema_version=1, upstream_commit=UPSTREAM_COMMIT,
|
||||
baseline_manifest_sha256=BASELINE_SHA256, change_id='test-fixture',
|
||||
issue_url='https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/issues/999999',
|
||||
description='Synthetic local fixture; no published issue or product change.', changes=changes)
|
||||
self.record_path.write_text(json.dumps(record), encoding='utf-8')
|
||||
return record
|
||||
|
||||
def test_original_files_and_index(self):
|
||||
self.assertEqual(verify_source(self.demo, True)['verified_files'], 435)
|
||||
|
||||
def test_modified_source_requires_record(self):
|
||||
self.modification()
|
||||
self.record_path.unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'identity differs'):
|
||||
verify_source(self.demo)
|
||||
|
||||
def test_record_and_source_must_both_be_staged(self):
|
||||
self.modification()
|
||||
self.assertEqual(verify_source(self.demo)['source_state'], 'recorded-change')
|
||||
with self.assertRaisesRegex(ValueError, 'Git index differs'):
|
||||
verify_source(self.demo, True)
|
||||
self.git('add', '-f', 'demo/tikzrefinery/README.md')
|
||||
with self.assertRaisesRegex(ValueError, 'Git index differs'):
|
||||
verify_source(self.demo, True)
|
||||
self.git('add', '-f', 'demo/source-change.json')
|
||||
self.assertTrue(verify_source(self.demo, True)['git_index_verified'])
|
||||
self.record_path.write_bytes(self.record_path.read_bytes() + b'\n')
|
||||
with self.assertRaisesRegex(ValueError, 'Git index differs'):
|
||||
verify_source(self.demo, True)
|
||||
self.record_path.unlink()
|
||||
with self.assertRaises(ValueError):
|
||||
verify_source(self.demo, True)
|
||||
|
||||
def test_rename_add_delete(self):
|
||||
old, new = 'README.md', 'README-renamed.md'
|
||||
(self.demo / 'tikzrefinery' / old).rename(self.demo / 'tikzrefinery' / new)
|
||||
self.record([dict(before=old, after=dict(path=new, **self.manifest['files'][old]))])
|
||||
self.assertEqual(verify_source(self.demo)['verified_files'], 435)
|
||||
self.git('add', '-f', '-A', 'demo')
|
||||
self.assertTrue(verify_source(self.demo, True)['git_index_verified'])
|
||||
(self.demo / 'tikzrefinery' / new).unlink()
|
||||
added = self.demo / 'tikzrefinery/new.txt'
|
||||
added.write_bytes(b'new\n')
|
||||
self.record([dict(before=old, after=None), dict(before=None, after=dict(path='new.txt', **identity(b'new\n')))])
|
||||
self.assertEqual(verify_source(self.demo)['verified_files'], 435)
|
||||
|
||||
def test_missing_original_asset_rejected_even_if_on_disk(self):
|
||||
self.git('rm', '--cached', '-f', 'demo/tikzrefinery/documents/assets/loop-example/loop-boxes.dvi')
|
||||
self.assertEqual(verify_source(self.demo)['verified_files'], 435)
|
||||
with self.assertRaisesRegex(ValueError, 'Git index differs'):
|
||||
verify_source(self.demo, True)
|
||||
|
||||
def test_missing_extra_or_modified_unlisted_source_rejected(self):
|
||||
self.modification()
|
||||
path = self.demo / 'tikzrefinery/CHANGELOG.md'
|
||||
path.write_bytes(b'unlisted edit')
|
||||
with self.assertRaisesRegex(ValueError, 'identity differs'):
|
||||
verify_source(self.demo)
|
||||
path.unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'Source tree differs'):
|
||||
verify_source(self.demo)
|
||||
path.write_bytes(self.original['CHANGELOG.md'])
|
||||
(self.demo / 'tikzrefinery/extra.txt').write_bytes(b'extra')
|
||||
with self.assertRaisesRegex(ValueError, 'Source tree differs'):
|
||||
verify_source(self.demo)
|
||||
|
||||
def test_original_manifest_cannot_be_rewritten(self):
|
||||
self.modification()
|
||||
path = self.demo / 'snapshot.json'
|
||||
path.write_bytes(path.read_bytes() + b'\n')
|
||||
with self.assertRaisesRegex(ValueError, 'baseline manifest changed'):
|
||||
verify_source(self.demo)
|
||||
|
||||
def test_invalid_records_rejected(self):
|
||||
valid = self.modification()
|
||||
malformed = []
|
||||
for field, value in [('schema_version', True), ('issue_url', 'https://example.com/issues/1'),
|
||||
('baseline_manifest_sha256', '0'*64), ('changes', []), ('unknown', True)]:
|
||||
row = copy.deepcopy(valid)
|
||||
row[field] = value
|
||||
malformed.append(row)
|
||||
for path in ['../escape', '/escape', 'a\\b', 'a/../b', '.git/config', '.Git/config',
|
||||
'README.md/child', 'readme.md/child']:
|
||||
row = copy.deepcopy(valid)
|
||||
row['changes'][0]['after']['path'] = path
|
||||
# Preserve README as an unchanged original for the directory collision case.
|
||||
row['changes'][0]['before'] = None
|
||||
malformed.append(row)
|
||||
row = copy.deepcopy(valid)
|
||||
row['changes'] *= 2
|
||||
malformed.append(row)
|
||||
for after in [dict(path='README.md', **self.manifest['files']['README.md']),
|
||||
dict(path='CHANGELOG.md', **identity(b'collision')),
|
||||
dict(path='readme.md', **identity(b'case collision'))]:
|
||||
row = copy.deepcopy(valid)
|
||||
row['changes'][0]['after'] = after
|
||||
if after['path'] == 'readme.md':
|
||||
row['changes'][0]['before'] = None
|
||||
malformed.append(row)
|
||||
for row in malformed:
|
||||
with self.subTest(record=row), self.assertRaises(ValueError):
|
||||
expected_files(self.manifest, row)
|
||||
with self.assertRaisesRegex(ValueError, 'Duplicate JSON key'):
|
||||
strict_json('{"changes":[],"changes":[]}')
|
||||
self.record_path.write_text('null')
|
||||
with self.assertRaisesRegex(ValueError, 'cannot be null'):
|
||||
verify_source(self.demo)
|
||||
|
||||
def test_package_metadata_tracks_declared_tree(self):
|
||||
self.modification()
|
||||
proof = verify_source(self.demo)
|
||||
expected = expected_files(self.manifest, proof['source_change_record'])
|
||||
hashes = {'snapshot.json': BASELINE_SHA256, 'source-change.json': proof['source_change_sha256'],
|
||||
**{'tikzrefinery/' + name: item['sha256'] for name, item in expected.items()}}
|
||||
record = dict(source_verification=proof, source_sha256=hashes, upstream_commit=UPSTREAM_COMMIT,
|
||||
application_baseline='0.1.4-alpha', execution='local test fixture')
|
||||
verify_packaged_provenance(record, self.manifest)
|
||||
record['execution'] = 'Jenkins'
|
||||
with self.assertRaisesRegex(ValueError, 'indexed source'):
|
||||
verify_packaged_provenance(record, self.manifest)
|
||||
record['execution'] = 'local test fixture'
|
||||
hashes['tikzrefinery/README.md'] = '0'*64
|
||||
with self.assertRaisesRegex(ValueError, 'inventory differs'):
|
||||
verify_packaged_provenance(record, self.manifest)
|
||||
|
||||
def test_record_generator_and_overwrite_guard(self):
|
||||
self.modification()
|
||||
self.record_path.unlink()
|
||||
command = [sys.executable, '-B', str(self.demo / 'ci/record-source-change.py'),
|
||||
'--issue-url', 'https://git.yebilly.me/ssw590-group1/vpn-dns-gateway/issues/999999',
|
||||
'--change-id', 'test-fixture', '--description', 'Synthetic local test only.']
|
||||
result = subprocess.run(command, capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(verify_source(self.demo)['source_state'], 'recorded-change')
|
||||
data = self.record_path.read_bytes()
|
||||
result = subprocess.run(command, capture_output=True, text=True)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual(self.record_path.read_bytes(), data)
|
||||
|
||||
def test_saved_oci_bundle_provenance(self):
|
||||
# Synthetic transport fixture, not a real image, Jenkins run or behavior claim.
|
||||
for changed in [False, True]:
|
||||
with self.subTest(changed=changed):
|
||||
if changed:
|
||||
self.modification()
|
||||
proof = verify_source(self.demo)
|
||||
expected = expected_files(self.manifest, proof['source_change_record'])
|
||||
record = dict(delivery_version='9.9.9', execution='synthetic local test fixture',
|
||||
application_baseline='0.1.4-alpha', upstream_commit=UPSTREAM_COMMIT,
|
||||
source_verification=proof, source_sha256={
|
||||
'snapshot.json': BASELINE_SHA256,
|
||||
**{'tikzrefinery/' + name: value['sha256'] for name, value in expected.items()}})
|
||||
bundle_files = {'upstream-snapshot.json': (self.demo / 'snapshot.json').read_bytes()}
|
||||
if changed:
|
||||
record['source_sha256']['source-change.json'] = proof['source_change_sha256']
|
||||
bundle_files['source-change.json'] = self.record_path.read_bytes()
|
||||
bundle_files['delivery-info.json'] = json.dumps(record).encode()
|
||||
layer_stream = io.BytesIO()
|
||||
def add(tar, name, data):
|
||||
item = tarfile.TarInfo(name)
|
||||
item.size = len(data)
|
||||
tar.addfile(item, io.BytesIO(data))
|
||||
with tarfile.open(fileobj=layer_stream, mode='w') as layer:
|
||||
for name, data in bundle_files.items():
|
||||
add(layer, 'opt/tikzrefinery/' + name, data)
|
||||
blobs = {}
|
||||
def blob(data):
|
||||
digest = hashlib.sha256(data).hexdigest()
|
||||
blobs['blobs/sha256/' + digest] = data
|
||||
return dict(digest='sha256:' + digest, size=len(data))
|
||||
image_manifest = dict(config=blob(b'{}'), layers=[blob(layer_stream.getvalue())])
|
||||
descriptor = blob(json.dumps(image_manifest).encode())
|
||||
record.update(application_image='synthetic-fixture:9.9.9', application_image_id=descriptor['digest'])
|
||||
artifacts = self.root / 'artifacts'
|
||||
artifacts.mkdir(exist_ok=True)
|
||||
archive_path = artifacts / 'TikZRefinery-9.9.9-linux-image.tar.gz'
|
||||
with tarfile.open(archive_path, 'w:gz') as archive:
|
||||
for name, data in {**blobs,
|
||||
'index.json': json.dumps(dict(manifests=[descriptor])).encode(),
|
||||
'manifest.json': json.dumps([dict(RepoTags=[record['application_image']])]).encode()}.items():
|
||||
add(archive, name, data)
|
||||
record['image_archive_sha256'] = hashlib.sha256(archive_path.read_bytes()).hexdigest()
|
||||
with zipfile.ZipFile(artifacts / 'TikZRefinery-9.9.9-architecture.zip', 'w') as docs:
|
||||
docs.writestr('html/index.html', 'Synthetic fixture')
|
||||
def write_record_and_sums():
|
||||
(artifacts / 'delivery-info.json').write_text(json.dumps(record))
|
||||
(artifacts / 'SHA256SUMS').write_text('\n'.join(
|
||||
hashlib.sha256(path.read_bytes()).hexdigest() + ' ' + path.name
|
||||
for path in sorted(artifacts.iterdir()) if path.name != 'SHA256SUMS') + '\n')
|
||||
write_record_and_sums()
|
||||
command = [sys.executable, '-B', str(REPOSITORY / 'demo/ci/verify-artifacts.py'), str(artifacts)]
|
||||
result = subprocess.run(command, capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
# Outer hashes are recalculated: only the actual image-bundle comparison catches this.
|
||||
record['downstream_commit_or_parent'] = 'tampered outer metadata'
|
||||
write_record_and_sums()
|
||||
self.assertNotEqual(subprocess.run(command, capture_output=True).returncode, 0)
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -7,15 +7,28 @@ import sys
|
||||
import tarfile
|
||||
import zipfile
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from source_provenance import BASELINE_SHA256, load_definition, strict_json, verify_packaged_provenance
|
||||
|
||||
folder = Path(sys.argv[1] if len(sys.argv) > 1 else 'build/demo/artifacts').resolve()
|
||||
actual_hashes = {}
|
||||
for line in (folder / 'SHA256SUMS').read_text().splitlines():
|
||||
expected, name = line.split(' ', 1)
|
||||
assert Path(name).name == name and re.fullmatch(r'[0-9a-f]{64}', expected)
|
||||
assert Path(name).name == name and name not in actual_hashes and re.fullmatch(r'[0-9a-f]{64}', expected)
|
||||
with (folder / name).open('rb') as stream:
|
||||
assert hashlib.file_digest(stream, 'sha256').hexdigest() == expected, name
|
||||
record = json.loads((folder / 'delivery-info.json').read_text())
|
||||
actual_hashes[name] = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
assert actual_hashes[name] == expected, name
|
||||
record = strict_json((folder / 'delivery-info.json').read_bytes())
|
||||
if 'source_verification' in record:
|
||||
baseline, _, _, _ = load_definition(Path(__file__).resolve().parents[1])
|
||||
verify_packaged_provenance(record, baseline)
|
||||
else:
|
||||
print('Legacy artifact: transport/OCI verification only; no new source-change proof is claimed.')
|
||||
version = record['delivery_version']
|
||||
assert re.fullmatch(r'\d+\.\d+\.\d+', version)
|
||||
assert {'delivery-info.json', f'TikZRefinery-{version}-linux-image.tar.gz',
|
||||
f'TikZRefinery-{version}-architecture.zip'} <= set(actual_hashes)
|
||||
assert record['image_archive_sha256'] == actual_hashes[f'TikZRefinery-{version}-linux-image.tar.gz']
|
||||
with tarfile.open(folder / f'TikZRefinery-{version}-linux-image.tar.gz', 'r:gz') as archive:
|
||||
compatibility = json.load(archive.extractfile('manifest.json'))[0]
|
||||
assert record['application_image'] in compatibility['RepoTags']
|
||||
@@ -34,6 +47,25 @@ with tarfile.open(folder / f'TikZRefinery-{version}-linux-image.tar.gz', 'r:gz')
|
||||
assert members[name].isfile(), name
|
||||
with archive.extractfile(name) as stream:
|
||||
assert 'sha256:' + hashlib.file_digest(stream, 'sha256').hexdigest() == reference['digest'], name
|
||||
if 'source_verification' in record:
|
||||
# application.Dockerfile's final filesystem layer is the complete bundle COPY.
|
||||
# Check actual packaged metadata without extracting files onto the workstation.
|
||||
with tarfile.open(fileobj=archive.extractfile(blob_name(manifest['layers'][-1]['digest'])), mode='r:*') as bundle:
|
||||
def bundled_bytes(name):
|
||||
member = bundle.getmember('opt/tikzrefinery/' + name)
|
||||
assert member.isfile(), name
|
||||
return bundle.extractfile(member).read()
|
||||
assert hashlib.sha256(bundled_bytes('upstream-snapshot.json')).hexdigest() == BASELINE_SHA256
|
||||
packaged_record = strict_json(bundled_bytes('delivery-info.json'))
|
||||
assert packaged_record == {key: value for key, value in record.items()
|
||||
if key not in {'application_image', 'application_image_id', 'image_archive_sha256'}}
|
||||
proof = record['source_verification']
|
||||
if proof['source_change_record'] is not None:
|
||||
change_bytes = bundled_bytes('source-change.json')
|
||||
assert hashlib.sha256(change_bytes).hexdigest() == proof['source_change_sha256']
|
||||
assert strict_json(change_bytes) == proof['source_change_record']
|
||||
else:
|
||||
assert 'opt/tikzrefinery/source-change.json' not in bundle.getnames()
|
||||
with zipfile.ZipFile(folder / f'TikZRefinery-{version}-architecture.zip') as docs:
|
||||
assert 'html/index.html' in docs.namelist()
|
||||
print(f'PASS: version {version}, artifact checksums, OCI manifest/config/{len(manifest["layers"])} layers and architecture ZIP')
|
||||
|
||||
+10
-37
@@ -1,45 +1,18 @@
|
||||
"""Verify the exact frozen source input, independent of either Git checkout."""
|
||||
"""Verify the frozen import or a precisely recorded, issue-linked downstream tree."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from source_provenance import verify_source
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--require-tracked', action='store_true',
|
||||
help='Also verify that the Git index contains every original blob.')
|
||||
help='Also verify source blobs and provenance records against the Git index.')
|
||||
args = parser.parse_args()
|
||||
|
||||
DEMO = Path(__file__).resolve().parents[1]
|
||||
SOURCE = DEMO / 'tikzrefinery'
|
||||
manifest = json.loads((DEMO / 'snapshot.json').read_text(encoding='utf-8'))
|
||||
expected = manifest['files']
|
||||
if args.require_tracked:
|
||||
index = subprocess.check_output(
|
||||
['git', 'ls-files', '--stage', '-z', '--', 'demo/tikzrefinery'], cwd=DEMO.parent)
|
||||
tracked = {}
|
||||
for row in index.decode('utf-8').split('\0'):
|
||||
if not row:
|
||||
continue
|
||||
metadata, path = row.split('\t', 1)
|
||||
mode, blob, stage = metadata.split()
|
||||
assert stage == '0', ('Unresolved snapshot index entry', path)
|
||||
tracked[path.removeprefix('demo/tikzrefinery/')] = (mode, blob)
|
||||
assert set(tracked) == set(expected), {
|
||||
'untracked_snapshot_files': sorted(set(expected) - set(tracked)),
|
||||
'unexpected_tracked_files': sorted(set(tracked) - set(expected))}
|
||||
for name, identity in expected.items():
|
||||
assert tracked[name] == (identity['mode'], identity['git_blob']), (
|
||||
'Git index differs from the frozen upstream blob', name)
|
||||
actual = {p.relative_to(SOURCE).as_posix() for p in SOURCE.rglob('*') if p.is_file()}
|
||||
assert actual == set(expected), {'missing': sorted(set(expected) - actual),
|
||||
'extra': sorted(actual - set(expected))}
|
||||
for name, identity in expected.items():
|
||||
data = (SOURCE / name).read_bytes()
|
||||
assert hashlib.sha256(data).hexdigest() == identity['sha256'], name
|
||||
git_blob = hashlib.sha1(b'blob ' + str(len(data)).encode() + b'\0' + data).hexdigest()
|
||||
assert git_blob == identity['git_blob'], name
|
||||
print(json.dumps({'result': 'passed', 'upstream_commit': manifest['upstream_commit'],
|
||||
'application_baseline': manifest['application_baseline'],
|
||||
'verified_files': len(expected),
|
||||
'git_index_verified': args.require_tracked}, indent=2))
|
||||
try:
|
||||
print(json.dumps(verify_source(Path(__file__).resolve().parents[1], args.require_tracked), indent=2))
|
||||
except (ValueError, OSError) as error:
|
||||
parser.exit(1, f'Source verification failed: {error}\n')
|
||||
|
||||
Reference in New Issue
Block a user