Connect Debian automatic update flag to verified Download releases

This commit is contained in:
Andrei Smaliak 2026-11-01 14:42:56 +01:00
parent 3e209a492b
commit 25ce3be6b9
12 changed files with 703 additions and 14 deletions

View File

@ -0,0 +1,13 @@
# stage_itscreen 1.0.38 — Debian client automatic updates
- Install iomatex-client-updater.service; reuse the existing itsupdater Unix
socket and active_update flag sent by the device is_check_update setting.
- Check the public DOWNLOAD_IOMATEX_APP Debian feed on git.iomatex.com every
15 minutes when enabled. Persist the flag; disabled means no automatic installs.
- Manual check/install reuse the same owner. Validate host, platform, ELF ABI,
size, SHA-256 and embedded version before stopping the client.
- Serialize with Console installation, atomically replace the executable, and
restore the previous binary after failed startup or interrupted installation.
- Keep registration, settings and media. Preserve a newer Download client when
installing an older OS stage. System packages remain managed by Console.
- Client binary remains verified 5.1.55 / 5010055 revision 2.

View File

@ -23,7 +23,7 @@
"version": "1.0.0"
},
"stage_itscreen": {
"version": "1.0.37"
"version": "1.0.38"
},
"stage_reverse_tunnels": {
"version": "1.0.2"

View File

@ -1,7 +1,7 @@
{
"schema_version": 1,
"client_version": "5.1.55",
"stage_version": "1.0.37",
"stage_version": "1.0.38",
"platform": "linux",
"architecture": "arm64",
"source_repository": "https://git.iomatex.com/Development/It-screenClient.git",

View File

@ -519,6 +519,10 @@ install_itscreen_binary() (
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"
)
@ -1568,6 +1572,7 @@ POWER_WAKE
install_x11_session_scripts
install_recovery_assets
install_systemd_unit
bash "$SCRIPT_DIR/updater/install.sh"
enable_managed_services
post_install_self_test
flush_filesystems

View File

@ -21,3 +21,20 @@ 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))

View File

@ -0,0 +1,40 @@
# Debian client updater
One privileged owner implements the existing AppUpdater newline JSON contract
on /tmp/itsupdater. Only root and the itscreen UID can connect. No client
credentials are sent to Download. Endpoint is fixed to the public Debian feed
on git.iomatex.com; redirects and arbitrary download hosts are rejected.
The platform checkbox is_check_update calls Updater.setActiveUpdate(0|1),
which sends set/active_update. The service saves it under
/var/lib/iomatex/client-update/settings.json (default off until configured).
Enabling triggers a check; recurring interval is 900 seconds. Disabling before
installation begins prevents replacement even after a download. Once the client
has been stopped, installation or rollback completes regardless of later changes.
get returns link, period, active_update, installed_version, ready_version,
device_id, state_update and progress_download. download_update checks; update
manually installs even with automatic updates off. quit cannot terminate the
privileged system service. Caller-supplied installed versions are ignored.
Compare native build first, then release_revision for same-version corrections.
If the current binary hash already matches the feed, record provenance without
reinstalling. Candidate must have exact size/hash, ARM64 ELF header and matching
--version output. /userdata stores candidate/rollback files. Replacement uses a
temporary file on the destination filesystem and os.replace. The Console shared
installer lock serializes replacement. A stopped/maintenance client is not started.
Readiness requires the new executable and an X11 client window within 90 seconds.
This is a startup check, not a proof of all media playback. Failed startup restores
the previous binary. An on-disk transaction also restores it after daemon/OS
interruption. The service never reboots the operating system.
Install: bash stage_itscreen/updater/install.sh (also part of stage_itscreen).
Tests: python3 -m unittest discover -s stage_itscreen/updater -p test_client_updater.py
State/diagnostics: status.json, installed.json in /var/lib/iomatex/client-update;
journalctl -u iomatex-client-updater. Existing Console cloud-registration status
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.

View File

@ -0,0 +1,410 @@
#!/usr/bin/env python3
"""Debian Download channel; existing AppUpdater newline-JSON socket contract."""
import fcntl
import grp
import hashlib
import json
import logging
import os
from pathlib import Path
import pwd
import queue
import re
import shutil
import socket
import socketserver
import struct
import subprocess
import tempfile
import threading
import time
import urllib.parse
import urllib.request
FEED = 'https://git.iomatex.com/An-J/DOWNLOAD_IOMATEX_APP/raw/branch/main/edge-client/debian/latest.json'
PREFIX = 'https://git.iomatex.com/An-J/DOWNLOAD_IOMATEX_APP/raw/branch/main/edge-client/debian/releases/'
BINARY = Path('/opt/itscreen/bin/itscreen')
STATE = Path('/var/lib/iomatex/client-update')
CACHE = Path('/userdata/iomatex-client-update')
LOCK = Path('/run/lock/iomatex-installer.lock')
SOCKET = '/tmp/itsupdater'
PERIOD = 900
def sync_directory(path):
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
def write_json(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix('.tmp')
with tmp.open('w') as stream:
json.dump(data, stream)
stream.flush()
os.fsync(stream.fileno())
os.chmod(tmp, 0o600)
os.replace(tmp, path)
sync_directory(path.parent)
def read_json(path):
try:
return json.loads(path.read_text())
except FileNotFoundError:
return {}
def digest(path):
with path.open('rb') as stream:
return hashlib.sha256(stream.read()).hexdigest()
def version_code(version):
if not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', version):
raise ValueError('Invalid client version')
major, minor, patch = map(int, version.split('.'))
if major < 5 or minor >= 100 or patch >= 10000:
raise ValueError('Unsupported client version')
return major * 1000000 + minor * 10000 + patch
def inspect_binary(path):
result = subprocess.run([str(path), '--version'], check=True, capture_output=True,
text=True, timeout=10)
parts = result.stdout.strip().split()
if len(parts) != 2 or int(parts[1]) != version_code(parts[0]):
raise ValueError('Invalid embedded client version')
return parts[0], int(parts[1])
def validate_manifest(data):
if (data.get('schema_version') != 1 or data.get('platform') != 'debian'
or data.get('architecture') != 'arm64' or data.get('artifact_type') != 'elf'
or type(data.get('build_number')) is not int
or data['build_number'] != version_code(data.get('version', ''))):
raise ValueError('Unsupported release manifest')
url = data.get('download_url', '')
parsed = urllib.parse.urlsplit(url)
if (not url.startswith(PREFIX) or parsed.query or parsed.fragment
or not re.fullmatch(re.escape(data['version']) + r'(?:-[A-Za-z0-9._-]+)?/itscreen', url[len(PREFIX):])):
raise ValueError('Untrusted download URL')
if not re.fullmatch(r'[0-9a-f]{64}', data.get('sha256', '')):
raise ValueError('Invalid checksum')
if type(data.get('size_bytes')) is not int or not 100000 <= data['size_bytes'] <= 128*1024*1024:
raise ValueError('Invalid download size')
revision = data.get('release_revision', 1)
if type(revision) is not int or revision < 1:
raise ValueError('Invalid release revision')
return dict(data, release_revision=revision)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise ValueError('Update redirect refused')
def open_url(url):
req = urllib.request.Request(url, headers={'User-Agent': 'IomatexOS-Updater/1.0'})
return urllib.request.build_opener(NoRedirect()).open(req, timeout=30)
class Updater:
def __init__(self, binary=BINARY, state=STATE, cache=CACHE):
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)
self.mutex = threading.RLock()
self.automatic = read_json(self.state/'settings.json').get('active_update', 0) == 1
self.pending = queue.Queue(maxsize=1)
self.listeners = set()
self.phase, self.progress, self.ready = 'init', 0, 0
self.busy = False
self.error = ''
self.device_id = ''
if read_json(self.state/'transaction.json'):
self.version, self.installed = '', 0
else:
self.version, self.installed = inspect_binary(self.binary)
def emit(self, key, value):
for handler in list(self.listeners):
handler.send(key, value)
def status(self, phase, error=''):
self.phase, self.error = phase, error
write_json(self.state/'status.json', {'state_update': phase, 'error': error,
'installed_version': self.installed, 'ready_version': self.ready,
'checked_at': int(time.time())})
self.emit('state_update', phase)
def set_automatic(self, value):
if type(value) is not int or value not in (0, 1):
raise ValueError('active_update must be 0 or 1')
with self.mutex:
self.automatic = bool(value)
write_json(self.state/'settings.json', {'active_update': value})
self.emit('active_update', value)
if value:
self.request(False)
def request(self, manual):
if not self.busy:
try:
self.pending.put_nowait(manual)
except queue.Full:
pass
def values(self):
return {'link': FEED, 'period': PERIOD, 'installed_version': self.installed,
'ready_version': self.ready, 'device_id': self.device_id,
'active_update': int(self.automatic), 'state_update': self.phase,
'progress_download': self.progress}
def newer(self, data):
if data['build_number'] != self.installed:
return data['build_number'] > self.installed
receipt = read_json(self.state/'installed.json')
installed_hash = digest(self.binary)
revision = receipt.get('release_revision', 0) if (
receipt.get('build_number') == self.installed
and receipt.get('sha256') == installed_hash) else 0
return data['release_revision'] > revision and installed_hash != data['sha256']
def download(self, data):
target = self.cache/'candidate'
try:
with open_url(data['download_url']) as response, target.open('wb') as output:
count, checksum = 0, hashlib.sha256()
while True:
block = response.read(256*1024)
if not block:
break
count += len(block)
if count > data['size_bytes']:
raise ValueError('Download exceeds expected size')
output.write(block)
checksum.update(block)
self.progress = int(count * 100 / data['size_bytes'])
self.emit('progress_download', self.progress)
output.flush()
os.fsync(output.fileno())
if count != data['size_bytes'] or checksum.hexdigest() != data['sha256']:
raise ValueError('Download checksum/size mismatch')
with target.open('rb') as stream:
elf = stream.read(20)
if elf[:6] != b'\x7fELF\x02\x01' or elf[18:20] != b'\xb7\x00':
raise ValueError('Downloaded file is not ARM64 ELF')
target.chmod(0o755)
if inspect_binary(target) != (data['version'], data['build_number']):
raise ValueError('Embedded version differs from manifest')
return target
except Exception:
target.unlink(missing_ok=True)
raise
def replace(self, source):
# Candidate and destination can be on different filesystems.
fd, name = tempfile.mkstemp(prefix='.client-update-', dir=self.binary.parent)
try:
with os.fdopen(fd, 'wb') as out, source.open('rb') as inp:
shutil.copyfileobj(inp, out)
out.flush()
os.fsync(out.fileno())
original = self.binary.stat()
os.chown(name, original.st_uid, original.st_gid)
os.chmod(name, 0o755)
os.replace(name, self.binary)
sync_directory(self.binary.parent)
finally:
Path(name).unlink(missing_ok=True)
def service(self, action):
subprocess.run(['systemctl', action, 'itscreen-x11.service'], check=True,
capture_output=True, timeout=90)
def healthy(self):
# Cover the normal X11/Qt startup period and verify this executable is running.
expected = digest(self.binary)
for _ in range(45):
time.sleep(2)
for executable in Path('/proc').glob('[0-9]*/exe'):
try:
if executable.resolve() == self.binary and digest(executable) == expected:
# Require a mapped playback window, not just a surviving launcher.
result = subprocess.run(['runuser', '-u', 'itscreen', '--', 'env',
'DISPLAY=:0', 'XAUTHORITY=/var/lib/itscreen/.Xauthority',
'xwininfo', '-root', '-tree'], capture_output=True, text=True, timeout=5)
if re.search(r'"it-screen".*\s[1-9][0-9]{2,}x[1-9][0-9]{2,}', result.stdout):
return True
except (OSError, subprocess.SubprocessError):
continue
return False
def recover(self):
transaction = read_json(self.state/'transaction.json')
if not transaction:
return
backup = self.cache/'previous'
if digest(backup) != transaction['previous_sha256']:
raise ValueError('Rollback backup checksum mismatch')
self.service('stop')
self.replace(backup)
self.service('start')
(self.state/'transaction.json').unlink()
sync_directory(self.state)
self.version, self.installed = inspect_binary(self.binary)
def install(self, candidate, data, manual):
with LOCK.open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
with self.mutex:
if not manual and not self.automatic:
self.status('not_permitted')
return
self.version, self.installed = inspect_binary(self.binary)
if not self.newer(data):
self.status('not_required')
return
# Do not start a stopped client (e.g. maintenance desktop mode).
if subprocess.run(['systemctl','is-active','--quiet','itscreen-x11']).returncode:
self.status('ready')
return
backup = self.cache/'previous'
shutil.copy2(self.binary, backup)
with backup.open('rb') as stream:
os.fsync(stream.fileno())
sync_directory(backup.parent)
write_json(self.state/'transaction.json', {'previous_sha256': digest(backup)})
self.status('updating')
try:
self.service('stop')
self.replace(candidate)
self.service('start')
if not self.healthy():
raise RuntimeError('Client did not become ready; rolling back')
write_json(self.state/'installed.json', data)
(self.state/'transaction.json').unlink()
sync_directory(self.state)
self.version, self.installed = inspect_binary(self.binary)
self.emit('installed_version', self.installed)
self.status('updated')
except Exception:
self.recover()
raise
def check(self, install=False):
self.busy = True
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))
self.ready = data['build_number']
self.emit('ready_version', self.ready)
self.version, self.installed = inspect_binary(self.binary)
if not self.newer(data):
if data['build_number'] == self.installed and digest(self.binary) == data['sha256']:
write_json(self.state/'installed.json', data)
self.status('not_required')
return
self.status('ready')
if not (install or self.automatic):
return
self.status('downloading')
candidate = self.download(data)
self.install(candidate, data, manual=install)
except Exception as exc:
logging.exception('Client update failed')
self.status('error', str(exc))
finally:
self.busy = False
def worker(self):
while True:
try:
manual_install = self.pending.get(timeout=PERIOD)
self.check(install=manual_install)
except queue.Empty:
if self.automatic:
self.check()
class Handler(socketserver.StreamRequestHandler):
def send(self, key, value):
try:
with self.write_lock:
self.wfile.write((json.dumps({key: value})+'\n').encode())
self.wfile.flush()
except OSError:
pass
def handle(self):
_, uid, _ = struct.unpack('3i', self.request.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
if uid not in (0, pwd.getpwnam('itscreen').pw_uid):
return
self.write_lock = threading.Lock()
updater = self.server.updater
updater.listeners.add(self)
try:
for key, value in updater.values().items():
self.send(key, value)
while True:
line = self.rfile.readline(65537)
if not line or len(line) > 65536:
break
try:
data = json.loads(line)
action, key = data.get('action'), data.get('key')
if action == 'get' and key in updater.values():
self.send(key, updater.values()[key])
elif action == 'set' and key == 'active_update':
updater.set_automatic(data.get('value'))
elif action == 'set' and key == 'device_id':
updater.device_id = str(data.get('value', ''))[:128]
self.send(key, updater.device_id)
elif action == 'set' and key == 'installed_version':
# Executable is version authority; never accept caller's version.
self.send(key, updater.installed)
elif action in ('download_update', 'update'):
updater.request(action == 'update')
elif action == 'quit':
self.send('state_update', updater.phase)
except (ValueError, TypeError, AttributeError):
self.send('state_update', 'error_info')
finally:
updater.listeners.discard(self)
class Server(socketserver.ThreadingUnixStreamServer):
daemon_threads = True
def main():
logging.basicConfig(level=logging.INFO)
STATE.mkdir(parents=True, exist_ok=True)
CACHE.mkdir(parents=True, exist_ok=True)
os.chmod(STATE, 0o700)
os.chmod(CACHE, 0o700)
updater = Updater()
with LOCK.open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
updater.recover()
Path(SOCKET).unlink(missing_ok=True)
with Server(SOCKET, Handler) as server:
server.updater = updater
os.chown(SOCKET, 0, grp.getgrnam('itscreen').gr_gid)
os.chmod(SOCKET, 0o660)
threading.Thread(target=updater.worker, daemon=True).start()
if updater.automatic:
updater.request(False)
server.serve_forever()
if __name__ == '__main__':
main()

View File

@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -euo pipefail
updater_source=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
install -d -m 0755 -o root -g root /usr/local/lib/iomatex/client-updater
install -m 0644 -o root -g root "$updater_source/client_updater.py" /usr/local/lib/iomatex/client-updater/
install -m 0644 -o root -g root "$updater_source/iomatex-client-updater.service" /etc/systemd/system/
install -d -m 0700 -o root -g root /var/lib/iomatex/client-update /userdata/iomatex-client-update
systemctl daemon-reload
systemctl enable iomatex-client-updater.service
# Installer holds the shared lock. Starting asynchronously lets the daemon wait
# for that lock without deadlocking the stage installer.
systemctl restart --no-block iomatex-client-updater.service

View File

@ -0,0 +1,18 @@
[Unit]
Description=EVAx10 Debian client updates from Download
After=network-online.target
Wants=network-online.target
RequiresMountsFor=/userdata /opt/itscreen
[Service]
Type=simple
ExecStart=/usr/bin/python3 /usr/local/lib/iomatex/client-updater/client_updater.py
Restart=on-failure
RestartSec=15
UMask=0077
# QLocalSocket's existing relative itsupdater name resolves in shared /tmp.
PrivateTmp=false
TimeoutStopSec=120
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,160 @@
import io
import json
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
import client_updater as c
def executable(path, version):
path.write_text('#!/bin/sh\necho "'+version+' '+str(c.version_code(version))+'"\n')
path.chmod(0o755)
def manifest():
return {'schema_version':1, 'platform':'debian','architecture':'arm64',
'artifact_type':'elf','version':'5.1.55','build_number':5010055,
'release_revision':2,'size_bytes':100000,'sha256':'a'*64,
'download_url':c.PREFIX+'5.1.55-r2/itscreen'}
class TestUpdater(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.binary = self.root/'itscreen'
executable(self.binary, '5.1.54')
self.u = c.Updater(self.binary,self.root/'state',self.root/'cache')
def test_socket_checkbox_and_fragmented_frames(self):
import os
import socket
import threading
from types import SimpleNamespace
path = str(self.root/'socket')
with patch.object(c.pwd,'getpwnam',return_value=SimpleNamespace(pw_uid=os.getuid())):
with c.Server(path,c.Handler) as server:
server.updater=self.u
thread=threading.Thread(target=server.serve_forever,daemon=True)
thread.start()
try:
with socket.socket(socket.AF_UNIX) as client:
client.settimeout(3);client.connect(path)
stream=client.makefile('rwb',buffering=0)
initial={}
for _ in range(8):initial.update(json.loads(stream.readline()))
self.assertEqual(initial['active_update'],0)
stream.write(b'{"action":"set","key":"active_')
stream.write(b'update","value":1}\n')
self.assertEqual(json.loads(stream.readline()),{'active_update':1})
self.assertTrue(c.Updater(self.binary,self.u.state,self.u.cache).automatic)
stream.write(b'{"action":"set","key":"active_update","value":0}\n')
self.assertEqual(json.loads(stream.readline()),{'active_update':0})
self.assertFalse(c.Updater(self.binary,self.u.state,self.u.cache).automatic)
finally:
server.shutdown();thread.join()
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'),
('download_url','https://git.it-screen.com/a'),
('download_url',c.PREFIX+'ok/itscreen?redirect=x'),
('architecture','x86_64'),('build_number',5010054),
('size_bytes',True),('sha256','bad'),('release_revision',0)]:
with self.subTest(key=key,value=value):
data=manifest();data[key]=value
with self.assertRaises(ValueError): c.validate_manifest(data)
def test_redirect_refused(self):
with self.assertRaises(ValueError):
c.NoRedirect().redirect_request(None,None,302,'',{},'https://git.it-screen.com')
def test_flag_persists_and_does_not_accept_other_values(self):
self.u.set_automatic(1)
self.assertTrue(c.Updater(self.binary,self.u.state,self.u.cache).automatic)
self.u.set_automatic(0)
self.assertFalse(c.Updater(self.binary,self.u.state,self.u.cache).automatic)
for v in [True,2,'1',None]:
with self.assertRaises(ValueError):self.u.set_automatic(v)
def test_check_only_when_off_and_auto_when_on(self):
with patch.object(c,'open_url',return_value=io.BytesIO(json.dumps(manifest()).encode())), patch.object(self.u,'download') as download:
self.u.check()
download.assert_not_called()
self.assertEqual(self.u.phase,'ready')
self.u.automatic=True
with patch.object(c,'open_url',return_value=io.BytesIO(json.dumps(manifest()).encode())), patch.object(self.u,'download',return_value=self.binary), patch.object(self.u,'install') as install:
self.u.check();install.assert_called_once()
def test_no_downgrade_or_repeat_and_revision_correction(self):
data=manifest();self.u.installed=5010056
self.assertFalse(self.u.newer(data))
self.u.installed=5010055
self.assertTrue(self.u.newer(data))
c.write_json(self.u.state/'installed.json',dict(data,sha256=c.digest(self.binary)))
self.assertFalse(self.u.newer(data))
data['release_revision']=3
self.assertTrue(self.u.newer(data))
data['sha256']=c.digest(self.binary)
self.assertFalse(self.u.newer(data))
def test_bad_download_leaves_installed_binary(self):
before=self.binary.read_bytes()
with patch.object(c,'open_url',return_value=io.BytesIO(b'bad')):
with self.assertRaises(ValueError):self.u.download(manifest())
self.assertEqual(self.binary.read_bytes(),before)
self.assertFalse((self.u.cache/'candidate').exists())
def test_verified_elf_and_embedded_version(self):
data=manifest();content=bytearray(data['size_bytes'])
content[:6]=b'\x7fELF\x02\x01';content[18:20]=b'\xb7\x00'
data['sha256']=c.hashlib.sha256(content).hexdigest()
with patch.object(c,'open_url',return_value=io.BytesIO(content)),patch.object(c,'inspect_binary',return_value=('5.1.55',5010055)):
self.assertEqual(self.u.download(data).read_bytes(),content)
with patch.object(c,'open_url',return_value=io.BytesIO(content)),patch.object(c,'inspect_binary',return_value=('5.1.54',5010054)):
with self.assertRaises(ValueError):self.u.download(data)
def test_disabling_after_download_prevents_install(self):
with patch.object(c,'LOCK',self.root/'lock'),patch.object(self.u,'service') as service:
self.u.install(self.binary,manifest(),False)
service.assert_not_called()
self.assertEqual(self.u.phase,'not_permitted')
def perform_install(self, healthy):
candidate=self.root/'candidate';executable(candidate,'5.1.55')
data=manifest();data['sha256']=c.digest(candidate)
run=subprocess.run
def local_run(args,**kwargs):
if args[0]=='systemctl':return subprocess.CompletedProcess(args,0)
return run(args,**kwargs)
with patch.object(c,'LOCK',self.root/'lock'),patch.object(c.subprocess,'run',side_effect=local_run),patch.object(self.u,'service') as service,patch.object(self.u,'healthy',return_value=healthy):
if healthy:self.u.install(candidate,data,True)
else:
with self.assertRaises(RuntimeError):self.u.install(candidate,data,True)
return service.call_args_list
def test_manual_install_when_off(self):
self.perform_install(True)
self.assertEqual(c.inspect_binary(self.binary),('5.1.55',5010055))
self.assertEqual(self.u.phase,'updated')
self.assertFalse((self.u.state/'transaction.json').exists())
def test_failed_health_rolls_back(self):
before=self.binary.read_bytes();self.perform_install(False)
self.assertEqual(self.binary.read_bytes(),before)
self.assertEqual(c.inspect_binary(self.binary),('5.1.54',5010054))
self.assertFalse((self.u.state/'transaction.json').exists())
def test_recovery_after_interruption(self):
backup=self.u.cache/'previous';executable(backup,'5.1.54')
c.write_json(self.u.state/'transaction.json',{'previous_sha256':c.digest(backup)})
executable(self.binary,'5.1.55')
u=c.Updater(self.binary,self.u.state,self.u.cache)
with patch.object(u,'service'):u.recover()
self.assertEqual(c.inspect_binary(self.binary),('5.1.54',5010054))
if __name__=='__main__':unittest.main()

View File

@ -1,21 +1,35 @@
#!/usr/bin/env python3
"""Check the executable itself before installing a client release."""
import json
"""Shared embedded-version check and protection against stage downgrades."""
import subprocess
import sys
from pathlib import Path
from updater.client_updater import inspect_binary, digest, read_json, STATE
def verify(binary, provenance):
with open(provenance, encoding="utf-8") as stream:
metadata = json.load(stream)
expected = f"{metadata['client_version']} {metadata['native_version_code']}"
result = subprocess.run([str(binary), "--version"], capture_output=True,
text=True, timeout=10, check=True)
actual = result.stdout.strip()
metadata = read_json(Path(provenance))
actual = inspect_binary(Path(binary))
expected = (metadata['client_version'], metadata['native_version_code'])
if actual != expected:
raise ValueError(f"Client release mismatch: expected {expected!r}, got {actual!r}")
return actual
raise ValueError(f'Client release mismatch: expected {expected!r}, got {actual!r}')
return f'{actual[0]} {actual[1]}'
if __name__ == "__main__":
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]))

View File

@ -1,3 +1,3 @@
{
"version": "1.0.37"
"version": "1.0.38"
}