From b6ea41ba8922d90de13e8ccc6c43479f46d98f35 Mon Sep 17 00:00:00 2001 From: Gleb Pesin Date: Wed, 2 Dec 2026 18:30:14 +0200 Subject: [PATCH 1/4] feat(updates): install signed offline NanoKVM package deltas --- .github/actions/assemble-release/action.yml | 9 + .github/workflows/ci.yml | 5 +- .github/workflows/release.yml | 7 +- docs/RELEASE-NAMING.md | 8 + docs/UPDATES.md | 50 +++- platform/README.md | 1 + scripts/build-offline-repository.sh | 52 ++++ scripts/offline_delta.py | 242 ++++++++++++++++++ scripts/publish-release.py | 3 + scripts/release_assets.py | 7 +- scripts/sign-release.sh | 41 ++- server-cpp/CMakeLists.txt | 3 + server-cpp/src/osupdate/helper.cpp | 7 + server-cpp/src/osupdate/internal.hpp | 2 + server-cpp/src/osupdate/offline.cpp | 241 +++++++++++++++++ server-cpp/src/osupdate/offline_upload.cpp | 182 +++++++++++++ server-cpp/src/osupdate/osupdate.cpp | 54 +++- server-cpp/src/osupdate/osupdate.hpp | 8 + server-cpp/src/osupdate/routes.cpp | 1 + server-cpp/src/osupdate/routes.hpp | 1 + server-cpp/tests/osupdate_test.cpp | 14 + server-cpp/tests/run.sh | 2 +- tests/test-offline-delta.py | 76 ++++++ web/src/api/updates.ts | 9 + web/src/i18n/locales/en.json | 4 + .../desktop/menu/settings/updates/card.tsx | 7 +- .../desktop/menu/settings/updates/index.tsx | 5 +- .../desktop/menu/settings/updates/offline.tsx | 89 +++++++ 28 files changed, 1109 insertions(+), 21 deletions(-) create mode 100644 scripts/build-offline-repository.sh create mode 100644 scripts/offline_delta.py create mode 100644 server-cpp/src/osupdate/offline.cpp create mode 100644 server-cpp/src/osupdate/offline_upload.cpp create mode 100644 tests/test-offline-delta.py create mode 100644 web/src/pages/desktop/menu/settings/updates/offline.tsx diff --git a/.github/actions/assemble-release/action.yml b/.github/actions/assemble-release/action.yml index 83dc907aa..26905dbdb 100644 --- a/.github/actions/assemble-release/action.yml +++ b/.github/actions/assemble-release/action.yml @@ -16,6 +16,9 @@ inputs: image: description: attach the SD image (it is always built, as a check that the packages install) default: 'true' + offline: + description: include the offline update archive in public releases + default: 'true' runs: using: composite steps: @@ -34,6 +37,8 @@ runs: env: OUT: ${{ inputs.out }} KEYS: ${{ inputs.keys }} + BUILD_OFFLINE_UPDATE: ${{ inputs.offline }} + GH_TOKEN: ${{ github.token }} run: | python3 scripts/release_build_tar.py "$RUNNER_TEMP/release-build.tar" "$OUT" # The key options are words: -e FILE, or -d. @@ -45,6 +50,7 @@ runs: env: OUT: ${{ inputs.out }} IMAGE: ${{ inputs.image }} + OFFLINE: ${{ inputs.offline }} run: | a=$OUT/assets rm -rf "$a" @@ -61,6 +67,9 @@ runs: if [ -d "$OUT/release/stock-installer" ]; then cp "$OUT"/release/stock-installer/nanokvm_*.tar.gz "$a/" fi + if [ "$OFFLINE" = true ] && [ ! -f "$OUT/offline-no-baseline" ]; then + cp "$OUT/release/NanoKVM-OS-$NANOKVM_VERSION-offline.tar" "$a/" + fi python3 scripts/release_assets.py "$a" ls -la "$a/public" "$a/packages" cat "$a/public/SHA256SUMS" "$a/packages/SHA256SUMS" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c5b7ac30f..e19c2e43f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,7 +57,7 @@ jobs: echo "rustdesk=$(changed '^addons/rustdesk/')" echo "assembly=$(changed '^firmware/(cpu/go-crypto-c906|crypto/openssl-c906)/|^addons/rustdesk/src/(poly1305|salsa20)_c906[.]S$|^platform/kernel/[0-9]+-crypto-')" echo "openssl=$(changed '^firmware/crypto/openssl-c906/|^platform/sources[.]lock$|^tests/test-openssl-source[.]py$')" - echo "signing=$(changed '^firmware/alpine/(packages/|release[.]env$)|^scripts/(build-alpine-packages|check-ec-key)[.]sh$|^scripts/package-versions[.]py$|^platform/sources[.]lock$|^tests/test-ecdsa-packages[.]py$')" + echo "signing=$(changed '^firmware/alpine/(packages/|release[.]env$)|^scripts/(build-alpine-packages|check-ec-key|build-offline-repository)[.]sh$|^scripts/(package-versions|offline_delta)[.]py$|^platform/sources[.]lock$|^tests/test-(ecdsa-packages|offline-delta)[.]py$')" echo "safe_update=$(changed '^firmware/alpine/safe-update/')" echo "server=$(changed '^server-cpp/|^platform/sources[.]lock$')" } | tee -a "$GITHUB_OUTPUT" @@ -203,7 +203,8 @@ jobs: run: | docker run --rm -v "$PWD:/src:ro" -w /src alpine:3.24 sh -ec ' apk add --no-cache alpine-sdk alpine-keys python3 openssl coreutils > /dev/null - python3 tests/test-ecdsa-packages.py' + python3 tests/test-ecdsa-packages.py + python3 tests/test-offline-delta.py apk' - name: Script tests run: | set -e diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0a0bfee81..ce842a424 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -10,7 +10,7 @@ name: Release # environment, so the signing keys are used only after a maintainer approves # the run. It signs the packages that changed and both indexes, then # stages them as temporary Actions artifacts for Pages. Public OS releases -# contain corresponding source and checksums; SD image releases also include +# contain the offline update, corresponding source and checksums. SD image releases also include # the stock Sipeed migration package. # A patch release is published at once, which publishes its packages (apk-repository.yml); a minor release and a pushed tag # stay drafts for their notes. @@ -59,9 +59,12 @@ on: - scripts/release_assets.py - scripts/release_build_tar.py - scripts/sign-release.sh + - scripts/build-offline-repository.sh + - scripts/offline_delta.py - scripts/apk_resign.py - scripts/check-release-key.sh - scripts/alpine-signer.sh + - tests/test-offline-delta.py - tests/test-apk-resign.py - tests/test-release-build-tar.py - scripts/build-stock-installer.py @@ -332,6 +335,7 @@ jobs: out: ${{ env.OUT }} keys: -e ${{ runner.temp }}/keys/${{ env.EC_KEY_NAME }}.key image: ${{ needs.build.outputs.image }} + offline: ${{ inputs.packages_only != true }} - name: Remove the keys if: always() @@ -410,6 +414,7 @@ jobs: out: ${{ env.OUT }} keys: -d image: ${{ needs.build.outputs.image }} + offline: ${{ inputs.packages_only != true }} - uses: actions/upload-artifact@v7 with: diff --git a/docs/RELEASE-NAMING.md b/docs/RELEASE-NAMING.md index 787272d99..55db54a7f 100644 --- a/docs/RELEASE-NAMING.md +++ b/docs/RELEASE-NAMING.md @@ -19,6 +19,14 @@ full tag so you can keep several release manifests in one directory. GitHub releases also include an identical `SHA256SUMS` for older stock installers. Older releases may only provide `SHA256SUMS`. +Public releases with offline-update support include `NanoKVM-OS--offline.tar`. +It carries changed NanoKVM components and the dependencies APK must install or +upgrade from the preceding compatible public release. Its signed `base-version` +names the required `nanokvm-release` APK version. The signed `installed-db` +records the resulting package state for the next offline update. The first +public release on a major has no delta. +Pages-only OTA publications omit this download. + Releases that include an SD image also include the [stock migration package](STOCK-INSTALL.md). Its numeric `nanokvm_X.Y.Z.tar.gz` filename is required by the Sipeed offline updater; do not rename it. The diff --git a/docs/UPDATES.md b/docs/UPDATES.md index c5a6e717c..69e9a84f5 100644 --- a/docs/UPDATES.md +++ b/docs/UPDATES.md @@ -38,6 +38,54 @@ Completed component transactions refresh affected services through separate apply command is required. `nanokvm-bootloader` also updates the bootloader on the SD card. It verifies the written file and keeps `/boot/fip.prev` for recovery; see [bootloader updates](BOOT.md#updating-fipbin). +## Updating a 5.x device without internet access + +1. On a connected computer, download `NanoKVM-OS--offline.tar` from the + target OS release. Each archive updates one specific base version on the + selected Stable or Beta channel. The signed `base-version` file inside + the archive names the required version of the installed `nanokvm-release` + package. Apply successive deltas in order if you are several releases behind. +2. Open **Settings → System → Updates → Install update from file** on the + NanoKVM. Choose the intact tar file and confirm its name. The upload + progress is followed by the usual package installation log. +3. Reboot if the update page requests it. + +The archive targets new or changed NanoKVM OS components and bundled modules. +It includes an Alpine package only when the base installation needs it to meet +the dependencies of those components or their libraries. APK reuses installed +libraries that already meet the requirements. Before installation the updater +verifies the archive signature, base version, target channel and APK transaction. It reports missing dependencies or conflicting local packages in +the update log. Allow space on the system partition for the upload, unpacking +and installation. Package-only hotfixes on Pages have no GitHub release archive. + +### First offline upgrade from a 5.x version without the file picker + +NanoKVM OS 5.0.1 predates the file picker. The first upgrade on an isolated +device can use the same archive as a local APK repository. On a trusted +computer, verify the archive against the SHA-256 published with the release, +extract it into an empty directory, and copy the directory to private system +storage on the NanoKVM (for example `/root/offline-update`). Use a newer +5.x release matching the selected channel. In an SSH session on the NanoKVM, +check that the archive starts at the installed release, then preview the transaction: + +```sh +cd /root/offline-update || exit 1 +base=$(cat base-version) || exit 1 +installed=$(apk --no-network --repositories-file=/dev/null query --from=installed --fields=version --format=default nanokvm-release) +[ "$installed" = "Version: $base" ] || { echo "This archive requires nanokvm-release $base"; exit 1; } +# Use the already installed NanoKVM packages as the upgrade targets. +set -- $(apk --no-network --repositories-file=/dev/null query --from=installed --fields=name --format=default 'nanokvm' 'nanokvm-*' | sed -n 's/^Name: //p') +[ "$#" -gt 0 ] || exit 1 +repo=$PWD/Packages.adb +apk --no-network --no-cache --repositories-file=/dev/null --repository="$repo" upgrade --no-self-upgrade --simulate "$@" +``` + +Check that the plan upgrades `nanokvm-release` to the expected version +and preserves the packages you want to keep. Once satisfied, run the same +command without `--simulate`. The installed trust keys are used, and the +device's repository configuration stays in place. After a successful +upgrade you can delete the copied directory and reboot if requested. + ## Update notices and component versions **Settings → System → Updates** lists the installed NanoKVM OS packages, the @@ -166,7 +214,7 @@ removed. ## Package publication and retention -New GitHub Releases contain OS releases only: corresponding source, checksums, +Public 5.x releases with offline-update support include the signed offline bundle, corresponding source, checksums, and, when built, the SD image and stock migration archive. APKs, indexes and the downloads of packages released on their own live on GitHub Pages. Their version tags reserve package revisions without creating GitHub Releases. The diff --git a/platform/README.md b/platform/README.md index 1db3b3912..076c9afb2 100644 --- a/platform/README.md +++ b/platform/README.md @@ -30,6 +30,7 @@ Every upstream input is pinned in `sources.lock` and checked when it is download | `release/apk/` | the signed APK repository of the OS packages: `recipes/riscv64/` with the packages, `APKINDEX.tar.gz` and `Packages.adb`, and the public keys | | `release/alpine-rootfs.tar.gz`, `release/installed-packages.txt`, `release/installed-licenses.txt` | the root file system, its package versions and their declared licenses | | `release/image/NanoKVM-OS-.img.zip`, `SHA256SUMS` | the SD card image | +| `release/NanoKVM-OS--offline.tar` | a signed offline delta from the preceding public OS version | | `release/stock-installer/nanokvm_X.Y.Z.tar.gz`, `SHA256SUMS` | stock Sipeed migration package (`stock-installer` step; included with SD image releases) | ## Release and installation versions diff --git a/scripts/build-offline-repository.sh b/scripts/build-offline-repository.sh new file mode 100644 index 000000000..2d06395be --- /dev/null +++ b/scripts/build-offline-repository.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# Plan against the public base's installed packages. No APK payload, maintainer +# script or transaction hook ever runs in the signer. +set -eu +export LC_ALL=C +root=/work/offline-root +apk_target() { + apk --arch riscv64 --root "$root" --keys-dir /work/offline-keys \ + --repositories-file /work/offline-repositories "$@" +} +if [ "$1" = plan ]; then + mkdir -p /work/offline /work/fetched /work/offline-keys "$root/lib/apk/db" "$root/etc/apk" "$root/var/cache/apk" + cp /usr/share/apk/keys/riscv64/*.pub /work/published/*.pub /work/release/*.pub /work/offline-keys/ + cp /work/delta/world "$root/etc/apk/world" + cp /work/delta/installed "$root/lib/apk/db/installed" + printf '%s\n' /work/repo/Packages.adb "$(cat /work/addons.list)" \ + https://dl-cdn.alpinelinux.org/alpine/v3.24/main \ + https://dl-cdn.alpinelinux.org/alpine/v3.24/community > /work/offline-repositories + apk_target update + # No global upgrade: already installed providers are eligible, including + # those no longer present in Alpine's rolling stable package indexes. + set -f + # shellcheck disable=SC2046 + apk_target add --simulate $(cat /work/delta/roots) > /work/delta/plan + exit +fi + +# Only solver-selected coordinates reach the repository. Fetch uses the +# authenticated source indexes, including the index-only-signed add-ons. +cd /work/offline +while IFS='=' read -r name revision; do + file=$name-$revision.apk + if [ -f "/work/repo/$file" ]; then + cp "/work/repo/$file" . + else + apk_target fetch --all-matches --output /work/fetched "$name" + mv "/work/fetched/$file" . + fi +done < /work/delta/fetch +apk --sign-key /work/keys/release.key --allow-untrusted mkndx \ + --description "NanoKVM OS $2 offline" --output Packages.adb ./*.apk +apk --keys-dir /work/release verify Packages.adb +apk --keys-dir /work/release adbdump --format=json Packages.adb > /work/delta/selected.json +# Exercise the device transaction using its installed NanoKVM targets and only the staged files. +set -f +# shellcheck disable=SC2046 +set -- $(awk -F: '$1 == "P" && ($2 == "nanokvm" || $2 ~ /^nanokvm-/) {print $2}' /work/delta/installed) +[ "$#" -gt 0 ] || exit 1 +apk --root "$root" --arch riscv64 --keys-dir /work/release --no-network --no-cache \ + --repositories-file=/dev/null --repository=/work/offline/Packages.adb \ + upgrade --no-self-upgrade --simulate "$@" > /work/delta/offline-plan +cp /work/delta/base-version . diff --git a/scripts/offline_delta.py b/scripts/offline_delta.py new file mode 100644 index 000000000..8cef0e330 --- /dev/null +++ b/scripts/offline_delta.py @@ -0,0 +1,242 @@ +#!/usr/bin/env python3 +"""Pick the previous public release available on this channel and diff its APK inventory.""" +import argparse +import base64 +import hashlib +import io +import json +from pathlib import Path +import re +import subprocess +import tarfile +import tempfile + +from pages_store import a, inventory +from release_assets import OS_TAG + +RECORD = re.compile(r'([a-z0-9][a-z0-9+_.-]*)=([0-9][A-Za-z0-9+_.~-]*)') +MAX_BUNDLE = 256 * 1024 * 1024 +MAX_STATE = 256 * 1024 +KEYS = Path(__file__).resolve().parents[1] / 'firmware/alpine/keys' + + +def packages(data, tag): + if len(data) > 256 * 1024: + raise ValueError('Oversized package inventory') + result = {} + for line in data.decode('ascii').splitlines(): + match = RECORD.fullmatch(line) + if not match or match[1] in result: + raise ValueError(f'Invalid installed package record: {line!r}') + result[match[1]] = match[2] + expected = tag[1:].replace('-beta', '_beta').replace('_beta.', '_beta') + if not re.fullmatch(re.escape(expected) + r'-r[0-9]+', result.get('nanokvm-release', '')): + raise ValueError(f'Installed nanokvm-release differs from {tag}') + return result + + +def previous_public(releases, target): + match = OS_TAG.fullmatch(target) + if not match: + raise ValueError(f'Invalid target tag: {target!r}') + candidates = (r for r in releases + if not r['draft'] and r.get('published_at') + and (m := OS_TAG.fullmatch(r['tag_name'])) and m[1] == match[1] + and (match[4] or not a.is_beta(r)) + and a.order(r) < a.order({'tag_name': target})) + return max(candidates, key=a.order, default=None) + + +def signed_state(release, filename, work): + asset = next(x for x in release['assets'] if x['name'] == filename) + if not 0 < asset['size'] <= MAX_BUNDLE: + raise ValueError('Invalid published offline bundle size') + sums = a.checksums(a.asset(release, 'SHA256SUMS').decode()) + data = a.checked(release, filename, sums, size=asset['size']) + with tarfile.open(fileobj=io.BytesIO(data), mode='r:') as archive: + files = {} + for item in archive: + if item.name not in ('SHA256SUMS', 'SHA256SUMS.sig', 'installed-db'): + continue + if item.name in files or not item.isreg() or not 0 < item.size <= MAX_STATE: + raise ValueError(f'Invalid prior bundle metadata: {item.name!r}') + files[item.name] = archive.extractfile(item).read() + for name in ('SHA256SUMS', 'SHA256SUMS.sig'): + (work / name).write_bytes(files[name]) + if not any(subprocess.run(['openssl', 'dgst', '-sha256', '-verify', key, '-signature', + work/'SHA256SUMS.sig', work/'SHA256SUMS'], capture_output=True).returncode == 0 + for key in KEYS.glob('*-ec-*.pub')): + raise ValueError('Prior bundle manifest is not signed by a release key') + data = files['installed-db'] + if a.checksums(files['SHA256SUMS'].decode()).get('installed-db') != hashlib.sha256(data).hexdigest(): + raise ValueError('Prior inventory differs from its signed manifest') + return data + + +# Package and solver fields only. File records, scripts and paths from the +# installed database must never become inputs to the signing job. +FIELDS = frozenset('CPVADpikrqSIsf') + + +def compact_db(data): + result = {} + for paragraph in data.decode('ascii', errors='surrogateescape').strip().split('\n\n'): + fields = {} + for line in paragraph.splitlines(): + if len(line) > 2 and line[1] == ':' and line[0] in FIELDS: + if line[0] in fields: + raise ValueError('Repeated package field') + fields[line[0]] = line[2:] + if not RECORD.fullmatch(fields['P'] + '=' + fields['V']) or fields['P'] in result: + raise ValueError('Invalid package identity in the installed database') + result[fields['P']] = fields + return result + + +def db_text(records): + return ''.join(''.join(f'{k}:{v}\n' for k, v in fields.items()) + '\n' + for _, fields in sorted(records.items())) + + +def encode_state(world, records): + data = (world.strip() + '\n\n' + db_text(records)).encode('ascii') + if len(data) > MAX_STATE: + raise ValueError('Oversized package solver state') + return data + + +def bootstrap(release): + # The migration archive contains the exact installed riscv64 database and + # world of the shipped image, including virtual providers from old Alpine + # versions no longer offered by the current repositories. + version = release['tag_name'][1:].split('-')[0] + filename = f'nanokvm_{version}.tar.gz' + asset = next((item for item in release['assets'] if item['name'] == filename), None) + if not asset or not 0 < asset['size'] <= MAX_BUNDLE: + raise ValueError(f'{release["tag_name"]} has no usable migration archive for the initial offline base') + sums = a.checksums(a.asset(release, 'SHA256SUMS').decode()) + raw = a.checked(release, filename, sums, size=asset['size']) + with tarfile.open(fileobj=io.BytesIO(raw), mode='r|gz') as outer: + for item in outer: + if item.name != f'nanokvm_{version}/migration/alpine-rootfs.tar.gz': + continue + if not item.isreg() or not 0 < item.size <= MAX_BUNDLE: + raise ValueError('Invalid migration root filesystem') + files = {} + with tarfile.open(fileobj=outer.extractfile(item), mode='r|gz') as root: + for member in root: + path = member.name.removeprefix('./') + if path in ('etc/apk/world', 'lib/apk/db/installed'): + if path in files or not member.isreg() or not 0 < member.size <= 4 * 1024 * 1024: + raise ValueError(f'Invalid migration package metadata: {path}') + files[path] = root.extractfile(member).read() + return encode_state(files['etc/apk/world'].decode('ascii'), compact_db(files['lib/apk/db/installed'])) + raise ValueError('Migration archive lacks the root filesystem') + + +def roots_for(base, target): + return sorted(f'{name}={version}' for name, version in target.items() + if (name == 'nanokvm' or name.startswith('nanokvm-')) + and base.get(name, {}).get('V') != version) + + +def prepare(target, installed, output): + previous = previous_public(inventory(), target) + if previous is None or OS_TAG.fullmatch(target)[1] != '5': + print(f'{target}: no compatible public baseline; skipping offline delta') + return + tag = previous['tag_name'] + filename = f'NanoKVM-OS-{tag}-offline.tar' + with tempfile.TemporaryDirectory() as temp: + if any(x['name'] == filename for x in previous['assets']): + state = signed_state(previous, filename, Path(temp)) + else: + state = bootstrap(previous) + world, body = state.split(b'\n\n', 1) + if len(state) > MAX_STATE or any(v.startswith(b'-') for v in world.splitlines()): + raise ValueError('Invalid offline baseline') + records = compact_db(body) + base = packages(''.join(f'{p}={r["V"]}\n' for p, r in records.items()).encode(), tag) + target_packages = packages(installed.read_bytes(), target) + roots = roots_for(records, target_packages) + if not any(x.startswith('nanokvm-release=') for x in roots): + raise ValueError('Missing target release package in delta') + output.mkdir() + (output / 'world').write_bytes(world + b'\n') + (output / 'installed').write_text(db_text(records)) + (output / 'base-version').write_text(base['nanokvm-release'] + '\n') + (output / 'roots').write_text('\n'.join(roots) + '\n') + print(f'{tag} -> {target}: {len(roots)} changed NanoKVM packages') + + +ACTION = re.compile(r'^\(\s*\d+/\s*\d+\) (Installing|Upgrading) ([^ ]+) \(([^()]*)\)$') + + +def plan_changes(plan): + changes = {} + for line in plan.read_text().splitlines(): + if not line.startswith('('): + continue + match = ACTION.fullmatch(line) + if not match: + raise ValueError(f'Unsupported APK transaction: {line}') + _, name, versions = match.groups() + version = versions.split(' -> ')[-1] + if not RECORD.fullmatch(name + '=' + version) or name in changes: + raise ValueError(f'Invalid APK transaction: {line}') + changes[name] = version + return changes + + +def index_record(package): + # APK's text installed database encodes a v3 SHA256 identity as its first + # 160 bits plus the S flag. v2 packages use the original SHA1 identity. + digest = bytes.fromhex(package['hashes']) + if len(digest) not in (20, 32): + raise ValueError('Unsupported package identity') + record = {'C': 'Q1' + base64.b64encode(digest[:20]).decode(), + 'P': package['name'], 'V': package['version'], 'A': package['arch']} + for key, field in [('installed-size', 'I'), ('file-size', 'S'), ('depends', 'D'), + ('provides', 'p'), ('install-if', 'i'), ('provider-priority', 'k')]: + value = package.get(key) + if value is not None: + record[field] = ' '.join(value) if isinstance(value, list) else str(value) + if len(digest) == 32: + record['f'] = 'S' + return record + + +def finish(directory): + baseline = compact_db((directory/'installed').read_bytes()) + changes = plan_changes(directory/'plan') + index = [index_record(p) for p in json.loads((directory/'selected.json').read_text())['packages']] + if changes != plan_changes(directory / 'offline-plan'): + raise ValueError('Offline APK upgrade differs from the dependency plan') + if {p['P']: p['V'] for p in index} != changes: + raise ValueError('APK files differ from the planned transaction') + for record in index: + baseline[record['P']] = {k: v for k, v in record.items() if k in FIELDS} + (directory/'installed-db').write_bytes(encode_state((directory/'world').read_text(), baseline)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest='cmd', required=True) + prepare_parser = commands.add_parser('prepare') + prepare_parser.add_argument('target') + prepare_parser.add_argument('installed', type=Path) + prepare_parser.add_argument('output', type=Path) + for command in ('plan', 'finish'): + commands.add_parser(command).add_argument('directory', type=Path) + args = parser.parse_args() + if args.cmd == 'prepare': + prepare(args.target, args.installed, args.output) + elif args.cmd == 'plan': + changed = plan_changes(args.directory/'plan') + coordinates = {f'{p}={v}' for p, v in changed.items()} + roots = set((args.directory / 'roots').read_text().splitlines()) + if not roots <= coordinates: + raise ValueError(f'Changes missing from APK plan: {sorted(roots - coordinates)}') + (args.directory / 'fetch').write_text(''.join(x + '\n' for x in sorted(coordinates))) + else: + finish(args.directory) diff --git a/scripts/publish-release.py b/scripts/publish-release.py index 48b9abdf2..3f92425dd 100644 --- a/scripts/publish-release.py +++ b/scripts/publish-release.py @@ -69,6 +69,9 @@ def validate_public_names(version, names, *, require_versioned=False): required.add(versioned) images = [n for n in names if (versions := image_versions(n)) and versions[1] == version] installer = {'nanokvm_' + version.removeprefix('v').split('-', 1)[0] + '.tar.gz'} & set(names) + offline = {f'NanoKVM-OS-{version}-offline.tar'} + if offline.intersection(names): + required.update(offline) if (len(names) != len(set(names)) or any(Path(n).name != n for n in names) or len(images) > 1 or set(names) != required | set(images) | installer): raise ValueError(f'{version}: original public download set is incomplete or unexpected') diff --git a/scripts/release_assets.py b/scripts/release_assets.py index b1459ca6b..359940f47 100644 --- a/scripts/release_assets.py +++ b/scripts/release_assets.py @@ -10,6 +10,7 @@ 'build-manifest.json', 'installed-packages.txt', 'installed-licenses.txt'} # addons.json is accepted for old builds, not produced by current OS releases. REQUIRED = TECHNICAL - {'build-manifest.json', 'addons.json'} +OFFLINE_BUNDLE = re.compile(r'NanoKVM-OS-(v[0-9A-Za-z.-]+)-offline\.tar') STOCK_INSTALLER = re.compile(r'nanokvm_\d+\.\d+\.\d+\.tar\.gz') @@ -77,7 +78,7 @@ def split(directory): if file.is_symlink() or not file.is_file(): raise ValueError(f'Not a regular release file: {file}') if re.fullmatch(r'NanoKVM-OS-.+-source\.tar\.xz', file.name) or image_versions( - file.name) or STOCK_INSTALLER.fullmatch(file.name): + file.name) or STOCK_INSTALLER.fullmatch(file.name) or OFFLINE_BUNDLE.fullmatch(file.name): public.append(file) elif file.name in TECHNICAL or file.name.endswith('.apk'): packages.append(file) @@ -91,6 +92,10 @@ def split(directory): installers = [f.name for f in public if STOCK_INSTALLER.fullmatch(f.name)] if installers and installers != [installer_name]: raise ValueError('Stock installer version differs from the release source') + for file in public: + offline = OFFLINE_BUNDLE.fullmatch(file.name) + if offline and offline[1] != version: + raise ValueError('Offline bundle version differs from the release source') for name, group in [('public', public), ('packages', packages)]: target = directory / name target.mkdir() diff --git a/scripts/sign-release.sh b/scripts/sign-release.sh index 3d02486a8..f158539bc 100755 --- a/scripts/sign-release.sh +++ b/scripts/sign-release.sh @@ -12,12 +12,17 @@ # Only the first gzip stream, the signature, changes, so their identity # (the control hash) stays; their size does not. # - Both indexes are made anew from the final files and signed. +# - BUILD_OFFLINE_UPDATE=true also signs the incremental offline repository +# for a public release and its SHA-256 manifest. # apk and abuild-sign come from Alpine's x86_64 minirootfs, checked against # platform/sources.lock, and Alpine's signed repository. -d signs with an EC # test key in OUTPUT/keys, as platform/build.sh -d does. set -euo pipefail export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin LC_ALL=C umask 022 +# Only the host-side reader of public release metadata needs the API token. +metadata_token=${GH_TOKEN:-} +unset GH_TOKEN here=$(cd "$(dirname "$0")" && pwd) repo=$(dirname "$here") out= @@ -110,9 +115,43 @@ signer /bin/sh -euc 'cd /work/repo version=$1; shift /sbin/apk --sign-key /work/keys/release.key --allow-untrusted mkndx \ --description "NanoKVM OS $version" --output Packages.adb "$@"' sh "$version" "${core[@]}" -as_root rm -rf "$root/work/keys" signer /sbin/apk --keys-dir /work/release verify /work/repo/APKINDEX.tar.gz /work/repo/Packages.adb +# Public releases ship an offline delta from the preceding public version. +# Packages-only publications keep their existing Pages-only layout. +if [ "${BUILD_OFFLINE_UPDATE:-false}" = true ]; then + GH_TOKEN="$metadata_token" python3 "$here/offline_delta.py" prepare "$version" "$out/release/installed-packages.txt" "$w/delta" +fi +if [ -d "$w/delta" ]; then + as_root cp -r "$w/delta" "$root/work/delta" + as_root install -m 0644 "$repo/firmware/alpine/etc/apk/repositories.d/nanokvm-addons.list" "$root/work/addons.list" + as_root install -m 0755 "$here/build-offline-repository.sh" "$root/work/build-offline-repository.sh" + signer /bin/sh /work/build-offline-repository.sh plan + as_root cat "$root/work/delta/plan" > "$w/delta/plan" + python3 "$here/offline_delta.py" plan "$w/delta" + as_root install -m 0644 "$w/delta/fetch" "$root/work/delta/fetch" + signer /bin/sh /work/build-offline-repository.sh fetch "$version" + as_root cat "$root/work/delta/offline-plan" > "$w/delta/offline-plan" + as_root cat "$root/work/delta/selected.json" > "$w/delta/selected.json" + python3 "$here/offline_delta.py" finish "$w/delta" + as_root install -m 0644 "$w/delta/installed-db" "$root/work/offline/installed-db" + ( + cd "$root/work/offline" + printf '%s\n' Packages.adb base-version installed-db *.apk | sort > "$w/files" + xargs -a "$w/files" sha256sum -- > "$w/SHA256SUMS" + openssl dgst -sha256 -sign "$eckey" -out "$w/SHA256SUMS.sig" "$w/SHA256SUMS" + bundle=$out/release/NanoKVM-OS-$version-offline.tar + tar --format=ustar --mtime=@0 --owner=0 --group=0 --numeric-owner --mode=0644 \ + -cf "$bundle.tmp" --verbatim-files-from -T "$w/files" -C "$w" SHA256SUMS SHA256SUMS.sig + [ "$(stat -c %s "$bundle.tmp")" -le $((256 * 1024 * 1024)) ] || { + echo "Offline update exceeds the 256 MiB upload limit" >&2; exit 1; } + mv "$bundle.tmp" "$bundle" + ) +elif [ "${BUILD_OFFLINE_UPDATE:-false}" = true ]; then + touch "$out/offline-no-baseline" +fi +as_root rm -rf "$root/work/keys" + # Back to OUTPUT, with packages.json for the new files and the release key's # public half in place of the build key's. for file in "${changed[@]}" APKINDEX.tar.gz Packages.adb; do diff --git a/server-cpp/CMakeLists.txt b/server-cpp/CMakeLists.txt index c93928f6e..abea03044 100644 --- a/server-cpp/CMakeLists.txt +++ b/server-cpp/CMakeLists.txt @@ -186,9 +186,11 @@ add_executable(NanoKVM-Server src/osupdate/apkrun.cpp src/osupdate/godecode.cpp src/osupdate/helper.cpp + src/osupdate/offline.cpp src/osupdate/notice.cpp src/osupdate/osupdate.cpp src/osupdate/routes.cpp + src/osupdate/offline_upload.cpp src/extensions/acme.cpp src/extensions/common.cpp src/extensions/netbird.cpp @@ -360,6 +362,7 @@ add_executable(nkos-update src/osupdate/apkrun.cpp src/osupdate/godecode.cpp src/osupdate/helper.cpp + src/osupdate/offline.cpp src/osupdate/notice.cpp src/osupdate/osupdate.cpp src/osupdate/software.cpp diff --git a/server-cpp/src/osupdate/helper.cpp b/server-cpp/src/osupdate/helper.cpp index e3f16acbe..7a2bc82bc 100644 --- a/server-cpp/src/osupdate/helper.cpp +++ b/server-cpp/src/osupdate/helper.cpp @@ -145,6 +145,13 @@ Error run_apk(const std::string &action) std::this_thread::sleep_for(std::chrono::seconds(1)); return finish(run_wait({"/sbin/reboot"})); } + if (action == "offline") { + if (auto e = run_offline(); !e.empty()) return finish(e); + (void)check_updates(false); + ApkStatus s; + s.state = "installed"; + return finish(save_apk_status(s)); + } if (action != "check" && action != "install" && action != "rollback") return finish("invalid package operation"); if (action == "rollback") { auto status = get_channel(); diff --git a/server-cpp/src/osupdate/internal.hpp b/server-cpp/src/osupdate/internal.hpp index 56ce429da..347ed4fe8 100644 --- a/server-cpp/src/osupdate/internal.hpp +++ b/server-cpp/src/osupdate/internal.hpp @@ -22,6 +22,8 @@ inline constexpr auto check_timeout = std::chrono::seconds(130); Error write_repositories(const std::string &data); Error save_notice(const UpdateNotice &n); +Error run_offline(); +Error offline_eligibility(const std::string &installed, const std::string &base_version, const std::string &target, const ChannelStatus &channel); Error save_apk_status_idle(); Error save_apk_status(const ApkStatus &s); Error remove_rollback_recovery(); diff --git a/server-cpp/src/osupdate/offline.cpp b/server-cpp/src/osupdate/offline.cpp new file mode 100644 index 000000000..b231085a9 --- /dev/null +++ b/server-cpp/src/osupdate/offline.cpp @@ -0,0 +1,241 @@ +// An offline release is an uncompressed USTAR of one signed repository and its +// signed inventory. Only flat regular files can be materialized in the private +// staging directory. Authenticate every byte before running the APK solver. +#include "osupdate/internal.hpp" + +#include "osupdate/files.hpp" +#include "osupdate/gostr.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace nkos::osupdate { +namespace { + +namespace fs = std::filesystem; +using Digest = std::unique_ptr; + +bool enough_space(const fs::path &where, std::uintmax_t bytes) +{ + struct statvfs st{}; + return ::statvfs(where.c_str(), &st) == 0 && st.f_bavail * std::uint64_t(st.f_frsize) >= bytes; +} + +bool verify_signature(const fs::path &keys, const std::string &sums, const std::string &signature) +{ + std::error_code ec; + for (fs::directory_iterator it(keys, ec), end; !ec && it != end; it.increment(ec)) { + auto name = it->path().filename().string(); + if (!name.starts_with("nkos-release-ec-") || !name.ends_with(".pub")) continue; + std::unique_ptr file(BIO_new_file(it->path().c_str(), "r"), BIO_free); + if (!file) continue; + std::unique_ptr key(PEM_read_bio_PUBKEY(file.get(), nullptr, nullptr, nullptr), EVP_PKEY_free); + Digest ctx(EVP_MD_CTX_new(), EVP_MD_CTX_free); + if (key && EVP_PKEY_is_a(key.get(), "EC") && ctx && + EVP_DigestVerifyInit(ctx.get(), nullptr, EVP_sha256(), nullptr, key.get()) == 1 && + EVP_DigestVerify(ctx.get(), reinterpret_cast(signature.data()), signature.size(), + reinterpret_cast(sums.data()), sums.size()) == 1) return true; + } + return false; +} + +bool zero(std::string_view data) { return data.find_first_not_of('\0') == data.npos; } + +bool tar_number(std::string_view field, std::uint64_t &out) +{ + auto first = field.find_first_not_of(' '); + if (first == field.npos) return false; + field.remove_prefix(first); + auto n = field.find_first_not_of("01234567"); + if (!n || n == field.npos || field.substr(n).find_first_not_of(std::string_view("\0 ", 2)) != field.npos) return false; + return std::from_chars(field.data(), field.data() + n, out, 8).ec == std::errc{}; +} + +Error extract_repository(const fs::path &bundle, const fs::path &repo, const fs::path &keys, std::string &release) +{ + std::error_code ec; + auto size = fs::file_size(bundle, ec); + if (ec || size == 0 || size % 512 || size > max_offline_bytes) return "invalid offline bundle size"; + if (!enough_space(repo, size + (16ULL << 20))) return "not enough system storage to unpack the offline update"; + std::ifstream in(bundle, std::ios::binary); + std::map hashes; + std::string sums, signature; + std::array buf{}; + std::array header{}; + bool ended = false; + while (in.read(header.data(), header.size())) { + std::string_view h(header.data(), header.size()); + if (zero(h)) { + // POSIX tar ends with two zero blocks; optional record padding must also be zero. + if (!in.read(header.data(), header.size()) || !zero(h)) return "invalid offline archive trailer"; + while (in.read(buf.data(), buf.size()) || in.gcount()) { + if (!zero({buf.data(), static_cast(in.gcount())})) return "unexpected data after offline archive"; + } + ended = in.eof(); + break; + } + std::uint64_t length = 0, check = 0; + unsigned sum = 0; + for (unsigned char c : h) sum += c; + for (unsigned char c : h.substr(148, 8)) sum -= c; + if (h.substr(257, 8) != std::string_view("ustar\0" "00", 8) || h[156] != '0' || + !zero(h.substr(157, 100)) || !zero(h.substr(345, 155)) || !tar_number(h.substr(124, 12), length) || + length == 0 || length > size || !tar_number(h.substr(148, 8), check) || check != sum + 8 * ' ') + return "invalid offline archive header"; + auto name_field = h.substr(0, 100); + auto count = name_field.find('\0'); + if (count != name_field.npos && !zero(name_field.substr(count))) return "invalid offline archive filename"; + std::string name(name_field.substr(0, count)); + bool metadata = name == "SHA256SUMS" || name == "SHA256SUMS.sig"; + if (metadata) { + auto &dest = name == "SHA256SUMS" ? sums : signature; + if (!dest.empty() || length > (name == "SHA256SUMS" ? 1024 * 1024u : 80u)) return "invalid offline signature files"; + dest.resize(length); + if (!in.read(dest.data(), dest.size())) return "truncated offline signature files"; + } else { + if (name == "base-version" && length > 128) return "invalid offline base version"; + if (name == "installed-db" && length > 256 * 1024) return "offline package inventory too large"; + if (name != "Packages.adb" && name != "base-version" && name != "installed-db") { + std::string package, version; + if (!name.ends_with(".apk") || !detail::apk_package_version(name.substr(0, name.size() - 4), package, version) || + !valid_package_name(package)) + return "unexpected offline repository file"; + if (package == "nanokvm-release") { + if (!release.empty()) return "multiple OS releases in the offline bundle"; + release = version; + } + } + if (hashes.size() >= 4096 || hashes.contains(name)) return "invalid offline package inventory"; + Digest digest(EVP_MD_CTX_new(), EVP_MD_CTX_free); + if (!digest || EVP_DigestInit_ex(digest.get(), EVP_sha256(), nullptr) != 1) return "cannot initialize SHA-256"; + std::ofstream out(repo / name, std::ios::binary); + for (auto left = length; left;) { + auto n = std::min(left, buf.size()); + if (!in.read(buf.data(), n) || !out.write(buf.data(), n)) return "cannot unpack offline repository"; + if (EVP_DigestUpdate(digest.get(), buf.data(), n) != 1) return "cannot hash offline package"; + left -= n; + } + out.close(); + unsigned char hash[32]; + if (!out || EVP_DigestFinal_ex(digest.get(), hash, nullptr) != 1) return "cannot finish offline package"; + static constexpr char hex[] = "0123456789abcdef"; + auto &encoded = hashes[name]; + for (auto c : hash) { + encoded.push_back(hex[c >> 4]); + encoded.push_back(hex[c & 15]); + } + } + auto padding = (512 - length % 512) % 512; + if (!in.read(buf.data(), padding) || !zero({buf.data(), static_cast(padding)})) return "invalid offline archive padding"; + } + if (!ended || !hashes.contains("Packages.adb") || !hashes.contains("base-version") || + !hashes.contains("installed-db") || release.empty()) return "incomplete offline release"; + std::string expected; + for (const auto &[name, hash] : hashes) expected += hash + " " + name + "\n"; + if (sums != expected || !verify_signature(keys, sums, signature)) return "offline release checksum or signature verification failed"; + return {}; +} + +Error validate_plan(const std::string &plan, const std::string &from, const std::string &to, std::vector &packages) +{ + bool updates_release = false; + for (const auto &line : gostr::split(plan, "\n")) { + std::string action, name, change; + if (!detail::parse_apk_step(line, action, name, change)) { + if (detail::step_number(gostr::trim_space(line))) return "unrecognized offline package transaction"; + continue; + } + if (action != "Upgrading" && action != "Installing" && action != "Reinstalling" && action != "Updating pinning") + return "offline update would " + action + " " + name + "; inspect installed packages before updating"; + packages.push_back(name); + if (name == "nanokvm-release" && action == "Upgrading" && change == from + " -> " + to) updates_release = true; + } + return updates_release ? Error{} : "installed package selections prevent this offline release from being applied"; +} + +} // namespace + +Error offline_eligibility(const std::string &installed, const std::string &base_version, const std::string &target, const ChannelStatus &channel) +{ + if (!detail::apk_bare_version(base_version)) return "invalid offline base version"; + if (!installed.starts_with("5.") || !target.starts_with("5.")) return "offline updates require an installed 5.x system and a 5.x release"; + if (installed != base_version) return "this offline update requires nanokvm-release " + base_version + "; installed: " + installed; + if (compare_apk_versions(target, installed) <= 0) return "the offline release must be newer than the installed release"; + if (!channel.available || channel.channel != (prerelease(target) ? "beta" : "stable")) return "offline release does not match the selected update channel"; + return {}; +} + +Error run_offline() +{ + struct Cleanup { + ~Cleanup() { std::error_code ec; fs::remove_all(offline_directory, ec); } + } cleanup; + auto repo = fs::path(offline_directory) / "repo"; + if (::mkdir(repo.c_str(), 0700) != 0) return "cannot create the offline package repository"; + std::string target; + if (auto e = extract_repository(offline_bundle, repo, "/etc/apk/keys", target); !e.empty()) return e; + if (::unlink(offline_bundle) != 0) return "cannot release offline upload storage"; + Error e; + auto versions = installed_versions(e); + if (!versions) return e; + auto current = versions->find("nanokvm-release"); + auto base_version = files::read((repo / "base-version").string()); + if (!base_version || !base_version->ends_with('\n')) return "invalid offline base version"; + base_version->pop_back(); + if (auto err = offline_eligibility(current == versions->end() ? "" : current->second, *base_version, target, get_channel()); !err.empty()) + return err; + + apkrun::Cmd cmd; + cmd.path = apk_executable; + cmd.args = {"--no-network", "--no-cache", "--repositories-file=/dev/null", "--repository=" + (repo / "Packages.adb").string(), + "upgrade", "--no-self-upgrade"}; + // Eligibility above requires an installed nanokvm-release, so this never + // degenerates into an unscoped upgrade of all available Alpine packages. + for (const auto &[name, version] : *versions) + if (name == "nanokvm" || name.starts_with("nanokvm-")) cmd.args.push_back(name); + cmd.args.push_back("--simulate"); + cmd.deadline = apkrun::Clock::now() + std::chrono::minutes(30); + auto plan = apkrun::output_split(cmd); + if (!plan.ok) return "offline APK dependency check failed: " + gostr::trim_space(plan.stderr_output); + std::vector packages; + if (auto err = validate_plan(plan.output, current->second, target, packages); !err.empty()) return err; + + // Bound peak storage conservatively: allow all selected new files and 16 MiB for + // package metadata, before relying on space freed by replacing an older file. + auto query = cmd; + query.args.resize(4); // the same private, network-disabled repository + query.args.insert(query.args.end(), {"query", "--from=repositories", "--fields=installed-size", "--format=default"}); + query.args.insert(query.args.end(), packages.begin(), packages.end()); + auto sizes = apkrun::output_split(query); + if (!sizes.ok) return "cannot check offline package storage requirements: " + gostr::trim_space(sizes.stderr_output); + std::uint64_t required = 16ULL << 20; + for (const auto &line : gostr::split(sizes.output, "\n")) { + if (line.empty()) continue; // virtual packages have no installed-size field + constexpr std::string_view prefix = "Installed-Size: "; + std::uint64_t bytes; + if (!line.starts_with(prefix)) return "invalid offline package size"; + auto end = line.data() + line.size(); + auto parsed = std::from_chars(line.data() + prefix.size(), end, bytes); + if (parsed.ec != std::errc{} || parsed.ptr != end || bytes > UINT64_MAX - required) return "invalid offline package size"; + required += bytes; + } + if (!enough_space(offline_directory, required)) return "not enough system storage for the selected offline packages"; + cmd.args.pop_back(); + auto r = apkrun::run(cmd); + if (!r.ok) return "offline APK transaction failed: " + r.error; + versions = installed_versions(e); + if (!versions || (*versions)["nanokvm-release"] != target) return "the offline transaction did not install the selected release"; + return {}; +} + +} // namespace nkos::osupdate diff --git a/server-cpp/src/osupdate/offline_upload.cpp b/server-cpp/src/osupdate/offline_upload.cpp new file mode 100644 index 000000000..fdb975b9c --- /dev/null +++ b/server-cpp/src/osupdate/offline_upload.cpp @@ -0,0 +1,182 @@ +#include "osupdate/routes.hpp" + +#include "auth/session.hpp" +#include "common/loop.hpp" +#include "http/upload.hpp" +#include "osupdate/osupdate.hpp" +#include "osupdate/reply.hpp" + +#include +#include +#include +#include +#include + +namespace nkos::osupdate { +namespace { + +struct Stage { + std::optional lock; + std::shared_ptr writer; + std::uint64_t capacity = 0; + bool handed_off = false; + + Error open(std::optional length) { + Error error; + lock = osupdate::lock(error); + if (!lock) return error; + if (auto e = prepare_offline_upload(*lock); !e.empty()) return e; + struct statvfs space{}; + if (statvfs(offline_directory, &space) != 0) return "Cannot determine the free space for the update"; + const std::uint64_t free = static_cast(space.f_bavail) * space.f_frsize; + constexpr std::uint64_t reserve = 16ULL << 20; + capacity = std::min(max_offline_bytes, free > reserve ? free - reserve : 0); + if (!capacity || (length && *length > capacity)) return "Not enough free space for the update bundle"; + writer = http::FileWriter::open(offline_bundle, O_CREAT | O_EXCL | O_NOFOLLOW, 0600, error); + return error; + } + + ~Stage() { + writer.reset(); + if (lock && !handed_off) discard_offline_upload(*lock); + } +}; + +class OfflineUpload final : public http::BodySink, public std::enable_shared_from_this { +public: + OfflineUpload(const http::Request &req, const http::Response &res, std::optional length) + : id_(req.id), headers_(res.headers), length_(length) {} + + void open() { + auto self = shared_from_this(); + loop::blocking([self] { + auto stage = std::make_shared(); + auto error = stage->open(self->length_); + loop::post([self, stage = std::move(stage), error]() mutable { self->opened(std::move(stage), error); }); + }); + } + + void data(std::string_view chunk) override { + if (done_) return; + last_input_ = Clock::now(); + received_ += chunk.size(); + if (!stage_) { + // Even with receive flow paused, one initial HTTP/2 window may arrive. + if (received_ > (1U << 20)) return fail("Too much data received before the upload was ready"); + prefix_.append(chunk); + return; + } + append(chunk); + } + + void end(http::Request &) override { + ended_ = true; + if (!done_ && stage_) finish(); + } + + void aborted() override { + if (done_) return; + done_ = true; + drop(); + } + +private: + using Clock = std::chrono::steady_clock; + std::uint64_t id_, received_ = 0; + decltype(http::Response::headers) headers_; + std::optional length_; + Clock::time_point last_input_ = Clock::now(); + std::shared_ptr stage_; + std::string prefix_; + bool done_ = false, ended_ = false; + + void opened(std::shared_ptr stage, const Error &error) { + stage_ = std::move(stage); + if (done_) return drop(); + if (!error.empty()) return fail(error); + stage_->writer->feeds(id_); + append(prefix_); + std::string().swap(prefix_); + if (done_) return; + if (!http::pause_request_body(id_, false)) return fail("Could not resume the update upload"); + if (ended_) return finish(); + check_stall(); + } + + void append(std::string_view chunk) { + if (received_ > stage_->capacity) return fail("Update bundle exceeds the available upload space"); + if (!chunk.empty() && !stage_->writer->write(chunk)) fail(stage_->writer->failure()); + } + + void check_stall() { + loop::after(std::chrono::seconds(30), [weak = weak_from_this()] { + auto self = weak.lock(); + if (!self || self->done_) return; + if (self->stage_->writer->holding()) self->last_input_ = Clock::now(); + if (Clock::now() - self->last_input_ >= std::chrono::seconds(60)) self->fail("Update upload timed out"); + else self->check_stall(); + }); + } + + void drop() { + if (!stage_) return; + if (stage_->writer) stage_->writer->abort(); + loop::blocking([stage = std::move(stage_)] {}); + } + + void respond(const Error &error) const { + http::Response res; + res.headers = headers_; + reply(res, "", error); + http::complete(id_, std::move(res)); + } + + void fail(const Error &error) { + aborted(); + respond(error); + } + + void finish() { + if (!received_ || (length_ && *length_ != received_)) return fail("Incomplete update bundle"); + done_ = true; + auto self = shared_from_this(); + stage_->writer->finish([self](const Error &write_error) { + loop::blocking([self, stage = std::move(self->stage_), write_error] { + stage->writer.reset(); + Error error = write_error.empty() ? start_offline(*stage->lock) : write_error; + stage->handed_off = error.empty(); + self->respond(error); + }); + }); + } +}; + +} // namespace + +void add_offline_route(http::Router &router) +{ + constexpr auto path = "/api/os/update/offline"; + auth::Guard admin{{"admin"}}; + router.upload("POST", path, auth::guarded_upload([](http::Request &req, http::Response &res) -> std::shared_ptr { + auto refuse = [&](const char *why) { reply(res, "", why); return nullptr; }; + if (req.header("content-type") != "application/octet-stream") return refuse("Expected an offline update file"); + std::optional length; + auto h = req.header("content-length"); + if (!h.empty()) { + std::uint64_t n = 0; + auto [end, ec] = std::from_chars(h.data(), h.data() + h.size(), n); + if (ec != std::errc{} || end != h.data() + h.size() || !n || n > max_offline_bytes) + return refuse("Invalid update bundle size"); + length = n; + } + if (!http::pause_request_body(req.id, true)) return refuse("Could not start the update upload"); + auto sink = std::make_shared(req, res, length); + sink->open(); + return sink; + }, admin)); + router.add("POST", path, auth::guarded([](http::Request &, http::Response &res) { + reply(res, "", "An update bundle is required"); + }, admin)); +} + +} // namespace nkos::osupdate diff --git a/server-cpp/src/osupdate/osupdate.cpp b/server-cpp/src/osupdate/osupdate.cpp index 714dea4dc..9d047f99e 100644 --- a/server-cpp/src/osupdate/osupdate.cpp +++ b/server-cpp/src/osupdate/osupdate.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -861,23 +862,20 @@ ApkStatus get_apk_status() return s; } -Error start_apk(const std::string &action) +static Error start_apk_locked(const std::string &action, const std::string &state, const UpdateLock &l) { - static const std::map states{ - {"check", "checking"}, {"install", "installing"}, {"rollback", "installing"}, {"reboot", "rebooting"}}; - auto state = states.find(action); - if (state == states.end()) return "invalid package operation"; - if (!files::exists("/etc/alpine-release")) return "native APK updates require Alpine"; Error e; - auto l = lock(e); - if (!l) return e; ApkStatus s; - s.state = state->second; - if (auto err = save_apk_status(s); !err.empty()) return err; + s.state = state; + if (auto err = files::mkdir_all(apk_state_dir, 0700); !err.empty()) return err; std::string log_path = std::string(apk_state_dir) + "/operation.log"; int log = ::open(log_path.c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_CLOEXEC, 0600); if (log < 0) return oserr::path_error("open", log_path, errno); - bool started = start_detached({helper, "apk-inherited", action}, log, l->fd(), e); + if (auto err = save_apk_status(s); !err.empty()) { + ::close(log); + return err; + } + bool started = start_detached({helper, "apk-inherited", action}, log, l.fd(), e); ::close(log); if (!started) { ApkStatus failed; @@ -889,6 +887,40 @@ Error start_apk(const std::string &action) return ""; } +Error start_apk(const std::string &action) +{ + static const std::map states{ + {"check", "checking"}, {"install", "installing"}, {"rollback", "installing"}, {"reboot", "rebooting"}}; + auto state = states.find(action); + if (state == states.end()) return "invalid package operation"; + if (!files::exists("/etc/alpine-release")) return "native APK updates require Alpine"; + Error e; + auto l = lock(e); + if (!l) return e; + return start_apk_locked(action, state->second, *l); +} + +Error prepare_offline_upload(const UpdateLock &) +{ + // A crash during upload or installation can leave the prior bundle here. The lock excludes any live owner. + std::error_code ec; + std::filesystem::remove_all(offline_directory, ec); + if (ec) return "cannot clear the previous offline update: " + ec.message(); + if (::mkdir(offline_directory, 0700) < 0) return oserr::path_error("mkdir", offline_directory, errno); + return {}; +} + +void discard_offline_upload(const UpdateLock &) +{ + std::error_code ec; + std::filesystem::remove_all(offline_directory, ec); +} + +Error start_offline(const UpdateLock &l) +{ + return start_apk_locked("offline", "installing", l); +} + // ---- Channel (channel.go) ---- bool is_core_package(const std::string &name) { return std::find(core_packages.begin(), core_packages.end(), name) != core_packages.end(); } diff --git a/server-cpp/src/osupdate/osupdate.hpp b/server-cpp/src/osupdate/osupdate.hpp index 08e7581ea..e92cfcf9b 100644 --- a/server-cpp/src/osupdate/osupdate.hpp +++ b/server-cpp/src/osupdate/osupdate.hpp @@ -74,6 +74,14 @@ ApkStatus get_apk_status(); std::string to_json(const ApkStatus &s); Error start_apk(const std::string &action); +// Stage only while holding lock(). The detached worker inherits it and takes ownership on success. +inline constexpr const char *offline_directory = "/kvmapp/.os-update/offline"; +inline constexpr const char *offline_bundle = "/kvmapp/.os-update/offline/bundle"; +inline constexpr std::uint64_t max_offline_bytes = 256ULL << 20; +Error prepare_offline_upload(const UpdateLock &lock); +void discard_offline_upload(const UpdateLock &lock); +Error start_offline(const UpdateLock &lock); + // ---- Versions and apk output ---- int compare_apk_versions(const std::string &a, const std::string &b); diff --git a/server-cpp/src/osupdate/routes.cpp b/server-cpp/src/osupdate/routes.cpp index d59f7f529..291ed12cc 100644 --- a/server-cpp/src/osupdate/routes.cpp +++ b/server-cpp/src/osupdate/routes.cpp @@ -50,6 +50,7 @@ void check_in_background() void add_routes(http::Router &router) { + add_offline_route(router); auth::Guard admin{{"admin"}}; auto add = [&](const char *method, const std::string &path, http::Handler handler) { router.add(method, "/api/os/update" + path, auth::guarded(std::move(handler), admin)); diff --git a/server-cpp/src/osupdate/routes.hpp b/server-cpp/src/osupdate/routes.hpp index 3f44449a3..24931c83b 100644 --- a/server-cpp/src/osupdate/routes.hpp +++ b/server-cpp/src/osupdate/routes.hpp @@ -9,6 +9,7 @@ namespace nkos::osupdate { void add_routes(http::Router &router); +void add_offline_route(http::Router &router); // RunNoticeSchedule: the update notice is checked two minutes after the start, then when due (daily; failed // attempts hourly). Starts a thread. diff --git a/server-cpp/tests/osupdate_test.cpp b/server-cpp/tests/osupdate_test.cpp index 6902b7589..6b449e5f0 100644 --- a/server-cpp/tests/osupdate_test.cpp +++ b/server-cpp/tests/osupdate_test.cpp @@ -2,6 +2,8 @@ #include "check.hpp" #include "osupdate/internal.hpp" +#include + using namespace nkos::osupdate; int main() @@ -37,5 +39,17 @@ int main() error.clear(); CHECK(stable_package_targets(components + release, error).empty() && !error.empty(), release); } + const ChannelStatus stable_channel{"stable", true}, beta_channel{"beta", true}; + CHECK(offline_eligibility("5.0.1-r0", "5.0.1-r0", "5.0.2-r0", stable_channel).empty()); + CHECK(offline_eligibility("5.0.1-r0", "5.0.1-r0", "5.0.2_beta1-r0", beta_channel).empty()); + for (const auto &[installed, base, to, selected] : std::vector>{ + {"5.0.1-r1", "5.0.1-r0", "5.0.2-r0", stable_channel}, + {"5.0.1-r0", "5.0.1-r0", "5.0.1-r0", stable_channel}, + {"5.1.0-r0", "5.1.0-r0", "5.0.9-r0", stable_channel}, + {"4.3.2-r0", "4.3.2-r0", "5.0.2-r0", stable_channel}, + {"5.0.1-r0", "5.0.1-r0", "6.0.0-r0", stable_channel}, + {"5.0.1-r0", "5.0.1-r0", "5.0.2_beta1-r0", stable_channel}, + {"5.0.1-r0", "5.0.1-r0", "5.0.2-r0", {}}}) + CHECK(!offline_eligibility(installed, base, to, selected).empty(), to); return finish("osupdate"); } diff --git a/server-cpp/tests/run.sh b/server-cpp/tests/run.sh index 6f442f6d1..d6354e8a7 100755 --- a/server-cpp/tests/run.sh +++ b/server-cpp/tests/run.sh @@ -53,7 +53,7 @@ fi # The server units the tests reach, as one archive. units="ai/agent_acp ai/agent_store ai/files ai/json ai/keys ai/mcp ai/tools api/multipart auth/brute_force auth/jwt auth/password auth/session auth/store auth/totp bmc/config bmc/ipmi - bmc/redfish common/fs common/log common/loop common/oserr common/path common/process common/text config/config config/yaml http/multipart http/router input/control input/hid input/media_keys network/util osupdate/osupdate + bmc/redfish common/fs common/log common/loop common/oserr common/path common/process common/text config/config config/yaml http/multipart http/router input/control input/hid input/media_keys network/util osupdate/osupdate osupdate/offline storage/download storage/go storage/userdisk system/serial_exchange system/ssh_keys system/tls_x509" flags=(-std=c++23 -O1 -pthread -ffunction-sections -fdata-sections -I"$src" -I"$b/glaze/include" -I"$b/inc" -I"$b/lws/include" -I"$b/multipart" -I"$tests") diff --git a/tests/test-offline-delta.py b/tests/test-offline-delta.py new file mode 100644 index 000000000..3433aa927 --- /dev/null +++ b/tests/test-offline-delta.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Public release baselines and constrained offline dependency solving.""" +import json +from pathlib import Path +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts')) +import offline_delta as delta + + +def release(tag, *, draft=False): + return {'tag_name': tag, 'published_at': '2026-01-01', 'draft': draft} + + +# Pages-only v5.0.2 has no public release. v5.0.3 must work from v5.0.1. +releases = [release('v4.3.2'), release('v5.0.1'), release('v5.0.3-beta'), release('v5.0.3', draft=True)] +assert delta.previous_public(releases, 'v5.0.3')['tag_name'] == 'v5.0.1' +assert delta.previous_public(releases, 'v5.0.3-beta.1')['tag_name'] == 'v5.0.3-beta' +assert delta.previous_public(releases, 'v5.0.0') is None + +with tempfile.TemporaryDirectory() as directory: + work = Path(directory) + plan = work/'plan' + for action in ('Purging', 'Downgrading', 'Replacing', 'Unknown'): + plan.write_text(f'(1/1) {action} example (1.0-r0)\n') + try: + delta.plan_changes(plan) + except ValueError: + pass + else: + raise AssertionError(f'accepted {action}') + # APK's selected version can be lower than the most recent version in + # the stock target image. Unrelated package changes are never roots. + base = {n: {'V': '1.0-r0'} for n in ('nanokvm-release', 'unrelated', 'provider', 'minimum')} + target = dict.fromkeys(base, '2.0-r0') + assert delta.roots_for(base, target) == ['nanokvm-release=2.0-r0'] + if len(sys.argv) > 1: + apk = sys.argv[1] + + def run(*args): + return subprocess.check_output([apk, *map(str, args)], text=True) + + def package(name, version, **fields): + path = work/f'{name}-{version}.apk' + args = ['mkpkg', '--output', path] + for key, value in dict(name=name, version=version, arch='riscv64', **fields).items(): + args.extend(['--info', f'{key}:{value}']) + run(*args) + return path + + root = work/'root' + (root/'lib/apk/db').mkdir(parents=True) + (root/'etc/apk').mkdir(parents=True) + (root/'etc/apk/world').write_text('nanokvm-release\nunrelated\n') + installed = [package(n, '1.0-r0', **({'provides': 'virtual=1'} if n == 'provider' else {})) + for n in base] + old = work/'old.adb' + run('--allow-untrusted', 'mkndx', '-o', old, *installed) + old_records = [delta.index_record(p) for p in json.loads(run('--allow-untrusted', 'adbdump', '--format=json', old))['packages']] + (root/'lib/apk/db/installed').write_text(delta.db_text({r['P']: r for r in old_records})) + # The new release requires both the existing virtual provider and an + # upgraded transitive dependency of newdep. Only the latter must move. + available = [package('nanokvm-release', '2.0-r0', depends='virtual>=1 newdep'), + package('newdep', '1.0-r0', depends='minimum>=2'), + package('minimum', '2.0-r0'), package('provider', '2.0-r0', provides='virtual=2'), + package('unrelated', '2.0-r0')] + index = work/'Packages.adb' + run('--allow-untrusted', 'mkndx', '-o', index, *available) + plan.write_text(run('--arch', 'riscv64', '--allow-untrusted', '--no-network', '--root', root, + '--repositories-file=/dev/null', '--repository=' + str(index), + 'add', '--simulate', *delta.roots_for(base, target))) + assert delta.plan_changes(plan) == {'newdep': '1.0-r0', 'minimum': '2.0-r0', 'nanokvm-release': '2.0-r0'} + +print('Offline release delta tests passed') diff --git a/web/src/api/updates.ts b/web/src/api/updates.ts index c077fb8db..c74ddc69c 100644 --- a/web/src/api/updates.ts +++ b/web/src/api/updates.ts @@ -29,3 +29,12 @@ export const setUpdateNoticeEnabled = (enabled: boolean) => export const availableUpdates = (notice: UpdateNotice | null | undefined) => notice?.enabled ? notice.updates : []; + +export function installOfflineUpdate(file: File, onProgress: (percent: number) => void) { + return http.post('/api/os/update/offline', file, { + headers: { 'Content-Type': 'application/octet-stream' }, + timeout: 0, + onUploadProgress: ({ loaded }) => + onProgress(Math.min(100, Math.floor((loaded * 100) / file.size))) + }); +} diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index e6a2609af..52d4d3c5a 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -1036,6 +1036,10 @@ "requestFailed": "The software request failed. Check device connectivity and retry." }, "updates": { + "offline": { + "install": "Install update from file", + "invalidSize": "Choose a NanoKVM OS offline update archive (.tar) between 1 byte and 256 MiB." + }, "apk": { "check": "Check for updates", "install": "Install updates", diff --git a/web/src/pages/desktop/menu/settings/updates/card.tsx b/web/src/pages/desktop/menu/settings/updates/card.tsx index 6d73544e1..fee4066fb 100644 --- a/web/src/pages/desktop/menu/settings/updates/card.tsx +++ b/web/src/pages/desktop/menu/settings/updates/card.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'; import { Alert, Button, Collapse, message, Popconfirm, Spin, Switch } from 'antd'; import { useAtomValue } from 'jotai'; import { useTranslation } from 'react-i18next'; @@ -30,7 +30,8 @@ export const UpdateCard = ({ components, busy, action, - onChange + onChange, + children }: { version?: string; apk?: APKState; @@ -39,6 +40,7 @@ export const UpdateCard = ({ busy: boolean; action: (name: string) => Promise; onChange: () => Promise; + children: ReactNode; }) => { const { t, i18n } = useTranslation(); const tr = useCallback( @@ -160,6 +162,7 @@ export const UpdateCard = ({ )} + {children} {apk?.reboot && ( diff --git a/web/src/pages/desktop/menu/settings/updates/index.tsx b/web/src/pages/desktop/menu/settings/updates/index.tsx index a0b99dcf2..a382aa4a7 100644 --- a/web/src/pages/desktop/menu/settings/updates/index.tsx +++ b/web/src/pages/desktop/menu/settings/updates/index.tsx @@ -11,6 +11,7 @@ import { SettingRow } from '@/components/ui/settings.tsx'; import { UpdateCard, type APKState } from './card'; import { ComponentList, Fold } from './components'; +import { OfflineUpdate } from './offline'; type State = { apk?: APKState; @@ -110,7 +111,9 @@ export const Updates = () => { busy={busy} action={action} onChange={refresh} - /> + > + + )} {state && ( diff --git a/web/src/pages/desktop/menu/settings/updates/offline.tsx b/web/src/pages/desktop/menu/settings/updates/offline.tsx new file mode 100644 index 000000000..f9305915d --- /dev/null +++ b/web/src/pages/desktop/menu/settings/updates/offline.tsx @@ -0,0 +1,89 @@ +import { useRef, useState } from 'react'; +import { Alert, Button, Modal, Progress } from 'antd'; +import { useTranslation } from 'react-i18next'; + +import { installOfflineUpdate } from '@/api/updates.ts'; +import { requestErrorText } from '@/lib/request-error.ts'; + +const maxBundleSize = 256 * 1024 * 1024; + +export const OfflineUpdate = ({ + disabled, + onBusy, + onChange +}: { + disabled: boolean; + onBusy: (busy: boolean) => void; + onChange: () => Promise; +}) => { + const { t } = useTranslation(); + const input = useRef(null); + const [file, setFile] = useState(); + const [percent, setPercent] = useState(null); + const [error, setError] = useState(null); + const uploading = percent !== null; + const validSize = !!file && file.size > 0 && file.size <= maxBundleSize; + + async function install() { + if (!file || !validSize || disabled || uploading) return; + onBusy(true); + setPercent(0); + setError(null); + try { + const rsp = await installOfflineUpdate(file, setPercent); + if (rsp.code !== 0) throw rsp; + setFile(undefined); + } catch (err) { + setError(requestErrorText(err, t('settings.updates.requestFailed'))); + } finally { + await onChange(); + setPercent(null); + onBusy(false); + } + } + + return ( + <> + { + setFile(event.target.files?.[0]); + setError(null); + event.target.value = ''; + }} + /> + + setFile(undefined)} + > +

{file?.name}

+

{t('settings.updates.apk.confirm')}

+ {percent !== null && ( +
+ {percent === 100 ? t('download.finishing') : t('download.uploading')} + +
+ )} + {file && !validSize && ( + + )} + {error && } +
+ + ); +}; From be894e9d6f8844943a21b675a43edc69b24cb25c Mon Sep 17 00:00:00 2001 From: Gleb Pesin Date: Wed, 2 Dec 2026 19:25:42 +0200 Subject: [PATCH 2/4] fix(updates): limit offline archives and installation to Stable --- .github/workflows/release.yml | 4 ++-- docs/RELEASE-NAMING.md | 6 +++--- docs/UPDATES.md | 10 +++++----- platform/README.md | 2 +- scripts/offline_delta.py | 8 +++++--- scripts/publish-release.py | 2 +- scripts/release_assets.py | 4 ++-- server-cpp/src/osupdate/offline.cpp | 3 ++- server-cpp/src/osupdate/osupdate.cpp | 3 ++- server-cpp/src/osupdate/osupdate.hpp | 1 + server-cpp/tests/osupdate_test.cpp | 5 ++++- tests/test-offline-delta.py | 5 ++++- web/src/pages/desktop/menu/settings/updates/index.tsx | 11 +++++++++-- 13 files changed, 41 insertions(+), 23 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ce842a424..82b40f28a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -335,7 +335,7 @@ jobs: out: ${{ env.OUT }} keys: -e ${{ runner.temp }}/keys/${{ env.EC_KEY_NAME }}.key image: ${{ needs.build.outputs.image }} - offline: ${{ inputs.packages_only != true }} + offline: ${{ inputs.packages_only != true && !contains(needs.build.outputs.version, '-beta') }} - name: Remove the keys if: always() @@ -414,7 +414,7 @@ jobs: out: ${{ env.OUT }} keys: -d image: ${{ needs.build.outputs.image }} - offline: ${{ inputs.packages_only != true }} + offline: ${{ inputs.packages_only != true && !contains(needs.build.outputs.version, '-beta') }} - uses: actions/upload-artifact@v7 with: diff --git a/docs/RELEASE-NAMING.md b/docs/RELEASE-NAMING.md index 55db54a7f..7700a75bb 100644 --- a/docs/RELEASE-NAMING.md +++ b/docs/RELEASE-NAMING.md @@ -19,13 +19,13 @@ full tag so you can keep several release manifests in one directory. GitHub releases also include an identical `SHA256SUMS` for older stock installers. Older releases may only provide `SHA256SUMS`. -Public releases with offline-update support include `NanoKVM-OS--offline.tar`. +Public stable releases with offline-update support include `NanoKVM-OS--offline.tar`. It carries changed NanoKVM components and the dependencies APK must install or -upgrade from the preceding compatible public release. Its signed `base-version` +upgrade from the preceding public stable release. Its signed `base-version` names the required `nanokvm-release` APK version. The signed `installed-db` records the resulting package state for the next offline update. The first public release on a major has no delta. -Pages-only OTA publications omit this download. +Beta releases and Pages-only OTA publications omit this download. Releases that include an SD image also include the [stock migration package](STOCK-INSTALL.md). Its numeric `nanokvm_X.Y.Z.tar.gz` diff --git a/docs/UPDATES.md b/docs/UPDATES.md index 69e9a84f5..a010883be 100644 --- a/docs/UPDATES.md +++ b/docs/UPDATES.md @@ -38,11 +38,11 @@ Completed component transactions refresh affected services through separate apply command is required. `nanokvm-bootloader` also updates the bootloader on the SD card. It verifies the written file and keeps `/boot/fip.prev` for recovery; see [bootloader updates](BOOT.md#updating-fipbin). -## Updating a 5.x device without internet access +## Updating a Stable 5.x device without internet access 1. On a connected computer, download `NanoKVM-OS--offline.tar` from the - target OS release. Each archive updates one specific base version on the - selected Stable or Beta channel. The signed `base-version` file inside + target stable OS release. Each archive updates the preceding public stable + version on the Stable channel. Beta devices use the online updater. The signed `base-version` file inside the archive names the required version of the installed `nanokvm-release` package. Apply successive deltas in order if you are several releases behind. 2. Open **Settings → System → Updates → Install update from file** on the @@ -65,7 +65,7 @@ device can use the same archive as a local APK repository. On a trusted computer, verify the archive against the SHA-256 published with the release, extract it into an empty directory, and copy the directory to private system storage on the NanoKVM (for example `/root/offline-update`). Use a newer -5.x release matching the selected channel. In an SSH session on the NanoKVM, +stable 5.x release on the Stable channel. In an SSH session on the NanoKVM, check that the archive starts at the installed release, then preview the transaction: ```sh @@ -214,7 +214,7 @@ removed. ## Package publication and retention -Public 5.x releases with offline-update support include the signed offline bundle, corresponding source, checksums, +Public stable 5.x releases with offline-update support include the signed offline bundle, corresponding source, checksums, and, when built, the SD image and stock migration archive. APKs, indexes and the downloads of packages released on their own live on GitHub Pages. Their version tags reserve package revisions without creating GitHub Releases. The diff --git a/platform/README.md b/platform/README.md index 076c9afb2..ab6230375 100644 --- a/platform/README.md +++ b/platform/README.md @@ -30,7 +30,7 @@ Every upstream input is pinned in `sources.lock` and checked when it is download | `release/apk/` | the signed APK repository of the OS packages: `recipes/riscv64/` with the packages, `APKINDEX.tar.gz` and `Packages.adb`, and the public keys | | `release/alpine-rootfs.tar.gz`, `release/installed-packages.txt`, `release/installed-licenses.txt` | the root file system, its package versions and their declared licenses | | `release/image/NanoKVM-OS-.img.zip`, `SHA256SUMS` | the SD card image | -| `release/NanoKVM-OS--offline.tar` | a signed offline delta from the preceding public OS version | +| `release/NanoKVM-OS--offline.tar` | a signed Stable-channel offline delta from the preceding public stable OS version | | `release/stock-installer/nanokvm_X.Y.Z.tar.gz`, `SHA256SUMS` | stock Sipeed migration package (`stock-installer` step; included with SD image releases) | ## Release and installation versions diff --git a/scripts/offline_delta.py b/scripts/offline_delta.py index 8cef0e330..fee76c7f8 100644 --- a/scripts/offline_delta.py +++ b/scripts/offline_delta.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Pick the previous public release available on this channel and diff its APK inventory.""" +"""Pick the previous public stable release and diff its APK inventory.""" import argparse import base64 import hashlib @@ -39,10 +39,12 @@ def previous_public(releases, target): match = OS_TAG.fullmatch(target) if not match: raise ValueError(f'Invalid target tag: {target!r}') + if match[1] != "5" or match[4]: + return None candidates = (r for r in releases if not r['draft'] and r.get('published_at') and (m := OS_TAG.fullmatch(r['tag_name'])) and m[1] == match[1] - and (match[4] or not a.is_beta(r)) + and not a.is_beta(r) and a.order(r) < a.order({'tag_name': target})) return max(candidates, key=a.order, default=None) @@ -142,7 +144,7 @@ def roots_for(base, target): def prepare(target, installed, output): previous = previous_public(inventory(), target) - if previous is None or OS_TAG.fullmatch(target)[1] != '5': + if previous is None: print(f'{target}: no compatible public baseline; skipping offline delta') return tag = previous['tag_name'] diff --git a/scripts/publish-release.py b/scripts/publish-release.py index 3f92425dd..445b14986 100644 --- a/scripts/publish-release.py +++ b/scripts/publish-release.py @@ -70,7 +70,7 @@ def validate_public_names(version, names, *, require_versioned=False): images = [n for n in names if (versions := image_versions(n)) and versions[1] == version] installer = {'nanokvm_' + version.removeprefix('v').split('-', 1)[0] + '.tar.gz'} & set(names) offline = {f'NanoKVM-OS-{version}-offline.tar'} - if offline.intersection(names): + if '-beta' not in version and offline.intersection(names): required.update(offline) if (len(names) != len(set(names)) or any(Path(n).name != n for n in names) or len(images) > 1 or set(names) != required | set(images) | installer): diff --git a/scripts/release_assets.py b/scripts/release_assets.py index 359940f47..fda0a19d1 100644 --- a/scripts/release_assets.py +++ b/scripts/release_assets.py @@ -94,8 +94,8 @@ def split(directory): raise ValueError('Stock installer version differs from the release source') for file in public: offline = OFFLINE_BUNDLE.fullmatch(file.name) - if offline and offline[1] != version: - raise ValueError('Offline bundle version differs from the release source') + if offline and (offline[1] != version or '-beta' in version): + raise ValueError('Offline bundle requires a matching stable OS release') for name, group in [('public', public), ('packages', packages)]: target = directory / name target.mkdir() diff --git a/server-cpp/src/osupdate/offline.cpp b/server-cpp/src/osupdate/offline.cpp index b231085a9..9c6593293 100644 --- a/server-cpp/src/osupdate/offline.cpp +++ b/server-cpp/src/osupdate/offline.cpp @@ -171,7 +171,8 @@ Error offline_eligibility(const std::string &installed, const std::string &base_ if (!installed.starts_with("5.") || !target.starts_with("5.")) return "offline updates require an installed 5.x system and a 5.x release"; if (installed != base_version) return "this offline update requires nanokvm-release " + base_version + "; installed: " + installed; if (compare_apk_versions(target, installed) <= 0) return "the offline release must be newer than the installed release"; - if (!channel.available || channel.channel != (prerelease(target) ? "beta" : "stable")) return "offline release does not match the selected update channel"; + if (!channel.offline_available() || prerelease(installed) || prerelease(target)) + return "Offline updates require Stable releases on the Stable channel"; return {}; } diff --git a/server-cpp/src/osupdate/osupdate.cpp b/server-cpp/src/osupdate/osupdate.cpp index 9d047f99e..525b43c56 100644 --- a/server-cpp/src/osupdate/osupdate.cpp +++ b/server-cpp/src/osupdate/osupdate.cpp @@ -902,6 +902,7 @@ Error start_apk(const std::string &action) Error prepare_offline_upload(const UpdateLock &) { + if (!get_channel().offline_available()) return "Offline updates require an installed Stable release on the Stable channel"; // A crash during upload or installation can leave the prior bundle here. The lock excludes any live owner. std::error_code ec; std::filesystem::remove_all(offline_directory, ec); @@ -1017,7 +1018,7 @@ ChannelStatus get_channel() std::string to_json(const ChannelStatus &c) { return "{\"channel\":" + json::str(c.channel) + ",\"available\":" + json::boolean(c.available) + - ",\"rollbackAvailable\":" + json::boolean(c.rollback_available) + "}"; + ",\"rollbackAvailable\":" + json::boolean(c.rollback_available) + ",\"offlineAvailable\":" + json::boolean(c.offline_available()) + "}"; } namespace { diff --git a/server-cpp/src/osupdate/osupdate.hpp b/server-cpp/src/osupdate/osupdate.hpp index e92cfcf9b..adf1fa330 100644 --- a/server-cpp/src/osupdate/osupdate.hpp +++ b/server-cpp/src/osupdate/osupdate.hpp @@ -149,6 +149,7 @@ std::vector installed_components(); struct ChannelStatus { std::string channel = "custom"; bool available = false, rollback_available = false; + bool offline_available() const { return available && channel == "stable" && !rollback_available; } }; ChannelStatus get_channel(); std::string to_json(const ChannelStatus &c); diff --git a/server-cpp/tests/osupdate_test.cpp b/server-cpp/tests/osupdate_test.cpp index 6b449e5f0..513b0a2fc 100644 --- a/server-cpp/tests/osupdate_test.cpp +++ b/server-cpp/tests/osupdate_test.cpp @@ -41,8 +41,11 @@ int main() } const ChannelStatus stable_channel{"stable", true}, beta_channel{"beta", true}; CHECK(offline_eligibility("5.0.1-r0", "5.0.1-r0", "5.0.2-r0", stable_channel).empty()); - CHECK(offline_eligibility("5.0.1-r0", "5.0.1-r0", "5.0.2_beta1-r0", beta_channel).empty()); for (const auto &[installed, base, to, selected] : std::vector>{ + {"5.0.1-r0", "5.0.1-r0", "5.0.2_beta1-r0", beta_channel}, + {"5.0.1-r0", "5.0.1-r0", "5.0.2-r0", beta_channel}, + {"5.1.0_beta-r0", "5.1.0_beta-r0", "5.1.0-r0", stable_channel}, + {"5.0.1-r0", "5.0.1-r0", "5.0.2-r0", {"stable", true, true}}, {"5.0.1-r1", "5.0.1-r0", "5.0.2-r0", stable_channel}, {"5.0.1-r0", "5.0.1-r0", "5.0.1-r0", stable_channel}, {"5.1.0-r0", "5.1.0-r0", "5.0.9-r0", stable_channel}, diff --git a/tests/test-offline-delta.py b/tests/test-offline-delta.py index 3433aa927..be9dbbd55 100644 --- a/tests/test-offline-delta.py +++ b/tests/test-offline-delta.py @@ -17,7 +17,10 @@ def release(tag, *, draft=False): # Pages-only v5.0.2 has no public release. v5.0.3 must work from v5.0.1. releases = [release('v4.3.2'), release('v5.0.1'), release('v5.0.3-beta'), release('v5.0.3', draft=True)] assert delta.previous_public(releases, 'v5.0.3')['tag_name'] == 'v5.0.1' -assert delta.previous_public(releases, 'v5.0.3-beta.1')['tag_name'] == 'v5.0.3-beta' +assert delta.previous_public(releases, 'v5.0.3-beta.1') is None +assert delta.previous_public(releases, 'v5.0.4-beta') is None +assert delta.previous_public([release('v5.0.0-beta')], 'v5.0.0') is None +assert delta.previous_public([*releases, release('v5.0.3')], 'v5.0.4')['tag_name'] == 'v5.0.3' assert delta.previous_public(releases, 'v5.0.0') is None with tempfile.TemporaryDirectory() as directory: diff --git a/web/src/pages/desktop/menu/settings/updates/index.tsx b/web/src/pages/desktop/menu/settings/updates/index.tsx index a382aa4a7..6d8d758f3 100644 --- a/web/src/pages/desktop/menu/settings/updates/index.tsx +++ b/web/src/pages/desktop/menu/settings/updates/index.tsx @@ -18,7 +18,12 @@ type State = { installed: { version: string }; components?: Components; notice?: UpdateNotice; - channel?: { channel: string; available: boolean; rollbackAvailable?: boolean }; + channel?: { + channel: string; + available: boolean; + rollbackAvailable?: boolean; + offlineAvailable?: boolean; + }; }; // System > Updates: the update card first, then the installed components and @@ -112,7 +117,9 @@ export const Updates = () => { action={action} onChange={refresh} > - + {state.channel?.offlineAvailable && ( + + )} )} {state && ( From ef5cf4241ba077c6cb1a1a25365e6ed0dba47875 Mon Sep 17 00:00:00 2001 From: Gleb Pesin Date: Wed, 2 Dec 2026 19:33:07 +0200 Subject: [PATCH 3/4] feat(updates): sign and verify the minimum supported Stable release --- .github/workflows/release.yml | 1 + docs/RELEASE-NAMING.md | 14 +++-- docs/UPDATES.md | 30 ++++++---- firmware/alpine/offline-minimums.json | 1 + platform/README.md | 2 +- scripts/build-offline-repository.sh | 34 +++++++----- scripts/offline_delta.py | 79 +++++++++++++++++---------- scripts/sign-release.sh | 10 +++- server-cpp/src/osupdate/internal.hpp | 2 +- server-cpp/src/osupdate/offline.cpp | 63 +++++++++++++++------ server-cpp/tests/osupdate_test.cpp | 7 ++- tests/test-offline-delta.py | 19 +++++-- 12 files changed, 172 insertions(+), 90 deletions(-) create mode 100644 firmware/alpine/offline-minimums.json diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 82b40f28a..a30649ecc 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -61,6 +61,7 @@ on: - scripts/sign-release.sh - scripts/build-offline-repository.sh - scripts/offline_delta.py + - firmware/alpine/offline-minimums.json - scripts/apk_resign.py - scripts/check-release-key.sh - scripts/alpine-signer.sh diff --git a/docs/RELEASE-NAMING.md b/docs/RELEASE-NAMING.md index 7700a75bb..1c8bd20e7 100644 --- a/docs/RELEASE-NAMING.md +++ b/docs/RELEASE-NAMING.md @@ -20,11 +20,15 @@ releases also include an identical `SHA256SUMS` for older stock installers. Older releases may only provide `SHA256SUMS`. Public stable releases with offline-update support include `NanoKVM-OS--offline.tar`. -It carries changed NanoKVM components and the dependencies APK must install or -upgrade from the preceding public stable release. Its signed `base-version` -names the required `nanokvm-release` APK version. The signed `installed-db` -records the resulting package state for the next offline update. The first -public release on a major has no delta. +It carries changed NanoKVM components and required dependencies for the signed +range `minimum-version <= installed nanokvm-release < target`. By default the +minimum is the previous public stable release on the same major. To support a +wider range, add an entry such as `"v6.0.0": "v5.3.0"` to +`firmware/alpine/offline-minimums.json` before building the target. The minimum +must be a published stable release from 5.x or later. With no eligible baseline +the build skips the archive. Build-time APK simulations cover every public stable +baseline in the range, and the device checks its own installed packages before +applying the update. The signed `installed-db` records the resulting package state. Beta releases and Pages-only OTA publications omit this download. Releases that include an SD image also include the diff --git a/docs/UPDATES.md b/docs/UPDATES.md index a010883be..14b3b0750 100644 --- a/docs/UPDATES.md +++ b/docs/UPDATES.md @@ -38,13 +38,13 @@ Completed component transactions refresh affected services through separate apply command is required. `nanokvm-bootloader` also updates the bootloader on the SD card. It verifies the written file and keeps `/boot/fip.prev` for recovery; see [bootloader updates](BOOT.md#updating-fipbin). -## Updating a Stable 5.x device without internet access +## Updating a Stable device without internet access 1. On a connected computer, download `NanoKVM-OS--offline.tar` from the - target stable OS release. Each archive updates the preceding public stable - version on the Stable channel. Beta devices use the online updater. The signed `base-version` file inside - the archive names the required version of the installed `nanokvm-release` - package. Apply successive deltas in order if you are several releases behind. + target stable OS release. The signed `minimum-version` file gives the oldest + supported `nanokvm-release`. An archive for 6.0.0 with a minimum of 5.3.0 + can upgrade 5.3.0 or 5.4.0 directly. On 5.1.2, first install a compatible + intermediate release. Beta devices use the online updater. 2. Open **Settings → System → Updates → Install update from file** on the NanoKVM. Choose the intact tar file and confirm its name. The upload progress is followed by the usual package installation log. @@ -54,7 +54,8 @@ The archive targets new or changed NanoKVM OS components and bundled modules. It includes an Alpine package only when the base installation needs it to meet the dependencies of those components or their libraries. APK reuses installed libraries that already meet the requirements. Before installation the updater -verifies the archive signature, base version, target channel and APK transaction. It reports missing dependencies or conflicting local packages in +verifies the archive signature, supported version range, channel and APK transaction. +It reports missing dependencies or conflicting local packages in the update log. Allow space on the system partition for the upload, unpacking and installation. Package-only hotfixes on Pages have no GitHub release archive. @@ -65,14 +66,21 @@ device can use the same archive as a local APK repository. On a trusted computer, verify the archive against the SHA-256 published with the release, extract it into an empty directory, and copy the directory to private system storage on the NanoKVM (for example `/root/offline-update`). Use a newer -stable 5.x release on the Stable channel. In an SSH session on the NanoKVM, -check that the archive starts at the installed release, then preview the transaction: +stable release on the Stable channel. In an SSH session on the NanoKVM, +check the supported version range, then preview the transaction: ```sh cd /root/offline-update || exit 1 -base=$(cat base-version) || exit 1 +minimum=$(cat minimum-version) || exit 1 installed=$(apk --no-network --repositories-file=/dev/null query --from=installed --fields=version --format=default nanokvm-release) -[ "$installed" = "Version: $base" ] || { echo "This archive requires nanokvm-release $base"; exit 1; } +installed=${installed#Version: } +set -- nanokvm-release-*.apk +[ "$#" -eq 1 ] && [ -f "$1" ] || exit 1 +target=${1#nanokvm-release-} +target=${target%.apk} +case "$installed" in *'_'*|'') exit 1 ;; esac +case "$(apk version -t "$installed" "$minimum")" in '='|'>') ;; *) echo "Requires NanoKVM OS $minimum or newer"; exit 1 ;; esac +[ "$(apk version -t "$installed" "$target")" = '<' ] || exit 1 # Use the already installed NanoKVM packages as the upgrade targets. set -- $(apk --no-network --repositories-file=/dev/null query --from=installed --fields=name --format=default 'nanokvm' 'nanokvm-*' | sed -n 's/^Name: //p') [ "$#" -gt 0 ] || exit 1 @@ -214,7 +222,7 @@ removed. ## Package publication and retention -Public stable 5.x releases with offline-update support include the signed offline bundle, corresponding source, checksums, +Public stable releases with offline-update support include the signed offline bundle, corresponding source, checksums, and, when built, the SD image and stock migration archive. APKs, indexes and the downloads of packages released on their own live on GitHub Pages. Their version tags reserve package revisions without creating GitHub Releases. The diff --git a/firmware/alpine/offline-minimums.json b/firmware/alpine/offline-minimums.json new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/firmware/alpine/offline-minimums.json @@ -0,0 +1 @@ +{} diff --git a/platform/README.md b/platform/README.md index ab6230375..e1c4ef0fb 100644 --- a/platform/README.md +++ b/platform/README.md @@ -30,7 +30,7 @@ Every upstream input is pinned in `sources.lock` and checked when it is download | `release/apk/` | the signed APK repository of the OS packages: `recipes/riscv64/` with the packages, `APKINDEX.tar.gz` and `Packages.adb`, and the public keys | | `release/alpine-rootfs.tar.gz`, `release/installed-packages.txt`, `release/installed-licenses.txt` | the root file system, its package versions and their declared licenses | | `release/image/NanoKVM-OS-.img.zip`, `SHA256SUMS` | the SD card image | -| `release/NanoKVM-OS--offline.tar` | a signed Stable-channel offline delta from the preceding public stable OS version | +| `release/NanoKVM-OS--offline.tar` | a signed Stable-channel offline delta with a signed minimum installed OS version | | `release/stock-installer/nanokvm_X.Y.Z.tar.gz`, `SHA256SUMS` | stock Sipeed migration package (`stock-installer` step; included with SD image releases) | ## Release and installation versions diff --git a/scripts/build-offline-repository.sh b/scripts/build-offline-repository.sh index 2d06395be..5e6f68c4d 100644 --- a/scripts/build-offline-repository.sh +++ b/scripts/build-offline-repository.sh @@ -11,17 +11,18 @@ apk_target() { if [ "$1" = plan ]; then mkdir -p /work/offline /work/fetched /work/offline-keys "$root/lib/apk/db" "$root/etc/apk" "$root/var/cache/apk" cp /usr/share/apk/keys/riscv64/*.pub /work/published/*.pub /work/release/*.pub /work/offline-keys/ - cp /work/delta/world "$root/etc/apk/world" - cp /work/delta/installed "$root/lib/apk/db/installed" printf '%s\n' /work/repo/Packages.adb "$(cat /work/addons.list)" \ https://dl-cdn.alpinelinux.org/alpine/v3.24/main \ https://dl-cdn.alpinelinux.org/alpine/v3.24/community > /work/offline-repositories - apk_target update # No global upgrade: already installed providers are eligible, including # those no longer present in Alpine's rolling stable package indexes. - set -f - # shellcheck disable=SC2046 - apk_target add --simulate $(cat /work/delta/roots) > /work/delta/plan + for base in /work/delta/bases/*; do + cp "$base/world" "$root/etc/apk/world" + cp "$base/installed" "$root/lib/apk/db/installed" + if [ "$base" = /work/delta/bases/0 ]; then apk_target update; fi + # shellcheck disable=SC2046 + apk_target add --simulate $(cat "$base/roots") > "$base/plan" + done exit fi @@ -34,7 +35,7 @@ while IFS='=' read -r name revision; do cp "/work/repo/$file" . else apk_target fetch --all-matches --output /work/fetched "$name" - mv "/work/fetched/$file" . + cp "/work/fetched/$file" . fi done < /work/delta/fetch apk --sign-key /work/keys/release.key --allow-untrusted mkndx \ @@ -42,11 +43,14 @@ apk --sign-key /work/keys/release.key --allow-untrusted mkndx \ apk --keys-dir /work/release verify Packages.adb apk --keys-dir /work/release adbdump --format=json Packages.adb > /work/delta/selected.json # Exercise the device transaction using its installed NanoKVM targets and only the staged files. -set -f -# shellcheck disable=SC2046 -set -- $(awk -F: '$1 == "P" && ($2 == "nanokvm" || $2 ~ /^nanokvm-/) {print $2}' /work/delta/installed) -[ "$#" -gt 0 ] || exit 1 -apk --root "$root" --arch riscv64 --keys-dir /work/release --no-network --no-cache \ - --repositories-file=/dev/null --repository=/work/offline/Packages.adb \ - upgrade --no-self-upgrade --simulate "$@" > /work/delta/offline-plan -cp /work/delta/base-version . +for base in /work/delta/bases/*; do + cp "$base/world" "$root/etc/apk/world" + cp "$base/installed" "$root/lib/apk/db/installed" + # shellcheck disable=SC2046 + set -- $(awk -F: '$1 == "P" && ($2 == "nanokvm" || $2 ~ /^nanokvm-/) {print $2}' "$base/installed") + [ "$#" -gt 0 ] || exit 1 + apk --root "$root" --arch riscv64 --keys-dir /work/release --no-network --no-cache \ + --repositories-file=/dev/null --repository=/work/offline/Packages.adb \ + upgrade --no-self-upgrade --simulate "$@" > "$base/offline-plan" +done +cp /work/delta/minimum-version . diff --git a/scripts/offline_delta.py b/scripts/offline_delta.py index fee76c7f8..c5a50023a 100644 --- a/scripts/offline_delta.py +++ b/scripts/offline_delta.py @@ -35,18 +35,21 @@ def packages(data, tag): return result -def previous_public(releases, target): +def supported_bases(releases, target, minimum=None): match = OS_TAG.fullmatch(target) if not match: raise ValueError(f'Invalid target tag: {target!r}') - if match[1] != "5" or match[4]: - return None - candidates = (r for r in releases - if not r['draft'] and r.get('published_at') - and (m := OS_TAG.fullmatch(r['tag_name'])) and m[1] == match[1] - and not a.is_beta(r) - and a.order(r) < a.order({'tag_name': target})) - return max(candidates, key=a.order, default=None) + if int(match[1]) < 5 or match[4]: + return [] + eligible = sorted((r for r in releases if not r['draft'] and r.get('published_at') + and (m := OS_TAG.fullmatch(r['tag_name'])) and int(m[1]) >= 5 + and not a.is_beta(r) and a.order(r) < a.order({'tag_name': target})), key=a.order) + if minimum is None: + return [r for r in eligible if OS_TAG.fullmatch(r['tag_name'])[1] == match[1]][-1:] + for i, release in enumerate(eligible): + if release['tag_name'] == minimum: + return eligible[i:] + raise ValueError(f'{target}: minimum {minimum!r} must be an earlier published Stable release (5.x or newer)') def signed_state(release, filename, work): @@ -143,10 +146,21 @@ def roots_for(base, target): def prepare(target, installed, output): - previous = previous_public(inventory(), target) - if previous is None: + minimums = json.loads((KEYS.parent / 'offline-minimums.json').read_text()) + bases = supported_bases(inventory(), target, minimums.get(target)) + if not bases: print(f'{target}: no compatible public baseline; skipping offline delta') return + target_packages = packages(installed.read_bytes(), target) + for i, release in enumerate(bases): + directory = output / 'bases' / str(i) + directory.mkdir(parents=True) + base_version = prepare_base(release, target, target_packages, directory) + if i == 0: + (output / 'minimum-version').write_text(base_version + '\n') + + +def prepare_base(previous, target, target_packages, output): tag = previous['tag_name'] filename = f'NanoKVM-OS-{tag}-offline.tar' with tempfile.TemporaryDirectory() as temp: @@ -159,16 +173,14 @@ def prepare(target, installed, output): raise ValueError('Invalid offline baseline') records = compact_db(body) base = packages(''.join(f'{p}={r["V"]}\n' for p, r in records.items()).encode(), tag) - target_packages = packages(installed.read_bytes(), target) roots = roots_for(records, target_packages) if not any(x.startswith('nanokvm-release=') for x in roots): raise ValueError('Missing target release package in delta') - output.mkdir() (output / 'world').write_bytes(world + b'\n') (output / 'installed').write_text(db_text(records)) - (output / 'base-version').write_text(base['nanokvm-release'] + '\n') (output / 'roots').write_text('\n'.join(roots) + '\n') print(f'{tag} -> {target}: {len(roots)} changed NanoKVM packages') + return base['nanokvm-release'] ACTION = re.compile(r'^\(\s*\d+/\s*\d+\) (Installing|Upgrading) ([^ ]+) \(([^()]*)\)$') @@ -208,17 +220,31 @@ def index_record(package): return record +def plan(directory): + union = set() + for base in (directory / 'bases').iterdir(): + changed = plan_changes(base / 'plan') + coordinates = {f'{p}={v}' for p, v in changed.items()} + roots = set((base / 'roots').read_text().splitlines()) + if not roots <= coordinates: + raise ValueError(f'Changes missing from APK plan: {sorted(roots - coordinates)}') + union.update(coordinates) + (directory / 'fetch').write_text(''.join(x + '\n' for x in sorted(union))) + + def finish(directory): - baseline = compact_db((directory/'installed').read_bytes()) - changes = plan_changes(directory/'plan') index = [index_record(p) for p in json.loads((directory/'selected.json').read_text())['packages']] - if changes != plan_changes(directory / 'offline-plan'): - raise ValueError('Offline APK upgrade differs from the dependency plan') - if {p['P']: p['V'] for p in index} != changes: - raise ValueError('APK files differ from the planned transaction') - for record in index: - baseline[record['P']] = {k: v for k, v in record.items() if k in FIELDS} - (directory/'installed-db').write_bytes(encode_state((directory/'world').read_text(), baseline)) + records = {(r['P'], r['V']): r for r in index} + if {f'{p}={v}' for p, v in records} != set((directory/'fetch').read_text().splitlines()): + raise ValueError('APK files differ from the planned package union') + for base in (directory / 'bases').iterdir(): + if plan_changes(base/'plan') != plan_changes(base/'offline-plan'): + raise ValueError(f'Offline APK upgrade differs from the dependency plan for {base.name}') + floor = directory / 'bases' / '0' + baseline = compact_db((floor/'installed').read_bytes()) + for name, version in plan_changes(floor/'offline-plan').items(): + baseline[name] = records[name, version] + (directory/'installed-db').write_bytes(encode_state((floor/'world').read_text(), baseline)) if __name__ == '__main__': @@ -234,11 +260,6 @@ def finish(directory): if args.cmd == 'prepare': prepare(args.target, args.installed, args.output) elif args.cmd == 'plan': - changed = plan_changes(args.directory/'plan') - coordinates = {f'{p}={v}' for p, v in changed.items()} - roots = set((args.directory / 'roots').read_text().splitlines()) - if not roots <= coordinates: - raise ValueError(f'Changes missing from APK plan: {sorted(roots - coordinates)}') - (args.directory / 'fetch').write_text(''.join(x + '\n' for x in sorted(coordinates))) + plan(args.directory) else: finish(args.directory) diff --git a/scripts/sign-release.sh b/scripts/sign-release.sh index f158539bc..97d600d1b 100755 --- a/scripts/sign-release.sh +++ b/scripts/sign-release.sh @@ -127,17 +127,21 @@ if [ -d "$w/delta" ]; then as_root install -m 0644 "$repo/firmware/alpine/etc/apk/repositories.d/nanokvm-addons.list" "$root/work/addons.list" as_root install -m 0755 "$here/build-offline-repository.sh" "$root/work/build-offline-repository.sh" signer /bin/sh /work/build-offline-repository.sh plan - as_root cat "$root/work/delta/plan" > "$w/delta/plan" + for base in "$w/delta/bases"/*; do + as_root cat "$root/work/delta/bases/${base##*/}/plan" > "$base/plan" + done python3 "$here/offline_delta.py" plan "$w/delta" as_root install -m 0644 "$w/delta/fetch" "$root/work/delta/fetch" signer /bin/sh /work/build-offline-repository.sh fetch "$version" - as_root cat "$root/work/delta/offline-plan" > "$w/delta/offline-plan" + for base in "$w/delta/bases"/*; do + as_root cat "$root/work/delta/bases/${base##*/}/offline-plan" > "$base/offline-plan" + done as_root cat "$root/work/delta/selected.json" > "$w/delta/selected.json" python3 "$here/offline_delta.py" finish "$w/delta" as_root install -m 0644 "$w/delta/installed-db" "$root/work/offline/installed-db" ( cd "$root/work/offline" - printf '%s\n' Packages.adb base-version installed-db *.apk | sort > "$w/files" + printf '%s\n' Packages.adb minimum-version installed-db *.apk | sort > "$w/files" xargs -a "$w/files" sha256sum -- > "$w/SHA256SUMS" openssl dgst -sha256 -sign "$eckey" -out "$w/SHA256SUMS.sig" "$w/SHA256SUMS" bundle=$out/release/NanoKVM-OS-$version-offline.tar diff --git a/server-cpp/src/osupdate/internal.hpp b/server-cpp/src/osupdate/internal.hpp index 347ed4fe8..e7939562b 100644 --- a/server-cpp/src/osupdate/internal.hpp +++ b/server-cpp/src/osupdate/internal.hpp @@ -23,7 +23,7 @@ inline constexpr auto check_timeout = std::chrono::seconds(130); Error write_repositories(const std::string &data); Error save_notice(const UpdateNotice &n); Error run_offline(); -Error offline_eligibility(const std::string &installed, const std::string &base_version, const std::string &target, const ChannelStatus &channel); +Error offline_eligibility(const std::string &installed, const std::string &minimum, const std::string &target, const ChannelStatus &channel); Error save_apk_status_idle(); Error save_apk_status(const ApkStatus &s); Error remove_rollback_recovery(); diff --git a/server-cpp/src/osupdate/offline.cpp b/server-cpp/src/osupdate/offline.cpp index 9c6593293..a53bb8ea8 100644 --- a/server-cpp/src/osupdate/offline.cpp +++ b/server-cpp/src/osupdate/offline.cpp @@ -103,9 +103,9 @@ Error extract_repository(const fs::path &bundle, const fs::path &repo, const fs: dest.resize(length); if (!in.read(dest.data(), dest.size())) return "truncated offline signature files"; } else { - if (name == "base-version" && length > 128) return "invalid offline base version"; + if (name == "minimum-version" && length > 128) return "invalid offline minimum version"; if (name == "installed-db" && length > 256 * 1024) return "offline package inventory too large"; - if (name != "Packages.adb" && name != "base-version" && name != "installed-db") { + if (name != "Packages.adb" && name != "minimum-version" && name != "installed-db") { std::string package, version; if (!name.ends_with(".apk") || !detail::apk_package_version(name.substr(0, name.size() - 4), package, version) || !valid_package_name(package)) @@ -138,7 +138,7 @@ Error extract_repository(const fs::path &bundle, const fs::path &repo, const fs: auto padding = (512 - length % 512) % 512; if (!in.read(buf.data(), padding) || !zero({buf.data(), static_cast(padding)})) return "invalid offline archive padding"; } - if (!ended || !hashes.contains("Packages.adb") || !hashes.contains("base-version") || + if (!ended || !hashes.contains("Packages.adb") || !hashes.contains("minimum-version") || !hashes.contains("installed-db") || release.empty()) return "incomplete offline release"; std::string expected; for (const auto &[name, hash] : hashes) expected += hash + " " + name + "\n"; @@ -146,8 +146,20 @@ Error extract_repository(const fs::path &bundle, const fs::path &repo, const fs: return {}; } -Error validate_plan(const std::string &plan, const std::string &from, const std::string &to, std::vector &packages) +bool stable_os_version(std::string_view version) { + for (const std::string_view separator : {".", ".", "-r"}) { + const auto n = version.find_first_not_of("0123456789"); + if (!n || n == version.npos || !version.substr(n).starts_with(separator)) return false; + version.remove_prefix(n + separator.size()); + } + return !version.empty() && version.find_first_not_of("0123456789") == version.npos; +} + +Error validate_plan(const std::string &plan, const std::map &installed, + const std::map &expected, const std::string &to, std::vector &packages) +{ + auto projected = installed; bool updates_release = false; for (const auto &line : gostr::split(plan, "\n")) { std::string action, name, change; @@ -158,21 +170,35 @@ Error validate_plan(const std::string &plan, const std::string &from, const std: if (action != "Upgrading" && action != "Installing" && action != "Reinstalling" && action != "Updating pinning") return "offline update would " + action + " " + name + "; inspect installed packages before updating"; packages.push_back(name); - if (name == "nanokvm-release" && action == "Upgrading" && change == from + " -> " + to) updates_release = true; + if (action == "Installing") projected[name] = change; + if (action == "Upgrading") { + const auto arrow = change.find(" -> "); + if (arrow == change.npos) return "invalid offline APK upgrade plan"; + projected[name] = change.substr(arrow + 4); + if (name == "nanokvm-release" && projected[name] == to) updates_release = true; + } + } + if (!updates_release) return "installed package selections prevent this offline release from being applied"; + for (const auto &[name, version] : expected) { + if (name != "nanokvm" && !name.starts_with("nanokvm-")) continue; + auto it = projected.find(name); + if (it != projected.end() && compare_apk_versions(it->second, version) < 0) + return "offline update requires " + name + " " + version + " but the package plan keeps " + it->second; } - return updates_release ? Error{} : "installed package selections prevent this offline release from being applied"; + return {}; } } // namespace -Error offline_eligibility(const std::string &installed, const std::string &base_version, const std::string &target, const ChannelStatus &channel) +Error offline_eligibility(const std::string &installed, const std::string &minimum, const std::string &target, const ChannelStatus &channel) { - if (!detail::apk_bare_version(base_version)) return "invalid offline base version"; - if (!installed.starts_with("5.") || !target.starts_with("5.")) return "offline updates require an installed 5.x system and a 5.x release"; - if (installed != base_version) return "this offline update requires nanokvm-release " + base_version + "; installed: " + installed; - if (compare_apk_versions(target, installed) <= 0) return "the offline release must be newer than the installed release"; - if (!channel.offline_available() || prerelease(installed) || prerelease(target)) + if (!channel.offline_available() || !stable_os_version(installed) || !stable_os_version(target)) return "Offline updates require Stable releases on the Stable channel"; + if (!stable_os_version(minimum) || compare_apk_versions(minimum, "5.0.0-r0") < 0 || + compare_apk_versions(minimum, target) >= 0) return "invalid offline minimum version"; + if (compare_apk_versions(installed, minimum) < 0) + return "This offline update requires NanoKVM OS " + minimum + " or newer; installed: " + installed; + if (compare_apk_versions(installed, target) >= 0) return "the offline release must be newer than the installed release"; return {}; } @@ -190,10 +216,10 @@ Error run_offline() auto versions = installed_versions(e); if (!versions) return e; auto current = versions->find("nanokvm-release"); - auto base_version = files::read((repo / "base-version").string()); - if (!base_version || !base_version->ends_with('\n')) return "invalid offline base version"; - base_version->pop_back(); - if (auto err = offline_eligibility(current == versions->end() ? "" : current->second, *base_version, target, get_channel()); !err.empty()) + auto minimum = files::read((repo / "minimum-version").string()); + if (!minimum || !minimum->ends_with('\n')) return "invalid offline minimum version"; + minimum->pop_back(); + if (auto err = offline_eligibility(current == versions->end() ? "" : current->second, *minimum, target, get_channel()); !err.empty()) return err; apkrun::Cmd cmd; @@ -209,7 +235,10 @@ Error run_offline() auto plan = apkrun::output_split(cmd); if (!plan.ok) return "offline APK dependency check failed: " + gostr::trim_space(plan.stderr_output); std::vector packages; - if (auto err = validate_plan(plan.output, current->second, target, packages); !err.empty()) return err; + const auto expected = parse_installed_db(files::read((repo / "installed-db").string()).value_or("")); + auto release = expected.find("nanokvm-release"); + if (release == expected.end() || release->second != target) return "offline target package inventory mismatch"; + if (auto err = validate_plan(plan.output, *versions, expected, target, packages); !err.empty()) return err; // Bound peak storage conservatively: allow all selected new files and 16 MiB for // package metadata, before relying on space freed by replacing an older file. diff --git a/server-cpp/tests/osupdate_test.cpp b/server-cpp/tests/osupdate_test.cpp index 513b0a2fc..f3dd12856 100644 --- a/server-cpp/tests/osupdate_test.cpp +++ b/server-cpp/tests/osupdate_test.cpp @@ -41,16 +41,19 @@ int main() } const ChannelStatus stable_channel{"stable", true}, beta_channel{"beta", true}; CHECK(offline_eligibility("5.0.1-r0", "5.0.1-r0", "5.0.2-r0", stable_channel).empty()); + for (const auto &from : {"5.3.0-r0", "5.3.0-r1", "5.4.0-r0", "5.10.0-r0"}) + CHECK(offline_eligibility(from, "5.3.0-r0", "6.0.0-r0", stable_channel).empty(), from); for (const auto &[installed, base, to, selected] : std::vector>{ {"5.0.1-r0", "5.0.1-r0", "5.0.2_beta1-r0", beta_channel}, {"5.0.1-r0", "5.0.1-r0", "5.0.2-r0", beta_channel}, {"5.1.0_beta-r0", "5.1.0_beta-r0", "5.1.0-r0", stable_channel}, {"5.0.1-r0", "5.0.1-r0", "5.0.2-r0", {"stable", true, true}}, - {"5.0.1-r1", "5.0.1-r0", "5.0.2-r0", stable_channel}, + {"5.1.2-r0", "5.3.0-r0", "6.0.0-r0", stable_channel}, {"5.0.1-r0", "5.0.1-r0", "5.0.1-r0", stable_channel}, {"5.1.0-r0", "5.1.0-r0", "5.0.9-r0", stable_channel}, {"4.3.2-r0", "4.3.2-r0", "5.0.2-r0", stable_channel}, - {"5.0.1-r0", "5.0.1-r0", "6.0.0-r0", stable_channel}, + {"6.0.0-r0", "5.3.0-r0", "6.0.0-r0", stable_channel}, + {"6.1.0-r0", "5.3.0-r0", "6.0.0-r0", stable_channel}, {"5.0.1-r0", "5.0.1-r0", "5.0.2_beta1-r0", stable_channel}, {"5.0.1-r0", "5.0.1-r0", "5.0.2-r0", {}}}) CHECK(!offline_eligibility(installed, base, to, selected).empty(), to); diff --git a/tests/test-offline-delta.py b/tests/test-offline-delta.py index be9dbbd55..95b14689e 100644 --- a/tests/test-offline-delta.py +++ b/tests/test-offline-delta.py @@ -16,12 +16,19 @@ def release(tag, *, draft=False): # Pages-only v5.0.2 has no public release. v5.0.3 must work from v5.0.1. releases = [release('v4.3.2'), release('v5.0.1'), release('v5.0.3-beta'), release('v5.0.3', draft=True)] -assert delta.previous_public(releases, 'v5.0.3')['tag_name'] == 'v5.0.1' -assert delta.previous_public(releases, 'v5.0.3-beta.1') is None -assert delta.previous_public(releases, 'v5.0.4-beta') is None -assert delta.previous_public([release('v5.0.0-beta')], 'v5.0.0') is None -assert delta.previous_public([*releases, release('v5.0.3')], 'v5.0.4')['tag_name'] == 'v5.0.3' -assert delta.previous_public(releases, 'v5.0.0') is None +assert [r['tag_name'] for r in delta.supported_bases(releases, 'v5.0.3')] == ['v5.0.1'] +assert not delta.supported_bases(releases, 'v5.0.3-beta.1') +assert not delta.supported_bases(releases, 'v5.0.0') +releases += [release(t) for t in ('v5.1.2', 'v5.4.0', 'v5.3.0', 'v5.4.1-beta')] +assert [r['tag_name'] for r in delta.supported_bases(releases, 'v6.0.0', 'v5.3.0')] == ['v5.3.0', 'v5.4.0'] +for invalid in ('v4.3.2', 'v5.4.1-beta', 'v5.9.9', 'v6.0.0'): + try: + delta.supported_bases(releases, 'v6.0.0', invalid) + except ValueError: + pass + else: + raise AssertionError(f'accepted invalid minimum: {invalid}') + with tempfile.TemporaryDirectory() as directory: work = Path(directory) From dc71149d498cf260ff087d3f61eb56b662f67c4a Mon Sep 17 00:00:00 2001 From: Gleb Pesin Date: Wed, 2 Dec 2026 19:50:49 +0200 Subject: [PATCH 4/4] Preserve all supported APK states across offline updates --- docs/RELEASE-NAMING.md | 5 +- scripts/offline_delta.py | 92 +++++++++++++++++++---------- scripts/sign-release.sh | 5 +- server-cpp/src/osupdate/offline.cpp | 8 ++- 4 files changed, 73 insertions(+), 37 deletions(-) diff --git a/docs/RELEASE-NAMING.md b/docs/RELEASE-NAMING.md index 1c8bd20e7..c3c0c2fff 100644 --- a/docs/RELEASE-NAMING.md +++ b/docs/RELEASE-NAMING.md @@ -28,7 +28,10 @@ wider range, add an entry such as `"v6.0.0": "v5.3.0"` to must be a published stable release from 5.x or later. With no eligible baseline the build skips the archive. Build-time APK simulations cover every public stable baseline in the range, and the device checks its own installed packages before -applying the update. The signed `installed-db` records the resulting package state. +applying the update. The signed `installed-db` lists the target NanoKVM component versions. Numbered +`installed-db.N` files preserve each distinct resulting APK world and package +inventory so later releases can plan for every supported upgrade path. When a +release also shipped an SD image, its stock inventory is another baseline. Beta releases and Pages-only OTA publications omit this download. Releases that include an SD image also include the diff --git a/scripts/offline_delta.py b/scripts/offline_delta.py index c5a50023a..1a2402d5a 100644 --- a/scripts/offline_delta.py +++ b/scripts/offline_delta.py @@ -15,6 +15,7 @@ from release_assets import OS_TAG RECORD = re.compile(r'([a-z0-9][a-z0-9+_.-]*)=([0-9][A-Za-z0-9+_.~-]*)') +STATE_FILE = re.compile(r'installed-db[.](?:0|[1-9][0-9]*)') MAX_BUNDLE = 256 * 1024 * 1024 MAX_STATE = 256 * 1024 KEYS = Path(__file__).resolve().parents[1] / 'firmware/alpine/keys' @@ -52,7 +53,7 @@ def supported_bases(releases, target, minimum=None): raise ValueError(f'{target}: minimum {minimum!r} must be an earlier published Stable release (5.x or newer)') -def signed_state(release, filename, work): +def signed_states(release, filename, work): asset = next(x for x in release['assets'] if x['name'] == filename) if not 0 < asset['size'] <= MAX_BUNDLE: raise ValueError('Invalid published offline bundle size') @@ -61,9 +62,10 @@ def signed_state(release, filename, work): with tarfile.open(fileobj=io.BytesIO(data), mode='r:') as archive: files = {} for item in archive: - if item.name not in ('SHA256SUMS', 'SHA256SUMS.sig', 'installed-db'): + if item.name not in ('SHA256SUMS', 'SHA256SUMS.sig', 'installed-db') and not STATE_FILE.fullmatch(item.name): continue - if item.name in files or not item.isreg() or not 0 < item.size <= MAX_STATE: + limit = 1024 * 1024 if item.name == 'SHA256SUMS' else MAX_STATE + if item.name in files or not item.isreg() or not 0 < item.size <= limit: raise ValueError(f'Invalid prior bundle metadata: {item.name!r}') files[item.name] = archive.extractfile(item).read() for name in ('SHA256SUMS', 'SHA256SUMS.sig'): @@ -72,15 +74,25 @@ def signed_state(release, filename, work): work/'SHA256SUMS.sig', work/'SHA256SUMS'], capture_output=True).returncode == 0 for key in KEYS.glob('*-ec-*.pub')): raise ValueError('Prior bundle manifest is not signed by a release key') - data = files['installed-db'] - if a.checksums(files['SHA256SUMS'].decode()).get('installed-db') != hashlib.sha256(data).hexdigest(): - raise ValueError('Prior inventory differs from its signed manifest') - return data + manifest = a.checksums(files['SHA256SUMS'].decode()) + numbered = {name for name in manifest if STATE_FILE.fullmatch(name)} + if numbered != {name for name in files if STATE_FILE.fullmatch(name)}: + raise ValueError('Prior bundle lacks signed solver states') + # Older bundles stored their only solver state directly in installed-db. + names = [f'installed-db.{i}' for i in range(len(numbered))] or ['installed-db'] + states = [] + for name in names: + data = files[name] + if manifest.get(name) != hashlib.sha256(data).hexdigest(): + raise ValueError(f'Prior inventory differs from its signed manifest: {name}') + states.append(data) + return states + # Package and solver fields only. File records, scripts and paths from the # installed database must never become inputs to the signing job. -FIELDS = frozenset('CPVADpikrqSIsf') +FIELDS = 'CPVADpikrqSIsf' def compact_db(data): @@ -99,7 +111,7 @@ def compact_db(data): def db_text(records): - return ''.join(''.join(f'{k}:{v}\n' for k, v in fields.items()) + '\n' + return ''.join(''.join(f'{k}:{fields[k]}\n' for k in FIELDS if k in fields) + '\n' for _, fields in sorted(records.items())) @@ -152,22 +164,33 @@ def prepare(target, installed, output): print(f'{target}: no compatible public baseline; skipping offline delta') return target_packages = packages(installed.read_bytes(), target) - for i, release in enumerate(bases): - directory = output / 'bases' / str(i) - directory.mkdir(parents=True) - base_version = prepare_base(release, target, target_packages, directory) - if i == 0: - (output / 'minimum-version').write_text(base_version + '\n') - - -def prepare_base(previous, target, target_packages, output): - tag = previous['tag_name'] - filename = f'NanoKVM-OS-{tag}-offline.tar' - with tempfile.TemporaryDirectory() as temp: - if any(x['name'] == filename for x in previous['assets']): - state = signed_state(previous, filename, Path(temp)) - else: - state = bootstrap(previous) + output.mkdir() + # Device-side minimum component versions come from the actual target image. + expected = {p: {'P': p, 'V': v} for p, v in target_packages.items() + if p == 'nanokvm' or p.startswith('nanokvm-')} + (output / 'installed-db').write_text(db_text(expected)) + count = 0 + for release in bases: + tag = release['tag_name'] + assets = {item['name'] for item in release['assets']} + filename = f'NanoKVM-OS-{tag}-offline.tar' + states = [] + if filename in assets: + with tempfile.TemporaryDirectory() as temp: + states = signed_states(release, filename, Path(temp)) + # A clean SD image can have different providers from an upgraded system. + if not states or f'nanokvm_{tag[1:]}.tar.gz' in assets: + states.append(bootstrap(release)) + for state in dict.fromkeys(states): + directory = output / 'bases' / str(count) + directory.mkdir(parents=True) + base_version = prepare_base(state, tag, target, target_packages, directory) + if count == 0: + (output / 'minimum-version').write_text(base_version + '\n') + count += 1 + + +def prepare_base(state, tag, target, target_packages, output): world, body = state.split(b'\n\n', 1) if len(state) > MAX_STATE or any(v.startswith(b'-') for v in world.splitlines()): raise ValueError('Invalid offline baseline') @@ -237,14 +260,19 @@ def finish(directory): records = {(r['P'], r['V']): r for r in index} if {f'{p}={v}' for p, v in records} != set((directory/'fetch').read_text().splitlines()): raise ValueError('APK files differ from the planned package union') - for base in (directory / 'bases').iterdir(): - if plan_changes(base/'plan') != plan_changes(base/'offline-plan'): + states = set() + for base in sorted((directory / 'bases').iterdir(), key=lambda path: int(path.name)): + changes = plan_changes(base/'offline-plan') + if plan_changes(base/'plan') != changes: raise ValueError(f'Offline APK upgrade differs from the dependency plan for {base.name}') - floor = directory / 'bases' / '0' - baseline = compact_db((floor/'installed').read_bytes()) - for name, version in plan_changes(floor/'offline-plan').items(): - baseline[name] = records[name, version] - (directory/'installed-db').write_bytes(encode_state((floor/'world').read_text(), baseline)) + baseline = compact_db((base/'installed').read_bytes()) + for name, version in changes.items(): + baseline[name] = records[name, version] + state = encode_state((base/'world').read_text(), baseline) + if state not in states: + (directory / f'installed-db.{len(states)}').write_bytes(state) + states.add(state) + if __name__ == '__main__': diff --git a/scripts/sign-release.sh b/scripts/sign-release.sh index 97d600d1b..ea25936ad 100755 --- a/scripts/sign-release.sh +++ b/scripts/sign-release.sh @@ -138,10 +138,11 @@ if [ -d "$w/delta" ]; then done as_root cat "$root/work/delta/selected.json" > "$w/delta/selected.json" python3 "$here/offline_delta.py" finish "$w/delta" - as_root install -m 0644 "$w/delta/installed-db" "$root/work/offline/installed-db" + as_root install -m 0644 "$w/delta/installed-db" "$w/delta"/installed-db.* "$root/work/offline/" ( cd "$root/work/offline" - printf '%s\n' Packages.adb minimum-version installed-db *.apk | sort > "$w/files" + printf '%s\n' Packages.adb minimum-version installed-db installed-db.* *.apk | sort > "$w/files" + [ "$(wc -l < "$w/files")" -le 4096 ] || { echo "Too many offline repository files" >&2; exit 1; } xargs -a "$w/files" sha256sum -- > "$w/SHA256SUMS" openssl dgst -sha256 -sign "$eckey" -out "$w/SHA256SUMS.sig" "$w/SHA256SUMS" bundle=$out/release/NanoKVM-OS-$version-offline.tar diff --git a/server-cpp/src/osupdate/offline.cpp b/server-cpp/src/osupdate/offline.cpp index a53bb8ea8..9c3b957f8 100644 --- a/server-cpp/src/osupdate/offline.cpp +++ b/server-cpp/src/osupdate/offline.cpp @@ -104,8 +104,12 @@ Error extract_repository(const fs::path &bundle, const fs::path &repo, const fs: if (!in.read(dest.data(), dest.size())) return "truncated offline signature files"; } else { if (name == "minimum-version" && length > 128) return "invalid offline minimum version"; - if (name == "installed-db" && length > 256 * 1024) return "offline package inventory too large"; - if (name != "Packages.adb" && name != "minimum-version" && name != "installed-db") { + constexpr std::string_view state_prefix = "installed-db."; + const bool solver_state = name.starts_with(state_prefix) && name.size() > state_prefix.size() && + name.find_first_not_of("0123456789", state_prefix.size()) == name.npos; + const bool inventory = name == "installed-db" || solver_state; + if (inventory && length > 256 * 1024) return "offline package inventory too large"; + if (name != "Packages.adb" && name != "minimum-version" && !inventory) { std::string package, version; if (!name.ends_with(".apk") || !detail::apk_package_version(name.substr(0, name.size() - 4), package, version) || !valid_package_name(package))