plugins/tools/plugin_fleet_rollback.py
unimatrixgit 622f7ab6cd
All checks were successful
DuneChat Build / dunechat (push) Successful in 42s
DuneRealms Plugin CI / plugins (push) Successful in 2m43s
Pin DuneChat cutover to the reviewed remaining servers
2026-12-02 13:41:41 +01:00

106 lines
7.6 KiB
Python

"""Explicit rollback of a verified plugin receipt after application-level readiness failure."""
import datetime
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import stat
import subprocess
def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def metadata(path):
row=Path(path).stat(); return {'uid':row.st_uid,'gid':row.st_gid,'mode':stat.S_IMODE(row.st_mode)}
def restore_metadata(path, values):
Path(path).chmod(values['mode'])
if hasattr(os,'chown'):os.chown(path,values['uid'],values['gid'])
def control(*args): return subprocess.run(['systemctl',*args],capture_output=True,text=True,check=False)
def rollback_receipt(receipt_path, expected_source, apply=False, run=control, legacy_owner=None, legacy_was_active=None):
import plugin_pack_properties as pack_properties
receipt_path=Path(receipt_path).resolve(strict=True); backup=receipt_path.parent
receipt=json.loads(receipt_path.read_text()); server=receipt['server']
if not re.fullmatch('[a-f0-9]{40}',expected_source) or receipt.get('sourceCommit')!=expected_source:
raise ValueError('Rollback source does not match the selected receipt')
raw=Path(server['root']);root=raw.resolve(strict=True);plugins=root/'plugins';unit=server['serviceUnit']
if not raw.is_absolute() or raw.is_symlink() or not plugins.is_dir() or plugins.is_symlink() or not (root/'server.properties').is_file():
raise ValueError('Rollback root is not the explicit existing server')
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.@:-]*\.service',unit):raise ValueError('Invalid receipt service')
was_active=receipt.get('wasActive',legacy_was_active)
if not isinstance(was_active,bool):raise ValueError('Legacy receipt requires explicit original active-state')
previous={}; selected={}
for entry in server['artifacts']:
name=entry['filename']
if not re.fullmatch(r'[A-Za-z0-9_.-]+\.jar',name) or name in selected:raise ValueError('Unsafe receipt artifact')
selected[name]=entry['sha256']
for old in server['previous']:
name=old['filename']
if not re.fullmatch(r'[A-Za-z0-9_.-]+\.jar',name) or name in previous:raise ValueError('Unsafe receipt backup')
saved=backup/name
if not saved.is_file() or saved.is_symlink() or digest(saved)!=old['sha256']:raise ValueError('Rollback backup checksum differs: '+name)
owner=old.get('metadata')
if owner is None:
if legacy_owner is None:raise ValueError('Legacy receipt requires explicitly verified UID:GID')
owner={'uid':legacy_owner[0],'gid':legacy_owner[1],'mode':stat.S_IMODE(saved.stat().st_mode)}
previous[name]=dict(old,metadata=owner)
for name in set(previous)|set(selected):
current=plugins/name
allowed={selected.get(name),previous.get(name,{}).get('sha256')}
if current.is_symlink() or (current.exists() and digest(current) not in allowed):
raise ValueError('Rollback would overwrite later/unexpected plugin bytes: '+name)
configs=server.get('configurations',[])
for entry in configs:
relative=entry['path']
sid = server['id']
reviewed = {'arrakis', 'caladan', 'giedi_prime', 'kaitain', 'sigma_draconis_iv', 'lobby'}
target = Path('/opt/dunerealms/lobby') if sid == 'lobby' else Path('/opt/dunerealms/servers') / sid
private_jarvis = (relative == 'JarvisTranslator/config.yml' and entry.get('transform') == 'enable-dunegroups'
and sid in reviewed and root == target and unit == f'dune-{sid}.service')
private_discord = (relative == 'DiscordSRV/config.yml' and entry.get('transform') == 'enable-modern-discord'
and sid in reviewed and root == target and unit == f'dune-{sid}.service')
if relative not in ('MCGUI/config.yml','DunerealmsGUI/menu-pack.yml') and not (private_jarvis or private_discord):
raise ValueError('Unsafe rollback configuration path')
current=plugins/relative
if current.is_symlink() or current.parent.is_symlink():raise ValueError('Symlinked rollback configuration')
if current.exists() and digest(current) not in (entry['sha256'],entry['previousSha256']):raise ValueError('Configuration changed since deployment')
if entry['previousSha256'] is not None:
saved=backup/'configurations'/relative
if not saved.is_file() or saved.is_symlink() or digest(saved)!=entry['previousSha256']:raise ValueError('Configuration backup differs')
if entry.get('previousMetadata') is None and legacy_owner is None:raise ValueError('Legacy configuration owner requires explicit UID:GID')
restored=all((plugins/name).is_file() and digest(plugins/name)==old['sha256'] and metadata(plugins/name)==old['metadata'] for name,old in previous.items())
restored=restored and all(not (plugins/name).exists() for name in selected if name not in previous)
for item in configs:
target=plugins/item['path'];restored=restored and ((not target.exists()) if item['previousSha256'] is None else (target.is_file() and digest(target)==item['previousSha256']))
if item['previousSha256'] is not None and target.is_file():
expected_metadata=item.get('previousMetadata') or {'uid':legacy_owner[0],'gid':legacy_owner[1],'mode':stat.S_IMODE((backup/'configurations'/item['path']).stat().st_mode)}
restored=restored and metadata(target)==expected_metadata
restored=pack_properties.verify_rollback(root,backup,server.get('serverProperties')) and restored
report={'sourceCommit':expected_source,'server':server['id'],'receipt':str(receipt_path),'applied':False,'alreadyRestored':restored}
if not apply or restored:return report
loaded=run('show',unit,'--property=LoadState','--value')
if loaded.returncode or loaded.stdout.strip()!='loaded':raise RuntimeError('Rollback service is not loaded')
if run('stop',unit).returncode:raise RuntimeError('Could not stop rollback target')
state=run('show',unit,'--property=ActiveState','--value')
if state.returncode or state.stdout.strip() not in ('inactive','failed'):raise RuntimeError('Rollback target is not fully stopped')
for name in selected:
(plugins/name).unlink(missing_ok=True)
for name,old in previous.items():
target=plugins/name;shutil.copy2(backup/name,target);restore_metadata(target,old['metadata'])
if digest(target)!=old['sha256'] or metadata(target)!=old['metadata']:raise RuntimeError('Restored plugin bytes/owner/mode differ')
pack_properties.restore(root,backup,server.get('serverProperties'))
for entry in configs:
target=plugins/entry['path']
if entry['previousSha256'] is None:target.unlink(missing_ok=True)
else:
saved=backup/'configurations'/entry['path'];target.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(saved,target)
owner=entry.get('previousMetadata') or {'uid':legacy_owner[0],'gid':legacy_owner[1],'mode':stat.S_IMODE(saved.stat().st_mode)}
restore_metadata(target,owner)
if digest(target)!=entry['previousSha256'] or metadata(target)!=owner:raise RuntimeError('Restored configuration differs')
if was_active and (run('start',unit).returncode or run('is-active','--quiet',unit).returncode):
raise RuntimeError('Original files restored but service did not become active')
report.update(applied=True,status='restored-service-active' if was_active else 'restored-service-left-stopped',time=datetime.datetime.now(datetime.timezone.utc).isoformat())
output=backup/'rollback-receipt.json';output.write_text(json.dumps(report,indent=2)+'\n');report['report']=str(output)
return report