refactor(windows): publish Velopack updates through Gitea Releases
This commit is contained in:
1 parent
826745b407
commit
1ef8edc8bc
17 files changed
+519
-87
No files matched your search
+43
-19
@@ -1,19 +1,27 @@
|
||||
"""Package the Windows Release directory and Android production APK."""
|
||||
"""Package Android and audited Velopack Windows installation/update artifacts."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, app_versions, checksum_lines, validate_artifact
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def main():
|
||||
version = re.search(r'^version: (\S+)', (ROOT / 'pubspec.yaml').read_text(), re.M)[1].split('+')[0]
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--vpk', type=Path, required=True, help='Pinned vpk executable or DLL')
|
||||
args = parser.parse_args()
|
||||
version, windows_version = app_versions(ROOT / 'pubspec.yaml')
|
||||
output = ROOT / 'dist'
|
||||
output.mkdir(exist_ok=True)
|
||||
# Repeated builds must not accidentally upload a previous version's files.
|
||||
if output.exists() and any(output.iterdir()):
|
||||
raise ValueError('dist must be empty; use a clean release workspace')
|
||||
apk = ROOT / 'build/app/outputs/flutter-apk/app-production-release.apk'
|
||||
windows = ROOT / 'build/windows/x64/production/runner/Release'
|
||||
if not apk.is_file() or not (windows / 'cutdex.exe').is_file():
|
||||
@@ -25,23 +33,39 @@ def main():
|
||||
raise ValueError(f'APK missing Flutter ABI: {abi}')
|
||||
if any(name.startswith('lib/armeabi-v7a/') for name in names):
|
||||
raise ValueError('APK must use supported 64-bit ABIs only')
|
||||
shutil.copyfile(apk, output / f'cutdex-{version}-android.apk')
|
||||
sys.path.insert(0, str(ROOT / 'tool/windows'))
|
||||
from check_windows_release import audit
|
||||
unused_jni = windows / 'dartjni.dll'
|
||||
if unused_jni.exists():
|
||||
unused_jni.unlink()
|
||||
report = audit(windows, require_processing=False)
|
||||
(output / 'windows-dependency-audit.json').write_text(json.dumps(report, indent=2) + '\n')
|
||||
package = output / f'cutdex-{version}-windows-x64.zip'
|
||||
with zipfile.ZipFile(package, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
|
||||
for path in sorted(windows.rglob('*')):
|
||||
if path.is_file() and path.suffix.lower() not in ('.pdb', '.lib', '.exp'):
|
||||
archive.write(path, f'cutdex-{version}/' + path.relative_to(windows).as_posix())
|
||||
files = sorted(output.glob('*.apk')) + sorted(output.glob('*.zip'))
|
||||
manifest = {path.name: hashlib.file_digest(path.open('rb'), 'sha256').hexdigest() for path in files}
|
||||
(output / 'SHA256SUMS').write_text(''.join(f'{digest} {name}\n' for name, digest in manifest.items()))
|
||||
(output / 'release-manifest.json').write_text(json.dumps({'version': version, 'files': manifest, 'androidSigning': 'debug', 'processingWorkersBundled': False}, indent=2) + '\n')
|
||||
from windows_updates import package_app
|
||||
with tempfile.TemporaryDirectory(prefix='cutdex-release-') as directory:
|
||||
temporary = Path(directory)
|
||||
staged, releases = temporary / 'app', temporary / 'releases'
|
||||
shutil.copytree(windows, staged,
|
||||
ignore=shutil.ignore_patterns('processing', '*.pdb', '*.lib', '*.exp', 'dartjni.dll'))
|
||||
report = audit(staged, require_processing=False)
|
||||
checksums = {}
|
||||
for path in sorted(staged.rglob('*')):
|
||||
if path.is_file():
|
||||
with path.open('rb') as stream:
|
||||
checksums[path.relative_to(staged).as_posix()] = hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
(staged / 'checksums.json').write_text(json.dumps(checksums), encoding='utf-8')
|
||||
result = package_app(staged, releases, args.vpk, require_processing=False)
|
||||
if result['version'] != windows_version:
|
||||
raise ValueError('Built Windows version differs from pubspec')
|
||||
contents = {f'cutdex-{version}-android.apk': apk.read_bytes(),
|
||||
AUDIT: (json.dumps(report, indent=2) + '\n').encode()}
|
||||
for path in releases.iterdir():
|
||||
if path.name in {FEED, INSTALLER, PORTABLE} or path.suffix == '.nupkg':
|
||||
contents[path.name] = path.read_bytes()
|
||||
files = {name: hashlib.sha256(body).hexdigest() for name, body in contents.items()}
|
||||
manifest = {'version': version, 'files': files, 'windowsUpdateVersion': windows_version,
|
||||
'windowsPackageId': 'Cutdex', 'windowsChannel': 'win-x64',
|
||||
'androidSigning': 'debug', 'processingWorkersBundled': False}
|
||||
contents['SHA256SUMS'] = checksum_lines(files).encode()
|
||||
contents['release-manifest.json'] = (json.dumps(manifest, indent=2) + '\n').encode()
|
||||
validate_artifact(contents, version, windows_version)
|
||||
output.mkdir(exist_ok=True)
|
||||
for name, body in contents.items():
|
||||
(output / name).write_bytes(body)
|
||||
print(json.dumps(manifest, indent=2))
|
||||
|
||||
|
||||
|
||||
@@ -1,24 +1,20 @@
|
||||
"""Promote packages from a successful main CI for the exact release commit."""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
import zipfile
|
||||
|
||||
from release_artifacts import app_versions, validate_artifact
|
||||
|
||||
SERVER = 'https://git.orangraph.com'
|
||||
REPO = os.environ['GITEA_REPOSITORY']
|
||||
TOKEN = os.environ['GITEA_TOKEN']
|
||||
BASE = f'{SERVER}/api/v1/repos/{REPO}'
|
||||
|
||||
|
||||
def request(url, data=None, method=None, content_type='application/json'):
|
||||
headers = {'Authorization': f'token {TOKEN}'}
|
||||
headers = {'Authorization': 'token ' + os.environ['GITEA_TOKEN']}
|
||||
if data is not None:
|
||||
headers['Content-Type'] = content_type
|
||||
if isinstance(data, dict):
|
||||
@@ -37,57 +33,56 @@ def download(asset):
|
||||
|
||||
|
||||
def main():
|
||||
repo = os.environ['GITEA_REPOSITORY']
|
||||
base = f'{SERVER}/api/v1/repos/{repo}'
|
||||
sha = os.environ['GITEA_SHA']
|
||||
tag = os.environ['RELEASE_TAG']
|
||||
version = re.search(r'^version: (\S+)', Path('pubspec.yaml').read_text(), re.M)[1].split('+')[0]
|
||||
version, windows_version = app_versions('pubspec.yaml')
|
||||
if tag != f'v{version}':
|
||||
raise ValueError('Release tag must match pubspec version')
|
||||
runs = request(f'{BASE}/actions/runs?limit=100')['workflow_runs']
|
||||
runs = request(f'{base}/actions/runs?limit=100')['workflow_runs']
|
||||
matches = [run for run in runs if run['head_sha'] == sha and run['path'].endswith('@refs/heads/main') and run['conclusion'] == 'success' and Path(run['path'].split('@')[0]).name == 'ci.yml']
|
||||
if not matches:
|
||||
raise ValueError('No successful main CI for this exact commit; run CI before releasing')
|
||||
run = max(matches, key=lambda item: item['id'])
|
||||
artifacts = request(f"{BASE}/actions/runs/{run['id']}/artifacts")['artifacts']
|
||||
artifacts = request(f"{base}/actions/runs/{run['id']}/artifacts")['artifacts']
|
||||
found = [item for item in artifacts if item['name'] == 'cutdex-release-packages' and not item.get('expired', False)]
|
||||
if len(found) != 1:
|
||||
raise ValueError('Expected one validated application artifact')
|
||||
data = request(f"{BASE}/actions/artifacts/{found[0]['id']}/zip")
|
||||
data = request(f"{base}/actions/artifacts/{found[0]['id']}/zip")
|
||||
with zipfile.ZipFile(io.BytesIO(data)) as archive:
|
||||
contents = {item.filename: archive.read(item) for item in archive.infolist() if not item.is_dir()}
|
||||
manifest = json.loads(contents['release-manifest.json'])
|
||||
if manifest['version'] != version:
|
||||
raise ValueError('Artifact version does not match release')
|
||||
expected = {f'cutdex-{version}-android.apk', f'cutdex-{version}-windows-x64.zip'}
|
||||
if set(manifest['files']) != expected:
|
||||
raise ValueError('Release requires both Android and Windows packages')
|
||||
for name, digest in manifest['files'].items():
|
||||
if hashlib.sha256(contents[name]).hexdigest() != digest:
|
||||
raise ValueError(f'Package checksum mismatch: {name}')
|
||||
releases = request(f'{BASE}/releases?limit=100')
|
||||
entries = [item for item in archive.infolist() if not item.is_dir()]
|
||||
if len({item.filename for item in entries}) != len(entries):
|
||||
raise ValueError('Duplicate artifact filenames')
|
||||
contents = {item.filename: archive.read(item) for item in entries}
|
||||
validate_artifact(contents, version, windows_version)
|
||||
releases = request(f'{base}/releases?limit=100')
|
||||
existing = [release for release in releases if release['tag_name'] == tag]
|
||||
if existing:
|
||||
release = existing[0]
|
||||
if not release['draft']:
|
||||
raise ValueError('Release already published; choose a new version')
|
||||
else:
|
||||
release = request(f'{BASE}/releases', {'tag_name': tag, 'target_commitish': sha, 'name': f'Cutdex {version}', 'draft': True, 'body': f'Windows x64 portable ZIP and Android ARM64/x86_64 APK. Android currently uses the project debug signing key. Processing workers and models are distributed separately. Verified CI run: {run["id"]}.'}, 'POST')
|
||||
assets = request(f"{BASE}/releases/{release['id']}/assets")
|
||||
release = request(f'{base}/releases', {'tag_name': tag, 'target_commitish': sha, 'name': f'Cutdex {version}', 'draft': True, 'prerelease': False, 'body': f'Windows x64 Velopack installer EXE, Portable ZIP, full update package and channel index; Android ARM64/x86_64 APK. Windows update version: {windows_version}. Android currently uses the project debug signing key. Processing workers and models are distributed separately. Verified CI run: {run["id"]}.'}, 'POST')
|
||||
assets = request(f"{base}/releases/{release['id']}/assets")
|
||||
for name, body in contents.items():
|
||||
if '/' in name or '\\' in name:
|
||||
raise ValueError('Unexpected artifact path')
|
||||
prior = [asset for asset in assets if asset['name'] == name]
|
||||
if prior:
|
||||
downloaded = download(prior[0])
|
||||
if downloaded != body:
|
||||
raise ValueError(f'Refusing to replace Release asset: {name}')
|
||||
continue
|
||||
boundary = uuid.uuid4().hex
|
||||
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode() + body + f'\r\n--{boundary}--\r\n'.encode())
|
||||
asset = request(f"{BASE}/releases/{release['id']}/assets?name={urllib.parse.quote(name)}", payload, 'POST', f'multipart/form-data; boundary={boundary}')
|
||||
if download(asset) != body:
|
||||
raise ValueError(f'Remote checksum verification failed: {name}')
|
||||
request(f"{BASE}/releases/{release['id']}", {'draft': False}, 'PATCH')
|
||||
print(f'{SERVER}/{REPO}/releases/tag/{tag}')
|
||||
request(f"{base}/releases/{release['id']}/assets?name={urllib.parse.quote(name)}", payload, 'POST', f'multipart/form-data; boundary={boundary}')
|
||||
# Refuse publishing a resumed draft containing unrelated/stale attachments.
|
||||
final_assets = request(f"{base}/releases/{release['id']}/assets")
|
||||
if len(final_assets) != len(contents) or {asset['name'] for asset in final_assets} != set(contents):
|
||||
raise ValueError('Draft Release attachments differ from the validated artifact')
|
||||
for asset in final_assets:
|
||||
if download(asset) != contents[asset['name']]:
|
||||
raise ValueError('Final Release attachment verification failed: ' + asset['name'])
|
||||
request(f"{base}/releases/{release['id']}", {'draft': False, 'prerelease': False}, 'PATCH')
|
||||
print(f'{SERVER}/{repo}/releases/tag/{tag}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Validate the complete app artifact before creating or publishing a Release."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'windows'))
|
||||
from update_versions import update_version
|
||||
|
||||
FEED = 'releases.win-x64.json'
|
||||
INSTALLER = 'Cutdex-win-x64-Setup.exe'
|
||||
PORTABLE = 'Cutdex-win-x64-Portable.zip'
|
||||
AUDIT = 'windows-dependency-audit.json'
|
||||
|
||||
|
||||
def app_versions(pubspec):
|
||||
match = re.search(r'^version:\s*(\d+\.\d+\.\d+)\+(\d+)\s*$',
|
||||
Path(pubspec).read_text(encoding='utf-8'), re.M)
|
||||
if not match:
|
||||
raise ValueError('Application version must include a numeric build number')
|
||||
return match[1], update_version(match[1], match[2])
|
||||
|
||||
|
||||
def checksum_lines(files):
|
||||
return ''.join(f'{files[name]} {name}\n' for name in sorted(files))
|
||||
|
||||
|
||||
def validate_artifact(contents, version, windows_version):
|
||||
manifest = json.loads(contents['release-manifest.json'])
|
||||
if (manifest['version'] != version or manifest.get('windowsUpdateVersion') != windows_version
|
||||
or manifest.get('windowsPackageId') != 'Cutdex'
|
||||
or manifest.get('windowsChannel') != 'win-x64'):
|
||||
raise ValueError('Artifact version, identity or channel does not match release')
|
||||
feed = json.loads(contents[FEED])
|
||||
assets = feed.get('Assets', [])
|
||||
if len(assets) != 1:
|
||||
raise ValueError('Release index must contain exactly one complete full package')
|
||||
asset = assets[0]
|
||||
if (asset.get('PackageId') != 'Cutdex' or asset.get('Version') != windows_version
|
||||
or asset.get('Type') != 'Full'):
|
||||
raise ValueError('Update package identity, version or type does not match release')
|
||||
package = asset.get('FileName', '')
|
||||
if not re.fullmatch(r'[A-Za-z0-9_.-]+\.nupkg', package):
|
||||
raise ValueError('Invalid update package filename')
|
||||
expected = {f'cutdex-{version}-android.apk', INSTALLER, PORTABLE, FEED, AUDIT, package}
|
||||
if set(manifest['files']) != expected or set(contents) != expected | {'SHA256SUMS', 'release-manifest.json'}:
|
||||
raise ValueError('Release requires APK, installer, Portable ZIP, index, full package and audit')
|
||||
for name, digest in manifest['files'].items():
|
||||
if hashlib.sha256(contents[name]).hexdigest() != digest:
|
||||
raise ValueError(f'Package checksum mismatch: {name}')
|
||||
payload = contents[package]
|
||||
if (asset.get('Size') != len(payload)
|
||||
or str(asset.get('SHA256', '')).lower() != hashlib.sha256(payload).hexdigest()
|
||||
or str(asset.get('SHA1', '')).lower() != hashlib.sha1(payload).hexdigest()):
|
||||
raise ValueError('Update index checksums do not match the full package')
|
||||
if contents['SHA256SUMS'].decode('utf-8') != checksum_lines(manifest['files']):
|
||||
raise ValueError('SHA256SUMS differs from the release manifest')
|
||||
return manifest
|
||||
@@ -0,0 +1,98 @@
|
||||
import importlib.util
|
||||
import io
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
import unittest
|
||||
import urllib.parse
|
||||
import zipfile
|
||||
|
||||
from test_release_artifacts import fixture
|
||||
|
||||
spec = importlib.util.spec_from_file_location('promote_release', Path(__file__).with_name('promote-release.py'))
|
||||
promote = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(promote)
|
||||
|
||||
|
||||
class PromotionTests(unittest.TestCase):
|
||||
def scenario(self, *, extra=False, corrupt_remote=False, corrupt_artifact=False, resume=False, wrong_commit=False):
|
||||
contents = fixture()
|
||||
if corrupt_artifact:
|
||||
contents['Cutdex-win-x64-Setup.exe'] += b'corrupt'
|
||||
archive = io.BytesIO()
|
||||
with zipfile.ZipFile(archive, 'w') as bundle:
|
||||
for name, body in contents.items():
|
||||
bundle.writestr(name, body)
|
||||
stored = dict(contents) if resume else {}
|
||||
if extra:
|
||||
stored['stale.zip'] = b'stale'
|
||||
calls = []
|
||||
|
||||
def assets():
|
||||
return [{'name': name} for name in stored]
|
||||
|
||||
def request(url, data=None, method=None, content_type=None):
|
||||
calls.append((method, url))
|
||||
if url.endswith('/actions/runs?limit=100'):
|
||||
return {'workflow_runs': [{'head_sha': 'other' if wrong_commit else 'commit',
|
||||
'path': '.gitea/workflows/ci.yml@refs/heads/main', 'conclusion': 'success', 'id': 1}]}
|
||||
if url.endswith('/actions/runs/1/artifacts'):
|
||||
return {'artifacts': [{'name': 'cutdex-release-packages', 'id': 2}]}
|
||||
if url.endswith('/actions/artifacts/2/zip'):
|
||||
return archive.getvalue()
|
||||
if url.endswith('/releases?limit=100'):
|
||||
return [{'id': 3, 'tag_name': 'v0.1.0', 'draft': True}] if resume else []
|
||||
if url.endswith('/releases') and method == 'POST':
|
||||
self.assertTrue(data['draft'])
|
||||
return {'id': 3}
|
||||
if url.endswith('/releases/3/assets'):
|
||||
return assets()
|
||||
if '/assets?name=' in url and method == 'POST':
|
||||
name = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)['name'][0]
|
||||
boundary = content_type.split('boundary=')[1].encode()
|
||||
stored[name] = data.split(b'\r\n\r\n', 1)[1].rsplit(b'\r\n--' + boundary, 1)[0]
|
||||
return {'name': name}
|
||||
if url.endswith('/releases/3') and method == 'PATCH':
|
||||
self.assertEqual(data, {'draft': False, 'prerelease': False})
|
||||
return {}
|
||||
raise AssertionError('Unexpected request: ' + url)
|
||||
|
||||
def download(asset):
|
||||
body = stored[asset['name']]
|
||||
return body + b'corrupt' if corrupt_remote else body
|
||||
|
||||
environment = {'GITEA_REPOSITORY': 'owner/cutdex', 'GITEA_SHA': 'commit', 'RELEASE_TAG': 'v0.1.0'}
|
||||
with patch.dict('os.environ', environment), patch.object(promote, 'request', side_effect=request), \
|
||||
patch.object(promote, 'download', side_effect=download), \
|
||||
patch.object(promote, 'app_versions', return_value=('0.1.0', '0.1.0-build.2')):
|
||||
if extra or corrupt_remote or corrupt_artifact or wrong_commit:
|
||||
with self.assertRaises(ValueError):
|
||||
promote.main()
|
||||
self.assertFalse(any(method == 'PATCH' for method, _ in calls))
|
||||
if corrupt_artifact or wrong_commit:
|
||||
self.assertFalse(any(method == 'POST' for method, _ in calls))
|
||||
else:
|
||||
promote.main()
|
||||
self.assertEqual(calls[-1][0], 'PATCH')
|
||||
self.assertEqual(set(stored), set(contents))
|
||||
if resume:
|
||||
self.assertFalse(any(method == 'POST' for method, _ in calls))
|
||||
|
||||
def test_complete_draft_is_verified_before_publication(self):
|
||||
self.scenario()
|
||||
|
||||
def test_matching_draft_can_be_resumed_without_replacing_assets(self):
|
||||
self.scenario(resume=True)
|
||||
|
||||
def test_stale_or_corrupt_remote_attachment_keeps_release_draft(self):
|
||||
self.scenario(extra=True)
|
||||
self.scenario(corrupt_remote=True)
|
||||
|
||||
def test_tampered_artifact_never_creates_release(self):
|
||||
self.scenario(corrupt_artifact=True)
|
||||
|
||||
def test_successful_ci_for_other_commit_cannot_publish(self):
|
||||
self.scenario(wrong_commit=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,106 @@
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, app_versions, checksum_lines, validate_artifact
|
||||
|
||||
|
||||
def fixture():
|
||||
package = 'Cutdex-0.1.0-build.2-win-x64-full.nupkg'
|
||||
payload = b'full package'
|
||||
feed = {'Assets': [{'PackageId': 'Cutdex', 'Version': '0.1.0-build.2', 'Type': 'Full',
|
||||
'FileName': package, 'Size': len(payload),
|
||||
'SHA1': hashlib.sha1(payload).hexdigest(),
|
||||
'SHA256': hashlib.sha256(payload).hexdigest()}]}
|
||||
contents = {'cutdex-0.1.0-android.apk': b'apk', INSTALLER: b'exe', PORTABLE: b'zip',
|
||||
FEED: json.dumps(feed).encode(), AUDIT: b'{}', package: payload}
|
||||
manifest = {'version': '0.1.0', 'windowsUpdateVersion': '0.1.0-build.2',
|
||||
'windowsPackageId': 'Cutdex', 'windowsChannel': 'win-x64', 'files': {}}
|
||||
return reseal(contents, manifest)
|
||||
|
||||
|
||||
def reseal(contents, manifest=None):
|
||||
if manifest is None:
|
||||
manifest = json.loads(contents['release-manifest.json'])
|
||||
manifest['files'] = {name: hashlib.sha256(body).hexdigest() for name, body in contents.items()
|
||||
if name not in ['SHA256SUMS', 'release-manifest.json']}
|
||||
contents['SHA256SUMS'] = checksum_lines(manifest['files']).encode()
|
||||
contents['release-manifest.json'] = json.dumps(manifest).encode()
|
||||
return contents
|
||||
|
||||
|
||||
class ReleaseArtifactTests(unittest.TestCase):
|
||||
def validate(self, contents):
|
||||
return validate_artifact(contents, '0.1.0', '0.1.0-build.2')
|
||||
|
||||
def test_complete_installer_portable_and_update_release(self):
|
||||
self.assertEqual(self.validate(fixture())['windowsPackageId'], 'Cutdex')
|
||||
|
||||
def test_missing_or_unexpected_attachments(self):
|
||||
original = fixture()
|
||||
for name in [INSTALLER, PORTABLE, 'Cutdex-0.1.0-build.2-win-x64-full.nupkg']:
|
||||
contents = copy.deepcopy(original)
|
||||
del contents[name]
|
||||
with self.assertRaises(ValueError):
|
||||
self.validate(contents)
|
||||
contents = fixture()
|
||||
contents['stale.zip'] = b'old'
|
||||
with self.assertRaises(ValueError):
|
||||
self.validate(reseal(contents))
|
||||
|
||||
def test_tampered_package_or_checksum_file(self):
|
||||
for name in [INSTALLER, PORTABLE, 'SHA256SUMS']:
|
||||
contents = fixture()
|
||||
contents[name] += b'tampered'
|
||||
with self.assertRaises(ValueError):
|
||||
self.validate(contents)
|
||||
|
||||
def test_wrong_identity_version_delta_or_escaping_filename(self):
|
||||
for key, value in [('PackageId', 'Cutdex.Dev'), ('Version', '0.1.0-build.1'),
|
||||
('Type', 'Delta'), ('FileName', '../outside.nupkg')]:
|
||||
contents = fixture()
|
||||
feed = json.loads(contents[FEED])
|
||||
feed['Assets'][0][key] = value
|
||||
contents[FEED] = json.dumps(feed).encode()
|
||||
with self.assertRaises(ValueError):
|
||||
self.validate(reseal(contents))
|
||||
|
||||
def test_resealed_manifest_cannot_hide_index_checksum_mismatch(self):
|
||||
for field in ['SHA1', 'SHA256', 'Size']:
|
||||
contents = fixture()
|
||||
feed = json.loads(contents[FEED])
|
||||
feed['Assets'][0][field] = 0 if field == 'Size' else '0' * 64
|
||||
contents[FEED] = json.dumps(feed).encode()
|
||||
with self.assertRaisesRegex(ValueError, 'index checksums'):
|
||||
self.validate(reseal(contents))
|
||||
|
||||
def test_stale_or_mixed_index_and_metadata_are_rejected(self):
|
||||
contents = fixture()
|
||||
feed = json.loads(contents[FEED])
|
||||
feed['Assets'].append(dict(feed['Assets'][0]))
|
||||
contents[FEED] = json.dumps(feed).encode()
|
||||
with self.assertRaises(ValueError):
|
||||
self.validate(reseal(contents))
|
||||
for key, value in [('version', '0.0.9'), ('windowsChannel', 'dev-win-x64'),
|
||||
('windowsUpdateVersion', '0.1.0-build.1')]:
|
||||
contents = fixture()
|
||||
manifest = json.loads(contents['release-manifest.json'])
|
||||
manifest[key] = value
|
||||
with self.assertRaises(ValueError):
|
||||
self.validate(reseal(contents, manifest))
|
||||
|
||||
def test_build_number_is_part_of_update_version(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
spec = Path(directory) / 'pubspec.yaml'
|
||||
spec.write_text('name: cutdex\nversion: 0.1.0+2\n')
|
||||
self.assertEqual(app_versions(spec), ('0.1.0', '0.1.0-build.2'))
|
||||
spec.write_text('version: 0.1.0\n')
|
||||
with self.assertRaises(ValueError):
|
||||
app_versions(spec)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user