diff --git a/docs/releases/stage-itscreen-1.0.39.md b/docs/releases/stage-itscreen-1.0.39.md new file mode 100644 index 0000000..7217992 --- /dev/null +++ b/docs/releases/stage-itscreen-1.0.39.md @@ -0,0 +1,13 @@ +# stage_itscreen 1.0.39 — First installation from Download + +- First provisioning resolves the same public Debian Download manifest as the + automatic updater. OS no longer selects stage_itscreen/itscreen for installation. +- Reuse manifest validation, download, ELF/size/SHA-256/embedded-version checks + and atomic replacement from the existing updater owner. +- Initial provisioning installs a client even when automatic updates are off; + preserve that flag, registration, settings and a newer installed client. +- Download failure aborts provisioning without falling back to an old bundled + executable. Archived files remain available only for legacy URL compatibility. +- Use isolated candidate filenames to avoid collisions with a concurrently + downloading updater; share the inherited Console installer lock. +- Dependencies, Console and service startup remain owned by the OS stages. diff --git a/stage-releases.json b/stage-releases.json index d2a3741..e906070 100644 --- a/stage-releases.json +++ b/stage-releases.json @@ -23,7 +23,7 @@ "version": "1.0.0" }, "stage_itscreen": { - "version": "1.0.38" + "version": "1.0.39" }, "stage_reverse_tunnels": { "version": "1.0.2" diff --git a/stage_itscreen/release-provenance.json b/stage_itscreen/release-provenance.json index 3a0882a..2afcd4c 100644 --- a/stage_itscreen/release-provenance.json +++ b/stage_itscreen/release-provenance.json @@ -1,7 +1,7 @@ { "schema_version": 1, "client_version": "5.1.55", - "stage_version": "1.0.38", + "stage_version": "1.0.39", "platform": "linux", "architecture": "arm64", "source_repository": "https://git.iomatex.com/Development/It-screenClient.git", @@ -12,5 +12,7 @@ "assembly_method": "Clean isolated release build from git archive using iomatex-debian-dev:local; --version and linked libraries verified on Debian 11 ARM64", "native_version_code": 5010055, "release_revision": 2, - "verified_version_output": "5.1.55 5010055" + "verified_version_output": "5.1.55 5010055", + "artifact_role": "legacy archive only; first installation resolves Download manifest", + "installation_feed": "https://git.iomatex.com/An-J/DOWNLOAD_IOMATEX_APP/raw/branch/main/edge-client/debian/latest.json" } diff --git a/stage_itscreen/stage_itscreen_install.sh b/stage_itscreen/stage_itscreen_install.sh index 6de9880..ee58836 100755 --- a/stage_itscreen/stage_itscreen_install.sh +++ b/stage_itscreen/stage_itscreen_install.sh @@ -513,17 +513,9 @@ cleanup_legacy_x11_hacks() { install_itscreen_binary() ( set -e step "Install itscreen binary" - local src - src=$(mktemp /userdata/.iomatex-client.XXXXXX) - trap 'rm -f "$src"' EXIT - python3 "$IOMATEX_PROJECT_ROOT/offline/git_delivery.py" fetch stage_itscreen/itscreen "$src" - chmod 0755 "$src" - python3 "$SCRIPT_DIR/verify_client_release.py" "$src" "$SCRIPT_DIR/release-provenance.json" - if python3 "$SCRIPT_DIR/verify_client_release.py" --keep-installed "$ITS_BINARY" "$SCRIPT_DIR/release-provenance.json"; then - log "Preserving newer client installed from Download" - return 0 - fi - install -m 0755 -o "$ITS_USER" -g "$ITS_GROUP" "$src" "$ITS_BINARY" + # One Download owner for initial provisioning and subsequent automatic updates. + # A failed download aborts the stage; never silently install the bundled legacy ELF. + python3 "$SCRIPT_DIR/updater/client_updater.py" --bootstrap ) install_sudoers() { diff --git a/stage_itscreen/test_verify_client_release.py b/stage_itscreen/test_verify_client_release.py index e364440..00a511d 100644 --- a/stage_itscreen/test_verify_client_release.py +++ b/stage_itscreen/test_verify_client_release.py @@ -21,20 +21,3 @@ class EmbeddedReleaseTest(unittest.TestCase): else: with self.assertRaises(ValueError): verify(binary, manifest) - - def test_stage_preserves_newer_download_release(self): - from verify_client_release import keep_installed - from updater.client_updater import digest - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - binary, metadata, receipt = root/'client', root/'meta.json', root/'receipt.json' - metadata.write_text(json.dumps({'client_version':'5.1.55','native_version_code':5010055,'release_revision':2})) - binary.write_text('#!/bin/sh\necho "5.1.56 5010056"\n');binary.chmod(0o755) - self.assertTrue(keep_installed(binary,metadata,receipt)) - binary.write_text('#!/bin/sh\necho "5.1.55 5010055"\n') - receipt.write_text(json.dumps({'build_number':5010055,'sha256':digest(binary),'release_revision':3})) - self.assertTrue(keep_installed(binary,metadata,receipt)) - receipt.write_text('{}') - self.assertFalse(keep_installed(binary,metadata,receipt)) - binary.write_text('#!/bin/sh\necho "5.1.54 5010054"\n') - self.assertFalse(keep_installed(binary,metadata,receipt)) diff --git a/stage_itscreen/updater/README.md b/stage_itscreen/updater/README.md index 8489337..853ce2f 100644 --- a/stage_itscreen/updater/README.md +++ b/stage_itscreen/updater/README.md @@ -38,3 +38,14 @@ continues to query the running client over its existing MQTT contract. First deployment requires Console stage 1.0.38; subsequent client updates come from Download. OS/Console updates remain separate. Do not publish an artifact without a successful native --version check. Stage version is not client version. + +## Initial provisioning (OS stage 1.0.39+) + +The stage calls this same owner with `--bootstrap` after installing dependencies +and creating the client account/directories. It resolves the public manifest, +downloads/validates the current ELF and atomically installs it, even with automatic +updates off. It records the actual Download provenance in installed.json; a +matching/newer existing client is preserved. The stage retains ownership of +service startup and inherits the shared installer lock into this command. +Failure aborts the stage; no legacy repository binary is substituted. Historical +stage_itscreen/itscreen and provenance are archives only, preserved for old URLs. diff --git a/stage_itscreen/updater/client_updater.py b/stage_itscreen/updater/client_updater.py index 32e0a6f..316d83a 100644 --- a/stage_itscreen/updater/client_updater.py +++ b/stage_itscreen/updater/client_updater.py @@ -14,6 +14,7 @@ import shutil import socket import socketserver import struct +import sys import subprocess import tempfile import threading @@ -113,7 +114,7 @@ def open_url(url): class Updater: - def __init__(self, binary=BINARY, state=STATE, cache=CACHE): + def __init__(self, binary=BINARY, state=STATE, cache=CACHE, bootstrap=False): self.binary, self.state, self.cache = Path(binary), Path(state), Path(cache) self.state.mkdir(parents=True, exist_ok=True) self.cache.mkdir(parents=True, exist_ok=True) @@ -128,7 +129,12 @@ class Updater: if read_json(self.state/'transaction.json'): self.version, self.installed = '', 0 else: - self.version, self.installed = inspect_binary(self.binary) + try: + self.version, self.installed = inspect_binary(self.binary) + except (OSError, ValueError, subprocess.SubprocessError): + if not bootstrap: + raise + self.version, self.installed = '', 0 def emit(self, key, value): for handler in list(self.listeners): @@ -175,7 +181,9 @@ class Updater: return data['release_revision'] > revision and installed_hash != data['sha256'] def download(self, data): - target = self.cache/'candidate' + fd, name = tempfile.mkstemp(prefix='candidate-', dir=self.cache) + os.close(fd) + target = Path(name) try: with open_url(data['download_url']) as response, target.open('wb') as output: count, checksum = 0, hashlib.sha256() @@ -214,7 +222,7 @@ class Updater: shutil.copyfileobj(inp, out) out.flush() os.fsync(out.fileno()) - original = self.binary.stat() + original = self.binary.stat() if self.binary.exists() else self.binary.parent.stat() os.chown(name, original.st_uid, original.st_gid) os.chmod(name, 0o755) os.replace(name, self.binary) @@ -296,15 +304,39 @@ class Updater: self.recover() raise + def manifest(self): + with open_url(FEED) as response: + raw = response.read(65537) + if len(raw) > 65536: + raise ValueError('Manifest too large') + return validate_manifest(json.loads(raw)) + + def bootstrap(self): + """Stage owns the installer lock and service lifecycle, regardless of auto flag.""" + if read_json(self.state/'transaction.json'): + raise RuntimeError('Recover interrupted client update before provisioning') + data = self.manifest() + if self.binary.exists() and not self.newer(data): + if digest(self.binary) == data['sha256']: + write_json(self.state/'installed.json', data) + return {'result': 'preserved', 'version': self.version, + 'build_number': self.installed, 'feed': FEED} + candidate = self.download(data) + try: + self.replace(candidate) + write_json(self.state/'installed.json', data) + return {'result': 'installed', 'version': data['version'], + 'build_number': data['build_number'], 'sha256': data['sha256'], + 'download_url': data['download_url'], 'feed': FEED} + finally: + candidate.unlink(missing_ok=True) + def check(self, install=False): self.busy = True + candidate = None try: self.status('check') - with open_url(FEED) as response: - raw = response.read(65537) - if len(raw) > 65536: - raise ValueError('Manifest too large') - data = validate_manifest(json.loads(raw)) + data = self.manifest() self.ready = data['build_number'] self.emit('ready_version', self.ready) self.version, self.installed = inspect_binary(self.binary) @@ -323,6 +355,8 @@ class Updater: logging.exception('Client update failed') self.status('error', str(exc)) finally: + if candidate is not None: + candidate.unlink(missing_ok=True) self.busy = False def worker(self): @@ -391,6 +425,20 @@ def main(): CACHE.mkdir(parents=True, exist_ok=True) os.chmod(STATE, 0o700) os.chmod(CACHE, 0o700) + if sys.argv[1:] == ['--bootstrap']: + # Nested stages inherit the existing flock file description. Standalone + # invocations acquire the same lock rather than bypassing Console. + inherited = os.environ.get('IOMATEX_INSTALL_LOCK_FD', '') + if inherited.isdigit() and Path('/proc/self/fd/'+inherited).resolve() == LOCK: + fcntl.flock(int(inherited), fcntl.LOCK_EX | fcntl.LOCK_NB) + print(json.dumps(Updater(bootstrap=True).bootstrap())) + else: + with LOCK.open('a') as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + print(json.dumps(Updater(bootstrap=True).bootstrap())) + return + if len(sys.argv) != 1: + raise ValueError('Usage: client_updater.py [--bootstrap]') updater = Updater() with LOCK.open('a') as lock: fcntl.flock(lock, fcntl.LOCK_EX) diff --git a/stage_itscreen/updater/test_client_updater.py b/stage_itscreen/updater/test_client_updater.py index 70e68d2..fc5209d 100644 --- a/stage_itscreen/updater/test_client_updater.py +++ b/stage_itscreen/updater/test_client_updater.py @@ -57,6 +57,53 @@ class TestUpdater(unittest.TestCase): finally: server.shutdown();thread.join() + def test_first_install_from_download_even_with_automatic_off(self): + self.binary.unlink() + u=c.Updater(self.binary,self.u.state,self.u.cache,bootstrap=True) + candidate=self.root/'new';executable(candidate,'5.1.55') + data=manifest();data['sha256']=c.digest(candidate) + with patch.object(u,'manifest',return_value=data),patch.object(u,'download',return_value=candidate): + self.assertEqual(u.bootstrap()['result'],'installed') + self.assertEqual(c.inspect_binary(self.binary),('5.1.55',5010055)) + self.assertFalse(u.automatic) + self.assertEqual(c.read_json(u.state/'installed.json')['sha256'],c.digest(self.binary)) + self.assertFalse(candidate.exists()) + + def test_bootstrap_preserves_newer_and_matching_install(self): + for version in ['5.1.55','5.1.56']: + executable(self.binary,version) + u=c.Updater(self.binary,self.u.state,self.u.cache,bootstrap=True) + data=manifest();data['sha256']=c.digest(self.binary) + with patch.object(u,'manifest',return_value=data),patch.object(u,'download') as download: + self.assertEqual(u.bootstrap()['result'],'preserved') + download.assert_not_called() + self.assertEqual(c.inspect_binary(self.binary)[0],version) + + def test_bootstrap_network_failure_preserves_existing_or_absent_binary(self): + before=self.binary.read_bytes() + with patch.object(self.u,'manifest',side_effect=OSError('offline')): + with self.assertRaises(OSError):self.u.bootstrap() + self.assertEqual(self.binary.read_bytes(),before) + self.binary.unlink() + u=c.Updater(self.binary,self.u.state,self.u.cache,bootstrap=True) + with patch.object(u,'manifest',side_effect=OSError('offline')): + with self.assertRaises(OSError):u.bootstrap() + self.assertFalse(self.binary.exists()) + + def test_bootstrap_rejects_bad_binary_before_replacement(self): + before=self.binary.read_bytes() + with patch.object(self.u,'manifest',return_value=manifest()),patch.object(c,'open_url',return_value=io.BytesIO(b'bad')): + with self.assertRaises(ValueError):self.u.bootstrap() + self.assertEqual(self.binary.read_bytes(),before) + + def test_bootstrap_stage_uses_shared_download_owner(self): + stage=Path(__file__).resolve().parents[1]/'stage_itscreen_install.sh' + if not stage.exists():self.skipTest('source contract runs in full checkout') + source=stage.read_text().split('install_itscreen_binary() (',1)[1].split('\n)',1)[0] + self.assertIn('updater/client_updater.py" --bootstrap',source) + self.assertNotIn('git_delivery.py',source) + self.assertNotIn('verify_client_release.py',source) + def test_manifest_rejects_untrusted_or_wrong_platform(self): self.assertEqual(c.validate_manifest(manifest())['build_number'],5010055) for key,value in [('download_url',c.PREFIX+'../itscreen'), diff --git a/stage_itscreen/verify_client_release.py b/stage_itscreen/verify_client_release.py index 2163175..132dcea 100644 --- a/stage_itscreen/verify_client_release.py +++ b/stage_itscreen/verify_client_release.py @@ -1,9 +1,8 @@ #!/usr/bin/env python3 -"""Shared embedded-version check and protection against stage downgrades.""" -import subprocess +"""Embedded-version check for archived release provenance.""" import sys from pathlib import Path -from updater.client_updater import inspect_binary, digest, read_json, STATE +from updater.client_updater import inspect_binary, read_json def verify(binary, provenance): @@ -15,21 +14,6 @@ def verify(binary, provenance): return f'{actual[0]} {actual[1]}' -def keep_installed(binary, provenance, receipt_path=STATE/'installed.json'): - try: - _, installed = inspect_binary(Path(binary)) - except (OSError, ValueError, subprocess.SubprocessError): - return False # Legacy binaries do not implement --version. - metadata = read_json(Path(provenance)) - if installed != metadata['native_version_code']: - return installed > metadata['native_version_code'] - receipt = read_json(receipt_path) - return (receipt.get('build_number') == installed - and receipt.get('sha256') == digest(Path(binary)) - and receipt.get('release_revision', 1) > metadata.get('release_revision', 1)) - if __name__ == '__main__': - if sys.argv[1] == '--keep-installed': - sys.exit(0 if keep_installed(sys.argv[2], sys.argv[3]) else 1) print(verify(sys.argv[1], sys.argv[2])) diff --git a/stage_itscreen/version.json b/stage_itscreen/version.json index 7133bbd..0b52bbd 100644 --- a/stage_itscreen/version.json +++ b/stage_itscreen/version.json @@ -1,3 +1,3 @@ { - "version": "1.0.38" + "version": "1.0.39" }