Build reproducible GUI renderer verification and safe fleet installer
This commit is contained in:
parent
794a96b5f8
commit
72a11f0870
2 changed files with 407 additions and 3 deletions
194
tools/install-plugin-fleet.py
Normal file
194
tools/install-plugin-fleet.py
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
"""Install only hash-verified CI plugins into an explicitly supplied, verified fleet inventory.
|
||||
|
||||
Default is a read-only plan. This is not a bootstrap installer and never discovers server paths,
|
||||
assigns modules, installs third-party dependencies, or deletes unrelated plugin backends.
|
||||
"""
|
||||
import argparse
|
||||
import datetime
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
|
||||
def digest(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def identity(path):
|
||||
with zipfile.ZipFile(path) as jar:
|
||||
text = jar.read('plugin.yml').decode('utf-8')
|
||||
result = {}
|
||||
for key in ('name', 'version', 'main'):
|
||||
match = re.search(r'^' + key + r':\s*(.+?)\s*$', text, re.M)
|
||||
if not match:
|
||||
raise ValueError(f'{path}: missing plugin {key}')
|
||||
result[key] = match.group(1).strip('"\'')
|
||||
return result
|
||||
|
||||
|
||||
def plan(artifacts, inventory, expected_source):
|
||||
artifacts = Path(artifacts).resolve(strict=True)
|
||||
manifest = json.loads((artifacts / 'release-manifest.json').read_text())
|
||||
if not re.fullmatch(r'[0-9a-f]{40}', expected_source) or manifest.get('sourceCommit') != expected_source:
|
||||
raise ValueError('Release source does not match the explicitly selected commit')
|
||||
allowed_names = {'DuneEss', 'DuneRealms', 'DuneCore', 'DuneLobby', 'DuneNPC', 'DunerealmsGUI', 'DuneTerrain', 'JarvisTranslator', 'DuneMenus'}
|
||||
files, names = {}, set()
|
||||
for entry in manifest['plugins']:
|
||||
name = entry['filename']
|
||||
if Path(name).name != name or not name.endswith('.jar') or name in files:
|
||||
raise ValueError('Unsafe or duplicate artifact filename')
|
||||
path = artifacts / name
|
||||
if path.is_symlink() or digest(path) != entry['sha256']:
|
||||
raise ValueError('Artifact checksum differs: ' + name)
|
||||
actual = identity(path)
|
||||
if any(actual[key] != entry[key] for key in ('name', 'version', 'main')):
|
||||
raise ValueError('Artifact descriptor differs: ' + name)
|
||||
if actual['name'] not in allowed_names or actual['name'].casefold() in names:
|
||||
raise ValueError('Unapproved or duplicate plugin identity: ' + actual['name'])
|
||||
names.add(actual['name'].casefold())
|
||||
files[name] = dict(entry, source=str(path))
|
||||
servers, ids, roots, units = [], set(), set(), set()
|
||||
for server in inventory['servers']:
|
||||
sid, unit = server['id'], server['serviceUnit']
|
||||
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,80}', sid) or sid in ids:
|
||||
raise ValueError('Unsafe or duplicate server identity')
|
||||
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.@:-]*\.service', unit) or unit in units:
|
||||
raise ValueError('Unsafe or duplicate service unit')
|
||||
raw_root = Path(server['root'])
|
||||
if not raw_root.is_absolute() or raw_root.is_symlink():
|
||||
raise ValueError('Server root must be explicit, absolute and not a symlink')
|
||||
root = raw_root.resolve(strict=True)
|
||||
plugins = root / 'plugins'
|
||||
if root in roots or not (root / 'server.properties').is_file() or not plugins.is_dir() or plugins.is_symlink():
|
||||
raise ValueError('Server root/plugins preconditions failed')
|
||||
selected = server['artifacts']
|
||||
if not selected or len(set(selected)) != len(selected) or any(name not in files for name in selected):
|
||||
raise ValueError('Server requires an explicit valid artifact list')
|
||||
wanted = {files[name]['name'].casefold() for name in selected}
|
||||
previous = []
|
||||
existing_identities = set()
|
||||
for old in plugins.glob('*.jar'):
|
||||
if old.is_symlink():
|
||||
raise ValueError('Symlinked plugin requires explicit operator reconciliation')
|
||||
try:
|
||||
old_id = identity(old)['name'].casefold()
|
||||
except (ValueError, KeyError, zipfile.BadZipFile, UnicodeDecodeError):
|
||||
continue
|
||||
existing_identities.add(old_id)
|
||||
if old_id in wanted:
|
||||
previous.append({'filename': old.name, 'sha256': digest(old)})
|
||||
if 'dunemenus' in wanted and not {'jarvistranslator', 'dunerealmsgui', 'mcgui'}.issubset(wanted | existing_identities):
|
||||
raise ValueError('DuneMenus requires preserved JARVIS, DunerealmsGUI and the existing MCGUI runtime')
|
||||
# Never overwrite a differently named plugin that happens to occupy a release filename.
|
||||
old_names = {row['filename'] for row in previous}
|
||||
for name in selected:
|
||||
if (plugins / name).exists() and name not in old_names:
|
||||
raise ValueError('Artifact filename collides with another plugin: ' + name)
|
||||
servers.append({'id': sid, 'root': str(root), 'serviceUnit': unit,
|
||||
'artifacts': [files[name] for name in selected], 'previous': previous})
|
||||
ids.add(sid); roots.add(root); units.add(unit)
|
||||
if not servers:
|
||||
raise ValueError('Explicit fleet inventory is empty')
|
||||
return {'sourceCommit': expected_source, 'servers': servers}
|
||||
|
||||
|
||||
def systemctl(*args):
|
||||
return subprocess.run(['systemctl', *args], text=True, capture_output=True, check=False)
|
||||
|
||||
|
||||
def apply(deployment, backup_root, control=systemctl):
|
||||
backup_root = Path(backup_root).resolve()
|
||||
stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S.%fZ')
|
||||
# Preflight the whole requested inventory before stopping any service.
|
||||
for server in deployment['servers']:
|
||||
loaded = control('show', server['serviceUnit'], '--property=LoadState', '--value')
|
||||
if loaded.returncode or loaded.stdout.strip() != 'loaded':
|
||||
raise RuntimeError('Verified service unit is not loaded: ' + server['serviceUnit'])
|
||||
state = control('show', server['serviceUnit'], '--property=ActiveState', '--value')
|
||||
if state.returncode or state.stdout.strip() not in ('active', 'inactive', 'failed'):
|
||||
raise RuntimeError('Service is in transition or its state cannot be verified')
|
||||
for entry in server['artifacts']:
|
||||
if digest(entry['source']) != entry['sha256']:
|
||||
raise ValueError('Artifact changed after planning')
|
||||
for old in server['previous']:
|
||||
if digest(Path(server['root']) / 'plugins' / old['filename']) != old['sha256']:
|
||||
raise ValueError('Installed plugin changed after planning')
|
||||
receipts = []
|
||||
for server in deployment['servers']:
|
||||
unit = server['serviceUnit']; plugins = Path(server['root']) / 'plugins'
|
||||
backup = backup_root / stamp / server['id']; backup.mkdir(parents=True, exist_ok=False)
|
||||
receipt = {'sourceCommit': deployment['sourceCommit'], 'server': server, 'status': 'backed-up'}
|
||||
for old in server['previous']:
|
||||
shutil.copy2(plugins / old['filename'], backup / old['filename'])
|
||||
if digest(backup / old['filename']) != old['sha256']:
|
||||
raise RuntimeError('Backup verification failed')
|
||||
record = backup / 'receipt.json'; record.write_text(json.dumps(receipt, indent=2))
|
||||
active = control('is-active', '--quiet', unit).returncode == 0
|
||||
installed = []
|
||||
try:
|
||||
if active and control('stop', unit).returncode:
|
||||
raise RuntimeError('Could not stop ' + unit)
|
||||
stopped = control('show', unit, '--property=ActiveState', '--value')
|
||||
if stopped.returncode or stopped.stdout.strip() not in ('inactive', 'failed'):
|
||||
raise RuntimeError('Refusing to replace plugins unless the service is fully stopped')
|
||||
for entry in server['artifacts']:
|
||||
fd, temporary = tempfile.mkstemp(prefix='.dune-ci-', suffix='.tmp', dir=plugins)
|
||||
import os
|
||||
os.close(fd)
|
||||
temporary = Path(temporary)
|
||||
try:
|
||||
shutil.copy2(entry['source'], temporary)
|
||||
if digest(temporary) != entry['sha256']:
|
||||
raise RuntimeError('Staged checksum differs')
|
||||
temporary.replace(plugins / entry['filename']); installed.append(entry['filename'])
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
for old in server['previous']:
|
||||
if old['filename'] not in installed:
|
||||
(plugins / old['filename']).unlink()
|
||||
if active and (control('start', unit).returncode or control('is-active', '--quiet', unit).returncode):
|
||||
raise RuntimeError('Service did not become active after installation')
|
||||
receipt['status'] = 'installed-service-active' if active else 'installed-service-left-stopped'
|
||||
except Exception as error:
|
||||
# Stop before restoring. Never mutate JARs while a service is active.
|
||||
stopped = control('show', unit, '--property=ActiveState', '--value')
|
||||
if stopped.returncode or stopped.stdout.strip() not in ('inactive', 'failed'):
|
||||
control('stop', unit)
|
||||
stopped = control('show', unit, '--property=ActiveState', '--value')
|
||||
if stopped.returncode or stopped.stdout.strip() not in ('inactive', 'failed'):
|
||||
receipt.update(status='rollback-blocked-service-active', error=str(error))
|
||||
record.write_text(json.dumps(receipt, indent=2)); raise
|
||||
for name in installed:
|
||||
(plugins / name).unlink(missing_ok=True)
|
||||
for old in server['previous']:
|
||||
shutil.copy2(backup / old['filename'], plugins / old['filename'])
|
||||
restarted = not active or control('start', unit).returncode == 0
|
||||
receipt.update(status='rolled-back', error=str(error), rollbackStartAccepted=restarted)
|
||||
record.write_text(json.dumps(receipt, indent=2)); raise
|
||||
record.write_text(json.dumps(receipt, indent=2)); receipts.append(str(record))
|
||||
return receipts
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--artifacts', required=True)
|
||||
parser.add_argument('--inventory', required=True)
|
||||
parser.add_argument('--expected-source', required=True)
|
||||
parser.add_argument('--apply', action='store_true')
|
||||
parser.add_argument('--backup-root')
|
||||
args = parser.parse_args()
|
||||
deployment = plan(args.artifacts, json.loads(Path(args.inventory).read_text()), args.expected_source)
|
||||
if not args.apply:
|
||||
print(json.dumps(deployment, indent=2)); return
|
||||
if not args.backup_root:
|
||||
parser.error('--backup-root is required when applying')
|
||||
print(json.dumps({'receipts': apply(deployment, args.backup_root)}, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
128
tools/test_plugin_fleet_install.py
Normal file
128
tools/test_plugin_fleet_install.py
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
import zipfile
|
||||
|
||||
spec = importlib.util.spec_from_file_location('installer', Path(__file__).with_name('install-plugin-fleet.py'))
|
||||
installer = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(installer)
|
||||
SOURCE = 'a' * 40
|
||||
|
||||
|
||||
def jar(path, name, version='1'):
|
||||
with zipfile.ZipFile(path, 'w') as archive:
|
||||
archive.writestr('plugin.yml', f'name: {name}\nversion: {version}\nmain: example.Main\n')
|
||||
|
||||
|
||||
class Service:
|
||||
def __init__(self, active=True, fail_start=False):
|
||||
self.active, self.fail_start, self.calls = active, fail_start, []
|
||||
|
||||
def __call__(self, *args):
|
||||
self.calls.append(args)
|
||||
status, text = 0, ''
|
||||
if args[0] == 'show':
|
||||
text = ('active\n' if self.active else 'inactive\n') if '--property=ActiveState' in args else 'loaded\n'
|
||||
elif args[0] == 'is-active':
|
||||
status = 0 if self.active else 3
|
||||
elif args[0] == 'stop':
|
||||
self.active = False
|
||||
elif args[0] == 'start':
|
||||
if self.fail_start:
|
||||
self.fail_start = False; status = 1
|
||||
else:
|
||||
self.active = True
|
||||
return subprocess.CompletedProcess(args, status, stdout=text, stderr='')
|
||||
|
||||
|
||||
class FleetInstallerTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
|
||||
self.base = Path(self.temp.name); self.artifacts = self.base / 'artifacts'; self.artifacts.mkdir()
|
||||
self.root = self.base / 'game'; self.root.mkdir(); (self.root / 'server.properties').write_text('')
|
||||
self.plugins = self.root / 'plugins'; self.plugins.mkdir()
|
||||
jar(self.artifacts / 'DunerealmsGUI.jar', 'DunerealmsGUI', '2')
|
||||
jar(self.plugins / 'legacy-gui.jar', 'DunerealmsGUI', '1')
|
||||
jar(self.plugins / 'DuneNPC.jar', 'DuneNPC')
|
||||
jar(self.plugins / 'MCGUI.jar', 'MCGUI')
|
||||
self.inventory = {'servers': [{'id': 'test', 'root': str(self.root.resolve()), 'serviceUnit': 'test-game.service', 'artifacts': ['DunerealmsGUI.jar']}]}
|
||||
entry = dict(installer.identity(self.artifacts / 'DunerealmsGUI.jar'), filename='DunerealmsGUI.jar', sha256=installer.digest(self.artifacts / 'DunerealmsGUI.jar'))
|
||||
(self.artifacts / 'release-manifest.json').write_text(json.dumps({'sourceCommit': SOURCE, 'plugins': [entry]}))
|
||||
|
||||
def deployment(self):
|
||||
return installer.plan(self.artifacts, self.inventory, SOURCE)
|
||||
|
||||
def test_planning_is_read_only_and_requires_exact_source_and_hash(self):
|
||||
before = {p.name: p.read_bytes() for p in self.plugins.iterdir()}
|
||||
self.deployment()
|
||||
self.assertEqual(before, {p.name: p.read_bytes() for p in self.plugins.iterdir()})
|
||||
with self.assertRaises(ValueError):
|
||||
installer.plan(self.artifacts, self.inventory, 'b' * 40)
|
||||
with (self.artifacts / 'DunerealmsGUI.jar').open('ab') as stream:
|
||||
stream.write(b'tampered')
|
||||
with self.assertRaises(ValueError):
|
||||
self.deployment()
|
||||
|
||||
def test_replaces_by_identity_and_preserves_backend_and_third_party(self):
|
||||
preserved = {n: (self.plugins / n).read_bytes() for n in ('DuneNPC.jar', 'MCGUI.jar')}
|
||||
service = Service()
|
||||
receipts = installer.apply(self.deployment(), self.base / 'backups', service)
|
||||
self.assertFalse((self.plugins / 'legacy-gui.jar').exists())
|
||||
self.assertEqual(installer.identity(self.plugins / 'DunerealmsGUI.jar')['version'], '2')
|
||||
for name, value in preserved.items():
|
||||
self.assertEqual((self.plugins / name).read_bytes(), value)
|
||||
self.assertTrue(service.active)
|
||||
self.assertEqual(json.loads(Path(receipts[0]).read_text())['status'], 'installed-service-active')
|
||||
self.assertTrue((Path(receipts[0]).parent / 'legacy-gui.jar').is_file())
|
||||
|
||||
def test_failed_start_restores_original_bytes_and_filename(self):
|
||||
before = {p.name: p.read_bytes() for p in self.plugins.iterdir()}
|
||||
service = Service(fail_start=True)
|
||||
with self.assertRaises(RuntimeError):
|
||||
installer.apply(self.deployment(), self.base / 'backups', service)
|
||||
self.assertEqual(before, {p.name: p.read_bytes() for p in self.plugins.iterdir()})
|
||||
self.assertTrue(service.active)
|
||||
receipt = next((self.base / 'backups').rglob('receipt.json'))
|
||||
self.assertEqual(json.loads(receipt.read_text())['status'], 'rolled-back')
|
||||
|
||||
def test_stopped_server_stays_stopped(self):
|
||||
service = Service(active=False)
|
||||
installer.apply(self.deployment(), self.base / 'backups', service)
|
||||
self.assertFalse(service.active)
|
||||
self.assertFalse(any(c[0] in ('stop', 'start') for c in service.calls))
|
||||
|
||||
def test_no_invented_module_mapping_or_filename_collision(self):
|
||||
self.inventory['servers'][0]['artifacts'] = []
|
||||
with self.assertRaises(ValueError):
|
||||
self.deployment()
|
||||
self.inventory['servers'][0]['artifacts'] = ['DunerealmsGUI.jar']
|
||||
jar(self.plugins / 'DunerealmsGUI.jar', 'SomeOtherPlugin')
|
||||
with self.assertRaises(ValueError):
|
||||
self.deployment()
|
||||
|
||||
def test_transitional_service_is_rejected_before_any_stop_or_write(self):
|
||||
service = Service()
|
||||
def transitional(*args):
|
||||
if '--property=ActiveState' in args:
|
||||
return subprocess.CompletedProcess(args, 0, stdout='activating\n', stderr='')
|
||||
return service(*args)
|
||||
before = {p.name: p.read_bytes() for p in self.plugins.iterdir()}
|
||||
with self.assertRaises(RuntimeError):
|
||||
installer.apply(self.deployment(), self.base / 'backups', transitional)
|
||||
self.assertEqual(before, {p.name: p.read_bytes() for p in self.plugins.iterdir()})
|
||||
self.assertFalse(any(c[0] == 'stop' for c in service.calls))
|
||||
|
||||
def test_installation_rejects_files_changed_since_plan(self):
|
||||
deployment = self.deployment()
|
||||
(self.plugins / 'legacy-gui.jar').write_bytes(b'changed')
|
||||
service = Service()
|
||||
with self.assertRaises(ValueError):
|
||||
installer.apply(deployment, self.base / 'backups', service)
|
||||
self.assertFalse(any(c[0] == 'stop' for c in service.calls))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Loading…
Reference in a new issue

Staff