#!/usr/bin/env python3 """Stage the pinned ARM64 browser under /data; never install packages into AGNOS.""" import fcntl import hashlib import json import os from pathlib import Path import platform import pwd import re import shutil import stat import subprocess import tarfile import tempfile import urllib.request import uuid ROOT = Path('/data/arabesque-firefox') BROWSER_UID = 61234 FORMAT = 1 FLOOR = 6 * 1024**3 DISPLAY_PACKAGE = 'display-xvfb.deb' FREETYPE_PACKAGE = 'graphics-libfreetype6.deb' SUPPORTED_AGNOS = ('19.8.1', '20.2-starpilot.1', '20.2.1', '20.5.1', '20.5.2') PHASES = {'staging', 'copying', 'qualifying', 'activate', 'committed', 'restore-copy', 'restore', 'restored'} def manifest(value): if not isinstance(value, dict): raise ValueError('Unsupported Firefox bundle receipt') value = dict(value) value.setdefault('bundle_revision', 0) value.setdefault('bundle_format', FORMAT) if (set(value) != {'version', 'agnos', 'packages', 'bundle_revision', 'bundle_format'} or type(value['bundle_format']) is not int or value['bundle_format'] != FORMAT or type(value['bundle_revision']) is not int or value['bundle_revision'] < 0 or not isinstance(value['version'], str) or not re.fullmatch(r'\d+\.\d+(?:\.\d+)?esr', value['version']) or value['agnos'] != '19.8.1' or not isinstance(value['packages'], list) or not 1 <= len(value['packages']) <= 64): raise ValueError('Unsupported Firefox bundle receipt') names = set() for package in value['packages']: if not isinstance(package, dict): raise ValueError('Invalid pinned Firefox package') digest = 'sha512' if 'sha512' in package else 'sha256' if (set(package) != {'name', 'url', 'size', digest} or not isinstance(package['name'], str) or not re.fullmatch(r'[a-zA-Z0-9_.+-]+\.(?:deb|tar\.xz)', package['name']) or package['name'] in names or not isinstance(package['url'], str) or not package['url'].startswith('https://') or type(package['size']) is not int or not 0 < package['size'] < 512 * 1024**2 or not isinstance(package[digest], str) or not re.fullmatch('[0-9a-f]{' + str(128 if digest == 'sha512' else 64) + '}', package[digest])): raise ValueError('Invalid pinned Firefox package') names.add(package['name']) return value def read_json(path): with path.open('rb') as stream: data = stream.read(65537) if len(data) > 65536 or not isinstance(value := json.loads(data), dict): raise ValueError('Invalid Firefox metadata') return value def approved(): return manifest(read_json(Path(__file__).with_name('runtime.json'))) def bundle_id(value): return hashlib.sha256(json.dumps(manifest(value), sort_keys=True, separators=(',', ':')).encode()).hexdigest() def sync_dir(path): fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) try: os.fsync(fd) finally: os.close(fd) def write_json(path, value): temporary = path.with_name(path.name + '.tmp') fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o644) with os.fdopen(fd, 'w') as stream: json.dump(value, stream, sort_keys=True) stream.write('\n') stream.flush() os.fsync(stream.fileno()) os.replace(temporary, path) sync_dir(path.parent) def safe(path, uid=0, private=False): info = path.lstat() if stat.S_ISLNK(info.st_mode) or info.st_uid != uid or info.st_mode & (0o077 if private else 0o022): raise RuntimeError(f'Unsafe Firefox path: {path}') return info def receipt(path): safe(path) safe(path / 'ready.json') safe(path / 'firefox/firefox') return manifest(read_json(path / 'ready.json')) def transaction_id(value): if not isinstance(value, str) or not re.fullmatch('[0-9a-f]{32}', value): raise ValueError('Invalid Firefox transaction identity') return value def journal(): path = ROOT / 'update.json' if not path.exists(): return None safe(path) return update_record(read_json(path)) def update_record(value): if (set(value) != {'format', 'id', 'phase', 'target', 'previous'} or type(value['format']) is not int or value['format'] != FORMAT or not isinstance(value['phase'], str) or value['phase'] not in PHASES): raise ValueError('Invalid Firefox update journal; preserve it for review') transaction_id(value['id']) value['target'] = manifest(value['target']) value['previous'] = manifest(value['previous']) safe(ROOT / 'updates') safe(ROOT / 'updates' / value['id']) return value def has_package(bundle, name): return any(package['name'] == name for package in bundle['packages']) def host_display(): return all(os.access(path, os.X_OK) for path in ('/usr/bin/Xvfb', '/usr/bin/xauth', '/usr/bin/xkbcomp')) def display_available(bundle): if has_package(bundle, DISPLAY_PACKAGE): return has_package(bundle, FREETYPE_PACKAGE) or Path('/usr/lib/aarch64-linux-gnu/libfreetype.so.6').is_file() return host_display() def inspect(): """Small local reads only; safe to call when the Firefox tool opens.""" target = approved() if ROOT.is_symlink(): raise RuntimeError('Firefox runtime path must not be a symlink') if not ROOT.exists(): return {'action': 'install', 'target': target} safe(ROOT) record = journal() if record and record['phase'] not in ('committed', 'restored'): return {'action': 'recover', 'target': target} if not (ROOT / 'runtime').exists(): if record: raise RuntimeError('Firefox runtime is missing; preserve its update journal for review') return {'action': 'install', 'target': target} current = receipt(ROOT / 'runtime') safe(ROOT / 'state', BROWSER_UID, private=True) if record and bundle_id(current) != bundle_id(record['target'] if record['phase'] == 'committed' else record['previous']): raise RuntimeError('Firefox no longer matches its recorded transaction; preserve it for review') if current['bundle_revision'] == target['bundle_revision'] and bundle_id(current) != bundle_id(target): raise RuntimeError('Firefox bundle changed without a new bundle revision') def version(value): return tuple((list(map(int, value.removesuffix('esr').split('.'))) + [0, 0])[:3]) newer = target['bundle_revision'] > current['bundle_revision'] and version(target['version']) >= version(current['version']) repair = (newer and not display_available(current) and has_package(target, DISPLAY_PACKAGE) and display_available(target) and current['version'] == target['version'] and all(package in target['packages'] for package in current['packages']) and all(package in current['packages'] or package['name'].startswith(('display-', 'graphics-')) for package in target['packages'])) restorable = bool(record and record['phase'] == 'committed' and not (ROOT / 'recovery').exists() and not (ROOT / 'recovery-state').exists() and display_available(record['previous']) and (ROOT / 'updates' / record['id'] / 'previous').is_dir() and (ROOT / 'updates' / record['id'] / 'profile-backup').is_dir()) return {'action': 'update' if newer else 'browse', 'target': target, 'current': current, 'restorable': restorable, 'repair': repair} def report(message): print(message, flush=True) def verify(path, package): algorithm = 'sha512' if 'sha512' in package else 'sha256' with path.open('rb') as stream: digest = hashlib.file_digest(stream, algorithm).hexdigest() if path.stat().st_size != package['size'] or digest != package[algorithm]: raise ValueError(f'Package checksum mismatch: {package["name"]}') def copy_package(package, response, partial, label): remaining = package['size'] with partial.open('wb') as target: while block := response.read(min(1024 * 1024, remaining + 1)): remaining -= len(block) if remaining < 0: raise ValueError('Browser package exceeds pinned size') target.write(block) report(f'{label}… {100 * (package["size"] - remaining) // package["size"]}%') def download(package, cache, *, cache_uid=0, offline_only=False): digest = package.get('sha512', package.get('sha256')) path = cache / (digest + '-' + package['name']) legacy = cache / package['name'] for existing in (path, legacy): if existing.exists(): safe(existing, cache_uid) try: verify(existing, package) if existing == legacy: legacy.rename(path) return path except ValueError: if existing == path: existing.unlink() if not path.exists(): partial = path.with_suffix('.partial') bundled = Path(__file__).with_name('offline') / path.name label = 'Firefox' if package['name'].startswith('firefox-') else 'browser libraries' try: try: fd = os.open(bundled, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) except FileNotFoundError: if offline_only: raise FileNotFoundError(f'Missing offline Firefox archive: {bundled.name}') from None with urllib.request.urlopen(package['url'], timeout=30) as response: if not response.url.startswith('https://'): raise ValueError('Refusing an insecure browser package redirect') from None copy_package(package, response, partial, f'Downloading {label}') else: with os.fdopen(fd, 'rb') as response: info = os.fstat(response.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_size != package['size']: raise ValueError(f'Invalid bundled Firefox package: {package["name"]}') copy_package(package, response, partial, f'Copying bundled {label}') verify(partial, package) partial.rename(path) finally: partial.unlink(missing_ok=True) verify(path, package) return path def unpack(path, destination): if path.suffix == '.deb': subprocess.run(['/usr/bin/dpkg-deb', '--extract', str(path), str(destination)], check=True, timeout=30) else: with tarfile.open(path) as archive: archive.extractall(destination, filter='data') def check_host(target): # Keep the receipt compatible with older checkouts while qualifying the private display on newer images. supported = SUPPORTED_AGNOS if has_package(target, DISPLAY_PACKAGE) else (target['agnos'],) if os.geteuid() != 0 or platform.machine() != 'aarch64' or Path('/VERSION').read_text().strip() not in supported: raise RuntimeError(f'Prepare this runtime as root on ARM64 AGNOS {", ".join(supported)}') def prepare(): target = approved() check_host(target) for path in (ROOT, ROOT / 'runtime', ROOT / 'state', ROOT / 'packages'): if path.is_symlink(): raise RuntimeError(f'Refusing symlink: {path}') if ROOT.exists() and (ROOT.stat().st_uid != 0 or ROOT.stat().st_mode & 0o022): raise RuntimeError('Unsafe browser directory ownership') ROOT.mkdir(mode=0o755, exist_ok=True) fd = os.open(ROOT / '.prepare.lock', os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o644) with os.fdopen(fd, 'r+') as lock: safe(ROOT / '.prepare.lock') fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) prepare_locked(target) def prepare_locked(manifest): cache = ROOT / 'packages' if (ROOT / 'runtime').exists(): raise RuntimeError('Runtime already exists; stop and review an update separately. The profile is never replaced.') if (ROOT / 'update.json').exists(): raise RuntimeError('Open Firefox in Arabesque to finish its pending recovery before manual preparation') quiescent() if shutil.disk_usage(ROOT).free < FLOOR: raise RuntimeError('At least 6 GiB free on /data is required to prepare Firefox') # A hard stop can interrupt extraction; only this root-owned staging area is disposable. for path in ROOT.glob('.prepare-*'): if path.is_symlink(): path.unlink() elif path.is_dir(): shutil.rmtree(path) private_directory(ROOT / 'state') cache.mkdir(mode=0o700, exist_ok=True) safe(cache, private=True) with tempfile.TemporaryDirectory(prefix='.prepare-', dir=ROOT) as temporary: staging = Path(temporary) / 'runtime' build(manifest, staging) staging.rename(ROOT / 'runtime') sync_dir(ROOT) report('Firefox is prepared. Starting the browser…') def quiescent(): try: pwd.getpwuid(BROWSER_UID) except KeyError: pass else: raise RuntimeError(f'UID {BROWSER_UID} is already assigned') for entry in Path('/proc').iterdir(): if entry.name.isdigit(): try: if entry.stat().st_uid == BROWSER_UID: raise RuntimeError(f'UID {BROWSER_UID} already has running processes') except FileNotFoundError: pass active = subprocess.check_output(['systemctl', '--no-pager', '--plain', '--no-legend', 'list-units', '--state=activating,active,deactivating', 'arabesque-firefox-*'], text=True, timeout=5) own_unit = next((Path(line[3:]).name for line in Path('/proc/self/cgroup').read_text().splitlines() if line.startswith('0::')), '') if any(line.split()[0] != own_unit for line in active.splitlines() if line.split()): raise RuntimeError('Close all Firefox sessions before preparing the runtime') def build(manifest, staging, *, offline_only=False): cache = ROOT / 'packages' cache.mkdir(mode=0o700, exist_ok=True) safe(cache, private=True) staging.mkdir() for index, package in enumerate(manifest['packages'], 1): report(f'Preparing Firefox ({index}/{len(manifest["packages"])})…') archive = download(package, cache, offline_only=offline_only) safe(archive) report('Unpacking Firefox…' if package['name'].startswith('firefox-') else 'Preparing browser libraries…') # Cairo and Xvfb both need the pinned Pixman library. display_only = package['name'].startswith('display-') and package['name'] != 'display-libpixman-1-0.deb' unpack(archive, staging / 'display' if display_only else staging) if has_package(manifest, DISPLAY_PACKAGE): # Ubuntu Xvfb resolves xkbcomp at /usr/bin. Expose just that helper through a unit-local /usr overlay. extension = staging / 'isolation/xkb/usr' (extension / 'bin').mkdir(parents=True) release = extension / 'lib/extension-release.d' release.mkdir(parents=True) (release / 'extension-release.xkb').write_text('ID=_any\n') (staging / 'display/usr/bin/xkbcomp').rename(extension / 'bin/xkbcomp') fonts = staging / 'etc/fonts/fonts.conf' if fonts.is_file(): # The stock config and its links target the system tree when installed by dpkg. fonts.write_text(fonts.read_text().replace('