Support issue-linked demo source changes
This commit is contained in:
@@ -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)
|
||||
Reference in New Issue
Block a user