diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 025b9c7..69a5bf0 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,13 +6,18 @@ on: permissions: contents: read concurrency: - group: release-${{ github.ref }} + group: release-preparation cancel-in-progress: false jobs: validate: + # GitHub restricts draft visibility to push-capable credentials. This job only reads releases. + permissions: + contents: write runs-on: ubuntu-latest outputs: version: ${{ steps.version.outputs.version }} + mode: ${{ steps.preflight.outputs.mode }} + release_run: ${{ steps.preflight.outputs.release_run }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -36,10 +41,21 @@ jobs: with open(os.environ['GITHUB_OUTPUT'], 'a') as output: output.write('version=' + version + '\n') PY + - name: Refuse published versions and identify resumable drafts + id: preflight + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RELEASE_VERSION: ${{ steps.version.outputs.version }} + RELEASE_COMMIT: ${{ github.sha }} + RELEASE_RUN: ${{ github.run_id }} + run: python3 scripts/prepare_release.py --preflight build: + if: needs.validate.outputs.mode == 'new' needs: validate uses: ./.github/workflows/dotnet-ci.yml draft: + if: always() && needs.validate.result == 'success' && (needs.build.result == 'success' || needs.build.result == 'skipped') && needs.validate.outputs.mode != 'complete' needs: [validate, build] runs-on: ubuntu-latest permissions: @@ -53,7 +69,7 @@ jobs: env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} - RELEASE_RUN: ${{ github.run_id }} + RELEASE_RUN: ${{ needs.validate.outputs.release_run }} run: | gh run download "$RELEASE_RUN" --pattern 'spn-*-preview' --dir release-input mkdir release-files @@ -66,9 +82,7 @@ jobs: GH_REPO: ${{ github.repository }} RELEASE_VERSION: ${{ needs.validate.outputs.version }} RELEASE_COMMIT: ${{ github.sha }} + RELEASE_RUN: ${{ needs.validate.outputs.release_run }} run: | - flags=() - RELEASE_TAG="v$RELEASE_VERSION" - if [[ "$RELEASE_TAG" == *-* ]]; then flags+=(--prerelease); fi - gh release create "$RELEASE_TAG" --target "$RELEASE_COMMIT" --draft --title "SidePulse.NET $RELEASE_VERSION" --notes-file "docs/releases/$RELEASE_VERSION.md" "${flags[@]}" release-files/* + python3 scripts/prepare_release.py --directory release-files echo "Release draft prepared. Review downloads, notes and acceptance before publishing." >> "$GITHUB_STEP_SUMMARY" diff --git a/README.md b/README.md index e230e45..d649eec 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ an agent is working, waiting for input or finished. The baseline is **C# / .NET 10 LTS**, **Spectre.Console** and **Spectre.Console.Cli**. Windows, macOS and Linux are supported by the preview; see the [platform matrix](docs/wiki/Platforms.md) for native credential requirements -and architecture-specific validation. No release has been published yet. +and architecture-specific validation. Beta 1 and beta 2 have been published; subsequent changes on main remain unreleased. Hardware/firmware, real provider sessions and the public release/update flow still need acceptance evidence. A live dashboard, device aliases, explicit Python @@ -154,7 +154,8 @@ with an installation manifest; older previews need one manual upgrade. Stop the host first and confirm `installed` before restarting it. See [updating and recovery](docs/wiki/Updating.md). Adding the release workflow does not publish a release. A matching version tag or manual Prepare release run on `main` -builds and verifies six archives, then creates an unpublished release draft. +builds and verifies six archives, then creates an unpublished release draft. Published +versions are refused; repeat runs reuse complete drafts or resume their original artifacts. Publishing the reviewed draft is a separate explicit release action. ### Device storage and firmware diff --git a/SidePulse.NET.slnx b/SidePulse.NET.slnx index 3b127e1..dcf4dfd 100644 --- a/SidePulse.NET.slnx +++ b/SidePulse.NET.slnx @@ -5,5 +5,6 @@ + diff --git a/docs/reviews/release-draft-2026-11-30.md b/docs/reviews/release-draft-2026-11-30.md new file mode 100644 index 0000000..330a58d --- /dev/null +++ b/docs/reviews/release-draft-2026-11-30.md @@ -0,0 +1,28 @@ +# Beta 2 draft audit — 2026-11-30 + +Issue #57 records an extra draft for `v0.1.0-beta.2`. + +| Release | ID | State | Target | +|---|---|---|---| +| Beta 1 | 422776643 | Published, preserved | f02d61a9607a4105b5d510d7bff391c0e5177316 | +| Beta 2 | 422825899 | Published, preserved | b5982f259ac2818f3fb39038c6809d1c191969ca | +| Extra Beta 2 | 424050144 | Unpublished, retained | b5982f259ac2818f3fb39038c6809d1c191969ca | + +The extra draft and its seven assets were created by `github-actions[bot]`. Assets +were uploaded on 2026-10-26 at 09:24 UTC. The successful tag-push Prepare release +[run 40298814975](https://github.com/Anheledir/SidePulse.NET/actions/runs/40298814975) +started at 09:20 UTC at the same target commit. The old workflow unconditionally +ran `gh release create --draft` and used a per-ref concurrency key, allowing repeat +or tag/dispatch preparation to produce another draft. + +Both beta.2 records have six archives plus `SHA256SUMS`, but all seven GitHub asset +digests differ. Equal target commits do not establish byte-identical artifacts. +The draft was therefore retained as unpublished evidence. No release, asset or tag +was deleted, replaced, renamed or published during this work. This is a deliberate +retention decision, not a claim that the duplicate was removed. + +The revised workflow refuses this published version even when a same-tag draft +exists. A read-only live preflight against beta.2 confirmed the refusal. Future +preparation uses a shared concurrency group, recorded provenance, immutable asset +checks and original-run artifact resumption. No live release was created to test +those mutation paths; deterministic API-contract tests cover them. diff --git a/docs/wiki/Updating.md b/docs/wiki/Updating.md index 8a38026..7d608cf 100644 --- a/docs/wiki/Updating.md +++ b/docs/wiki/Updating.md @@ -59,8 +59,19 @@ the backup directory manually before the CLI can run again. Unknown user-added files are copied into the new directory unless they collide with a new application-owned file. Existing directory access permissions and access -permissions on user-added files are preserved. Avoid editing the installation -during updating. +permissions on user-added files are preserved. Preparation records content and access +permission fingerprints of the current and staged trees, including empty directories. +Apply checks both again under the update lock before renaming anything. Additions, +equal-size edits, deletions, permission changes or altered staged copies refuse the +swap and preserve the current directory; stop writers and prepare again. Plans from +older versions without fingerprints are refused rather than assumed safe. + +The helper checks again after moving the old directory to its backup and after the +startup probe. Detected changes during that interval trigger rollback. A modified +replacement is retained under `workspace/failed-package`; edits there are not silently +merged into the restored installation. Writers must remain stopped throughout the +transaction: file fingerprints cannot freeze arbitrary external processes or their +already-open handles. Inspect both retained trees after a failure. Phone links, profiles and hooks normally live outside it and are not changed. The complete old installation and temporary download/helper workspace are retained for recovery. Once installation is confirmed and no helper is running, these @@ -68,12 +79,30 @@ paths may be removed manually to reclaim space. Failed updates preserve evidence ## Publishing -The Release workflow runs on `vVERSION` tags or manual dispatch on such a tag. -The tag must match the project version. It reuses all three native CI jobs and -self-contained smoke checks, collects all six archives, writes `SHA256SUMS`, uploads -a draft release and only then publishes it. Hyphenated versions are prereleases. -No release or tag is created simply by adding this workflow to a branch. Existing -release tags are not overwritten. Review the release notes/assets after publishing. +The Prepare release workflow accepts matching `vVERSION` tags or manual dispatch on +`main`. The project version and matching `docs/releases/VERSION.md` are required. +It builds/tests all three native platforms and verifies all six runtime archives. +**Publication stays manual:** preparation creates an unpublished draft; it never +publishes a release or rewrites an existing tag. + +All preparation runs share one non-cancelling concurrency group, including tag and +manual-dispatch runs. Preflight refuses any already-published version before building, +even if an extra draft has the same tag. Use a new project version and matching notes. +An existing draft must match its commit, notes, prerelease flag and recorded asset +inventory. Complete drafts are reused without rebuilding or replacing anything. +Partial drafts resume only missing uploads from their original workflow artifacts; +accepted uploads are reconciled by SHA-256/size instead of replayed or overwritten. +If those artifacts expired, preserve/review the draft and choose a new version rather +than mixing rebuilt binaries into it. Conflicting metadata/assets or multiple drafts +are refused. Do not publish manually while a preparation workflow is still running; +GitHub does not offer an atomic draft-state condition on an asset upload. + +The hidden release-plan comment records the originating run, commit and seven asset +digests. Do not edit it during preparation. Legacy drafts without that provenance +require explicit review. The existing extra beta.2 draft was inspected and retained +because its archive hashes differ from the published beta.2; see +[the audit](../reviews/release-draft-2026-11-30.md). Neither public beta nor its assets +or tags were changed. `update status --json` always exposes the same lower-camel-case fields: `state`, `version`, `target`, `backup`, `workspace`, `error`, and `receipt`. Missing values diff --git a/scripts/prepare_release.py b/scripts/prepare_release.py new file mode 100644 index 0000000..f49f802 --- /dev/null +++ b/scripts/prepare_release.py @@ -0,0 +1,158 @@ +"""Prepare or resume one immutable release draft; never publish or replace assets.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import subprocess +from urllib.parse import quote + +from verify_release import verify + +NAMES = {f'spn-{platform}-{arch}' + ('.zip' if platform == 'win' else '.tar.gz') + for platform in ('win', 'linux', 'osx') for arch in ('x64', 'arm64')} | {'SHA256SUMS'} +MARKER = 'spn-release-plan-v1:' + + +class GitHub: + def __init__(self, repository): + if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', repository): + raise ValueError('Invalid repository name') + self.repository = repository + + def api(self, path, method='GET', payload=None, file=None): + command = ['gh', 'api', path, '--method', method] + data = None + if payload is not None: + command += ['--input', '-'] + data = json.dumps(payload) + if file is not None: + command += ['--input', str(file), '-H', 'Content-Type: application/octet-stream'] + response = subprocess.run(command, input=data, capture_output=True, text=True, check=True) + return json.loads(response.stdout) + + def releases(self): + releases = [] + page = 1 + while True: + batch = self.api(f'repos/{self.repository}/releases?per_page=100&page={page}') + releases.extend(batch) + if len(batch) < 100: + return releases + page += 1 + + def get(self, release_id): + return self.api(f'repos/{self.repository}/releases/{release_id}') + + def create(self, payload): + return self.api(f'repos/{self.repository}/releases', 'POST', payload=payload) + + def upload(self, release_id, path): + return self.api(f'https://uploads.github.com/repos/{self.repository}/releases/{release_id}/assets?name={quote(path.name)}', 'POST', file=path) + + +def metadata(release, version, commit, notes): + if not release.get('draft'): + raise ValueError('Version is already published; choose a new version and matching release notes. No release was modified.') + if (release['tag_name'] != 'v' + version or release['target_commitish'] != commit + or release['name'] != 'SidePulse.NET ' + version or release['prerelease'] != ('-' in version)): + raise ValueError('Existing draft metadata differs. Review it; no release was modified.') + body = release.get('body') or '' + pattern = r'\n\n\n?' + matches = list(re.finditer(pattern, body)) + if len(matches) != 1 or matches[0].end() != len(body) or body[:matches[0].start()] != notes.strip(): + raise ValueError('Existing draft notes or provenance differ. No release was modified.') + plan = json.loads(matches[0][1]) + if (plan.get('commit') != commit or not re.fullmatch(r'[1-9][0-9]*', str(plan.get('run', ''))) + or set(plan.get('files', {})) != NAMES): + raise ValueError('Existing draft provenance is invalid') + for entry in plan['files'].values(): + if not isinstance(entry.get('size'), int) or entry['size'] <= 0 or not re.fullmatch(r'sha256:[0-9a-f]{64}', entry.get('digest', '')): + raise ValueError('Invalid draft asset inventory') + seen = set() + for asset in release['assets']: + name = asset['name'] + if name in seen or name not in plan['files'] or any(asset.get(key) != plan['files'][name][key] for key in ('size', 'digest')): + raise ValueError('Existing draft assets differ from the verified inventory. Nothing will be overwritten.') + seen.add(name) + return plan, NAMES - seen + + +def inspect(api, version, commit, notes): + matches = [r for r in api.releases() if r['tag_name'] == 'v' + version] + if any(not r['draft'] for r in matches): + raise ValueError('Version is already published; choose a new version and matching release notes. No release was modified.') + if len(matches) > 1: + raise ValueError('Multiple drafts exist for this version. Resolve the ambiguity before preparing another release.') + if not matches: + return None, None, NAMES + release = api.get(matches[0]['id']) + plan, missing = metadata(release, version, commit, notes) + return release, plan, missing + + +def preflight(api, version, commit, notes, run): + release, plan, missing = inspect(api, version, commit, notes) + return {'mode': 'new' if release is None else 'resume' if missing else 'complete', + 'release_run': str(plan['run'] if plan else run)} + + +def prepare(api, root, version, commit, notes, run): + # Refuse a published version before touching local artifacts or remote state. + release, plan, missing = inspect(api, version, commit, notes) + if release is not None and not missing: + return release['id'] + verify(root, version) + inventory = {name: {'size': (root / name).stat().st_size, + 'digest': 'sha256:' + hashlib.sha256((root / name).read_bytes()).hexdigest()} + for name in sorted(NAMES)} + if plan is not None and inventory != plan['files']: + raise ValueError('Resume requires the original verified build artifacts. Existing assets were preserved.') + if release is None: + plan = {'commit': commit, 'run': str(run), 'files': inventory} + body = notes.strip() + '\n\n\n' + release = api.create({'tag_name': 'v' + version, 'target_commitish': commit, 'draft': True, + 'prerelease': '-' in version, 'name': 'SidePulse.NET ' + version, 'body': body}) + # Check ID, draft state, metadata and digest inventory before each non-overwriting upload. + # Never retry a POST after an ambiguous result; the next run reconciles server state. + for name in sorted(NAMES): + current, current_plan, current_missing = inspect(api, version, commit, notes) + if current is None or current['id'] != release['id'] or current_plan != plan: + raise ValueError('Release changed during preparation. Stop and review it.') + if name in current_missing: + api.upload(release['id'], root / name) + final = api.get(release['id']) + _, missing = metadata(final, version, commit, notes) + if missing: + raise ValueError('Draft is incomplete; rerun preparation to resume its original artifacts') + return release['id'] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--preflight', action='store_true') + parser.add_argument('--directory', type=Path) + args = parser.parse_args() + version, commit, run = (os.environ[name] for name in ('RELEASE_VERSION', 'RELEASE_COMMIT', 'RELEASE_RUN')) + if not re.fullmatch(r'\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?', version): + raise ValueError('Invalid release version') + if not re.fullmatch(r'[0-9a-f]{40}', commit) or not re.fullmatch(r'[1-9][0-9]*', run): + raise ValueError('A full commit SHA and originating workflow run ID are required') + notes = Path('docs/releases', version + '.md').read_text(encoding='utf-8') + api = GitHub(os.environ['GH_REPO']) + if args.preflight: + decision = preflight(api, version, commit, notes, run) + if os.environ.get('GITHUB_OUTPUT'): + with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as output: + for key, value in decision.items(): + output.write(f'{key}={value}\n') + print(json.dumps(decision)) + else: + if args.directory is None: + parser.error('--directory is required to prepare a draft') + print('Unpublished draft verified:', prepare(api, args.directory, version, commit, notes, run)) + + +if __name__ == '__main__': + main() diff --git a/scripts/tests/test_prepare_release.py b/scripts/tests/test_prepare_release.py new file mode 100644 index 0000000..f5e9d24 --- /dev/null +++ b/scripts/tests/test_prepare_release.py @@ -0,0 +1,142 @@ +import copy +import hashlib +import json +from pathlib import Path +import sys +import tempfile +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from prepare_release import NAMES, inspect, preflight, prepare +import test_release + + +class FakeGitHub: + def __init__(self): + self.items = [] + self.created = 0 + self.uploaded = [] + self.interrupt = False + + def releases(self): + return copy.deepcopy(self.items) + + def get(self, release_id): + return copy.deepcopy(next(r for r in self.items if r['id'] == release_id)) + + def create(self, payload): + self.created += 1 + release = dict(payload, id=self.created, assets=[]) + self.items.append(release) + return copy.deepcopy(release) + + def upload(self, release_id, path): + release = next(r for r in self.items if r['id'] == release_id) + self.uploaded.append(path.name) + data = path.read_bytes() + release['assets'].append({'name': path.name, 'size': len(data), 'digest': 'sha256:' + hashlib.sha256(data).hexdigest()}) + if self.interrupt: + self.interrupt = False + raise OSError('fixture upload accepted but acknowledgement lost') + + +class DraftPreparationTests(unittest.TestCase): + version = '0.1.0-beta.1' + commit = 'a' * 40 + notes = 'Reviewed notes\n' + + def packages(self, root): + test_release.ReleaseTests().packages(root, single_file=True) + + def test_repeated_preparation_reuses_complete_draft_without_new_build_or_upload(self): + api = FakeGitHub() + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self.packages(root) + first = prepare(api, root, self.version, self.commit, self.notes, '100') + self.assertEqual(first, prepare(api, root, self.version, self.commit, self.notes, '200')) + self.assertEqual({'mode': 'complete', 'release_run': '100'}, preflight(api, self.version, self.commit, self.notes, '200')) + self.assertEqual(1, api.created) + self.assertEqual(7, len(api.uploaded)) + self.assertTrue(api.items[0]['draft']) + + def test_interrupted_upload_reconciles_original_artifacts_without_replaying_accepted_asset(self): + api = FakeGitHub() + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self.packages(root) + api.interrupt = True + with self.assertRaises(OSError): + prepare(api, root, self.version, self.commit, self.notes, '100') + self.assertEqual({'mode': 'resume', 'release_run': '100'}, preflight(api, self.version, self.commit, self.notes, '200')) + prepare(api, root, self.version, self.commit, self.notes, '100') + self.assertEqual(1, api.created) + self.assertEqual(len(NAMES), len(set(api.uploaded))) + self.assertEqual(len(NAMES), len(api.uploaded)) + + def test_published_version_wins_even_when_duplicate_draft_exists(self): + api = FakeGitHub() + api.items = [{'id': 42, 'tag_name': 'v' + self.version, 'draft': False}, {'id': 43, 'tag_name': 'v' + self.version, 'draft': True}] + before = copy.deepcopy(api.items) + with self.assertRaisesRegex(ValueError, 'already published'): + prepare(api, Path('/does-not-exist'), self.version, self.commit, self.notes, '200') + self.assertEqual(before, api.items) + self.assertEqual(0, api.created) + self.assertEqual([], api.uploaded) + + def test_ambiguous_drafts_are_never_chosen_arbitrarily(self): + api = FakeGitHub() + api.items = [{'id': i, 'tag_name': 'v' + self.version, 'draft': True} for i in (1, 2)] + with self.assertRaisesRegex(ValueError, 'Multiple drafts'): + inspect(api, self.version, self.commit, self.notes) + + def test_changed_notes_or_commit_and_changed_existing_assets_are_preserved(self): + api = FakeGitHub() + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self.packages(root) + prepare(api, root, self.version, self.commit, self.notes, '100') + for commit, notes in [(self.commit, 'different notes'), ('b' * 40, self.notes)]: + with self.assertRaises(ValueError): + prepare(api, root, self.version, commit, notes, '200') + api.items[0]['assets'][0]['digest'] = 'sha256:' + '0' * 64 + with self.assertRaisesRegex(ValueError, 'assets differ'): + prepare(api, root, self.version, self.commit, self.notes, '200') + self.assertEqual(7, len(api.uploaded)) + + def test_rebuilt_artifacts_cannot_fill_an_older_partial_draft(self): + api = FakeGitHub() + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self.packages(root) + api.interrupt = True + with self.assertRaises(OSError): + prepare(api, root, self.version, self.commit, self.notes, '100') + with patch('prepare_release.verify'): + (root / 'spn-win-x64.zip').write_bytes(b'different rebuild') + with self.assertRaisesRegex(ValueError, 'original verified build'): + prepare(api, root, self.version, self.commit, self.notes, '200') + self.assertEqual(1, len(api.uploaded)) + + def test_publishing_during_preparation_stops_before_any_next_upload(self): + api = FakeGitHub() + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + self.packages(root) + original_create = api.create + def publish(payload): + result = original_create(payload) + api.items[0]['draft'] = False + return result + api.create = publish + with self.assertRaisesRegex(ValueError, 'already published'): + prepare(api, root, self.version, self.commit, self.notes, '100') + self.assertEqual([], api.uploaded) + + def test_tag_and_dispatch_share_one_non_cancelling_serialization_group(self): + workflow = (Path(__file__).resolve().parents[2] / '.github/workflows/release.yml').read_text() + self.assertIn('group: release-preparation\n cancel-in-progress: false', workflow) + self.assertNotIn('group: release-${{ github.ref }}', workflow) + self.assertIn("needs.validate.outputs.mode == 'new'", workflow) + self.assertIn('RELEASE_RUN: ${{ needs.validate.outputs.release_run }}', workflow) diff --git a/scripts/update_smoke.py b/scripts/update_smoke.py index af867c1..dff7437 100644 --- a/scripts/update_smoke.py +++ b/scripts/update_smoke.py @@ -1,5 +1,4 @@ """Run the actual updater helper against isolated self-contained installs.""" -import hashlib import json import os from pathlib import Path @@ -13,43 +12,54 @@ def main(executable): executable = Path(executable).resolve() source = executable.parent shipped = json.loads((source / 'sidepulse-install.json').read_text(encoding='utf-8')) + fixture = Path(__file__).resolve().parents[1] / 'tests/SidePulse.UpdateFixture/SidePulse.UpdateFixture.csproj' + subprocess.run(['dotnet', 'build', str(fixture), '-c', 'Release', '--nologo'], check=True) with tempfile.TemporaryDirectory(prefix='SidePulse updater ü ') as temporary: root = Path(temporary).resolve() env = dict(os.environ, SIDEPULSE_NET_HOME=str(root / 'state')) - for fail in (False, True): - home = root / ('rollback' if fail else 'success') + for scenario in ('success', 'rollback', 'changed-user-files'): + fail = scenario == 'rollback' + changed = scenario == 'changed-user-files' + expected_failure = fail or changed + home = root / scenario target = home / 'installation' job = home / '.sidepulse-update-smoke' stage = job / 'stage' - backup = home / 'installation.backup-smoke' helper = job / 'helper' # A deliberately incorrect expected version exercises real startup rollback. - for destination in (target, stage, helper): + for destination in (target, stage): shutil.copytree(source, destination) + (target / 'personal.txt').write_text('before', encoding='utf-8') expected = '99.0.0' if fail else shipped['Version'] if fail: (stage / 'sidepulse-install.json').write_text(json.dumps(dict(shipped, Version=expected)), encoding='utf-8') initial = subprocess.run([str(target / executable.name), 'update', 'status', '--json'], env=env, capture_output=True, text=True, timeout=15) assert initial.returncode == 0, (initial.stdout, initial.stderr) receipt = Path(json.loads(initial.stdout)['receipt']) - plan = dict(Target=str(target), Stage=str(stage), Backup=str(backup), Job=str(job), Receipt=str(receipt), - ExpectedManifestHash=hashlib.sha256((target / 'sidepulse-install.json').read_bytes()).hexdigest().upper(), - Version=expected, Runtime=shipped['Runtime'], ParentId=2147483647, ParentStartTicks=0) + subprocess.run(['dotnet', 'run', '--no-build', '-c', 'Release', '--project', str(fixture), '--', + str(target), str(stage), str(job), expected, shipped['Runtime']], env=env, check=True, timeout=45) plan_path = job / 'plan.json' - plan_path.write_text(json.dumps(plan), encoding='utf-8') + plan = json.loads(plan_path.read_text(encoding='utf-8')) + backup = Path(plan['Backup']) + if changed: + (target / 'personal.txt').write_text('edited after preparation', encoding='utf-8') result = subprocess.run([str(helper / executable.name), 'internal-update', '--plan', str(plan_path)], env=env, capture_output=True, text=True, timeout=75, cwd=job) - assert result.returncode == (1 if fail else 0), (result.returncode, result.stdout, result.stderr, receipt.read_text(encoding='utf-8') if receipt.exists() else 'no receipt') + assert result.returncode == (1 if expected_failure else 0), (result.returncode, result.stdout, result.stderr, receipt.read_text(encoding='utf-8') if receipt.exists() else 'no receipt') state = json.loads(receipt.read_text(encoding='utf-8')) - assert state['State'] == ('failed' if fail else 'installed'), state + assert state['State'] == ('failed' if expected_failure else 'installed'), state current = json.loads((target / 'sidepulse-install.json').read_text(encoding='utf-8')) assert current['Version'] == shipped['Version'] version = subprocess.run([str(target / executable.name), '--version'], env=env, capture_output=True, text=True, timeout=15) assert version.returncode == 0 and version.stdout.strip() == shipped['Version'] status = subprocess.run([str(target / executable.name), 'update', 'status', '--json'], env=env, capture_output=True, text=True, timeout=15) - assert status.returncode == (1 if fail else 0) and json.loads(status.stdout)['state'] == state['State'] - assert (job / 'failed-package').exists() if fail else backup.exists() - print('Native updater ' + ('startup failure rollback' if fail else 'replacement and backup') + ' passed.', flush=True) + assert status.returncode == (1 if expected_failure else 0) and json.loads(status.stdout)['state'] == state['State'] + assert (target / 'personal.txt').read_text(encoding='utf-8') == ('edited after preparation' if changed else 'before') + if changed: + assert not backup.exists(), 'Conflict should refuse before exchanging directories' + else: + assert (job / 'failed-package').exists() if fail else backup.exists() + print('Native updater ' + ('post-prepare user-file refusal' if changed else 'startup failure rollback' if fail else 'replacement and backup') + ' passed.', flush=True) if __name__ == '__main__': diff --git a/src/SidePulse.Core/UpdateTransaction.cs b/src/SidePulse.Core/UpdateTransaction.cs index 2e7b368..2e2086a 100644 --- a/src/SidePulse.Core/UpdateTransaction.cs +++ b/src/SidePulse.Core/UpdateTransaction.cs @@ -4,7 +4,7 @@ namespace SidePulse.Core; -public sealed record UpdatePlan(string Target, string Stage, string Backup, string Job, string Receipt, string ExpectedManifestHash, string Version, string Runtime, int ParentId, long ParentStartTicks); +public sealed record UpdatePlan(string Target, string Stage, string Backup, string Job, string Receipt, string ExpectedManifestHash, string Version, string Runtime, int ParentId, long ParentStartTicks, string? ExpectedTargetTreeHash = null, string? ExpectedStageTreeHash = null); public sealed record UpdateReceipt(string State, string Version, string Target, string Backup, string Job, string? Error = null); public static class UpdateTransaction { @@ -38,6 +38,7 @@ public static UpdatePlan Prepare(string target, string stage, string job, string var current = InstallationManifest.Read(target); if (current.Runtime != runtime) throw new IOException("Current installation runtime does not match this process."); current.Verify(target, false); + var originalTreeHash = Snapshot(target); var next = InstallationManifest.Read(stage); if (next.Version != version || next.Runtime != runtime) throw new IOException("Staged installation does not match the release."); next.Verify(stage, true); @@ -57,6 +58,8 @@ public static UpdatePlan Prepare(string target, string stage, string job, string else File.SetUnixFileMode(destination, File.GetUnixFileMode(path)); } PreserveDirectoryAccess(target, stage); + if (Snapshot(target) != originalTreeHash) throw new IOException("Installation files changed during preparation. Prepare the update again after stopping other writers."); + plan = plan with { ExpectedTargetTreeHash = originalTreeHash, ExpectedStageTreeHash = Snapshot(stage) }; var helper = Path.Combine(job, "helper"); Directory.CreateDirectory(helper); foreach (var file in current.Files) @@ -72,6 +75,41 @@ public static UpdatePlan Prepare(string target, string stage, string job, string Receipt(plan, "prepared"); return plan; } + // Include unowned files, empty directories and access permissions. Content hashes + // are independent of timestamps, so equal-size edits and restored timestamps count. + private static string Snapshot(string root) + { + using var bytes = new MemoryStream(); + using var writer = new BinaryWriter(bytes, Encoding.UTF8, true); + void Visit(string path) + { + var attributes = File.GetAttributes(path); + if ((attributes & FileAttributes.ReparsePoint) != 0) throw new IOException("Symbolic links are not supported in an updated installation."); + var directory = (attributes & FileAttributes.Directory) != 0; + writer.Write(Path.GetRelativePath(root, path).Replace('\\', '/')); + writer.Write(directory); + writer.Write((attributes & FileAttributes.ReadOnly) != 0); + if (OperatingSystem.IsWindows()) + { + System.Security.AccessControl.FileSystemSecurity access = directory + ? FileSystemAclExtensions.GetAccessControl(new DirectoryInfo(path), System.Security.AccessControl.AccessControlSections.Access) + : FileSystemAclExtensions.GetAccessControl(new FileInfo(path), System.Security.AccessControl.AccessControlSections.Access); + writer.Write(access.GetSecurityDescriptorSddlForm(System.Security.AccessControl.AccessControlSections.Access)); + } + else writer.Write((int)File.GetUnixFileMode(path)); + if (directory) + foreach (var child in Directory.EnumerateFileSystemEntries(path).Order(StringComparer.Ordinal)) Visit(child); + else writer.Write(InstallationManifest.Hash(path)); + } + Visit(root); + writer.Flush(); + return Convert.ToHexString(SHA256.HashData(bytes.ToArray())); + } + private static void VerifySnapshot(string root, string? expected) + { + if (expected is null || Snapshot(root) != expected) + throw new IOException("Installation or staged user files changed since preparation, or the plan predates file snapshots. No stale user files will be installed; prepare the update again."); + } private static void PreserveDirectoryAccess(string source, string destination) { foreach (var child in Directory.EnumerateDirectories(source)) @@ -104,13 +142,20 @@ public static async Task Apply(UpdatePlan plan, Func(() => fixture.Prepare()); Assert.Equal("personal", File.ReadAllText(System.IO.Path.Combine(fixture.Target, "custom.txt"))); } + [Theory] + [InlineData("edit")] + [InlineData("add")] + [InlineData("delete")] + [InlineData("empty-directory")] + public async Task UserChangesAfterPrepareRefuseTheSwap(string mutation) + { + using var fixture = new Installation(); + var personal = System.IO.Path.Combine(fixture.Target, "personal ü.txt"); + File.WriteAllText(personal, "before"); + var timestamp = File.GetLastWriteTimeUtc(personal); + var plan = fixture.Prepare(); + switch (mutation) + { + case "edit": File.WriteAllText(personal, "edited"); File.SetLastWriteTimeUtc(personal, timestamp); break; + case "add": File.WriteAllText(System.IO.Path.Combine(fixture.Target, "added.txt"), "new data"); break; + case "delete": File.Delete(personal); break; + case "empty-directory": Directory.CreateDirectory(System.IO.Path.Combine(fixture.Target, "new empty folder")); break; + } + var probed = false; + await Assert.ThrowsAsync(() => UpdateTransaction.Apply(plan, (_, _) => { probed = true; return Task.CompletedTask; })); + Assert.False(probed); + Assert.False(Directory.Exists(plan.Backup)); + Assert.Equal("1.0.0", InstallationManifest.Read(fixture.Target).Version); + if (mutation == "edit") Assert.Equal("edited", File.ReadAllText(personal)); + if (mutation == "delete") Assert.False(File.Exists(personal)); + if (mutation == "add") Assert.Equal("new data", File.ReadAllText(System.IO.Path.Combine(fixture.Target, "added.txt"))); + if (mutation == "empty-directory") Assert.True(Directory.Exists(System.IO.Path.Combine(fixture.Target, "new empty folder"))); + } + [Fact] + public async Task ChangedStagedUserCopyCannotReplaceCurrentData() + { + using var fixture = new Installation(); + File.WriteAllText(System.IO.Path.Combine(fixture.Target, "personal.txt"), "current data"); + var plan = fixture.Prepare(); + File.WriteAllText(System.IO.Path.Combine(fixture.Stage, "personal.txt"), "stale or injected"); + await Assert.ThrowsAsync(() => UpdateTransaction.Apply(plan, (_, _) => Task.CompletedTask)); + Assert.Equal("current data", File.ReadAllText(System.IO.Path.Combine(fixture.Target, "personal.txt"))); + Assert.False(Directory.Exists(plan.Backup)); + } + [Fact] + public async Task OldPlansWithoutSnapshotsRefuseRatherThanAssumePreservation() + { + using var fixture = new Installation(); + var plan = fixture.Prepare() with { ExpectedTargetTreeHash = null, ExpectedStageTreeHash = null }; + await Assert.ThrowsAsync(() => UpdateTransaction.Apply(plan, (_, _) => Task.CompletedTask)); + Assert.False(Directory.Exists(plan.Backup)); + } + [Fact] + public async Task MutationsDuringStartupProbeRollbackAndRetainBothTrees() + { + using var fixture = new Installation(); + File.WriteAllText(System.IO.Path.Combine(fixture.Target, "personal.txt"), "before"); + var plan = fixture.Prepare(); + await Assert.ThrowsAsync(() => UpdateTransaction.Apply(plan, (target, _) => + { + File.WriteAllText(System.IO.Path.Combine(plan.Backup, "personal.txt"), "late write to old handle"); + File.WriteAllText(System.IO.Path.Combine(target, "new.txt"), "late write in replacement"); + return Task.CompletedTask; + })); + Assert.Equal("late write to old handle", File.ReadAllText(System.IO.Path.Combine(fixture.Target, "personal.txt"))); + Assert.Equal("late write in replacement", File.ReadAllText(System.IO.Path.Combine(plan.Job, "failed-package", "new.txt"))); + Assert.Equal("failed", UpdateTransaction.Status(fixture.Target)!.State); + } private static object Release(string tag, bool draft = false, bool prerelease = true) => new { tag_name = tag, draft, prerelease, assets = new[] { new { name = "spn-linux-x64.tar.gz", size = 10 }, new { name = "SHA256SUMS", size = 100 } } }; private static HttpResponseMessage Json(string text) => new(HttpStatusCode.OK) { Content = new StringContent(text) }; private sealed class Handler(Func handler) : HttpMessageHandler diff --git a/tests/SidePulse.UpdateFixture/Program.cs b/tests/SidePulse.UpdateFixture/Program.cs new file mode 100644 index 0000000..a6793ee --- /dev/null +++ b/tests/SidePulse.UpdateFixture/Program.cs @@ -0,0 +1,6 @@ +using SidePulse.Core; + +// Native smoke tests use the real preparation API rather than manufacture plans +// or duplicate its platform-specific permission/content fingerprint algorithm. +if (args.Length != 5) throw new ArgumentException("Expected target, stage, job, version and runtime."); +UpdateTransaction.Prepare(args[0], args[1], args[2], args[3], args[4], int.MaxValue, 0); diff --git a/tests/SidePulse.UpdateFixture/SidePulse.UpdateFixture.csproj b/tests/SidePulse.UpdateFixture/SidePulse.UpdateFixture.csproj new file mode 100644 index 0000000..b7f9e97 --- /dev/null +++ b/tests/SidePulse.UpdateFixture/SidePulse.UpdateFixture.csproj @@ -0,0 +1,4 @@ + + Exefalse + + diff --git a/tests/SidePulse.UpdateFixture/packages.lock.json b/tests/SidePulse.UpdateFixture/packages.lock.json new file mode 100644 index 0000000..5da7540 --- /dev/null +++ b/tests/SidePulse.UpdateFixture/packages.lock.json @@ -0,0 +1,19 @@ +{ + "version": 2, + "dependencies": { + "net10.0": { + "sidepulse.core": { + "type": "Project", + "dependencies": { + "System.Security.Cryptography.ProtectedData": "[11.0.0, )" + } + }, + "System.Security.Cryptography.ProtectedData": { + "type": "CentralTransitive", + "requested": "[11.0.0, )", + "resolved": "11.0.0", + "contentHash": "iS9iyAMwLDPFBzTdcREDkzRBYmwy7aENYl7EXxAvnNJNCbl7+UVRgJfWaVLtVjSeDmT3JIItgGODmuAPljXFww==" + } + } + } +} \ No newline at end of file