142 lines
5.4 KiB
Python
142 lines
5.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Config-only installer. No process, network, config.yaml or scheduler changes."""
|
|
import argparse
|
|
import base64
|
|
import fcntl
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import tempfile
|
|
|
|
ROOT = Path(__file__).resolve().parent
|
|
PROFILES = ('pmo', 'canina-competitor-worker', 'canina-seo-worker',
|
|
'canina-content-worker', 'canina-vet-review-worker', 'canina-qa-worker')
|
|
ALLOWED = {'editorial-v4/status.json'} | {
|
|
f'profiles/{p}/skills/canina-editorial-v4/{f}'
|
|
for p in PROFILES for f in ('SKILL.md', 'references/policy.md', 'references/role.json')}
|
|
|
|
|
|
def digest(data):
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def safe(home, relative):
|
|
path = home / relative
|
|
for part in (path, *path.parents):
|
|
if part.is_symlink():
|
|
raise ValueError(f'symlink refused: {part}')
|
|
if relative not in ALLOWED and relative not in (
|
|
'editorial-v4/.installer/transaction.json', 'editorial-v4/.installer/lock'):
|
|
raise ValueError('path not allowlisted')
|
|
if path.exists() and not path.is_file():
|
|
raise ValueError(f'not a regular file: {path}')
|
|
return path
|
|
|
|
|
|
def atomic(path, data):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
fd, temp = tempfile.mkstemp(prefix='.editorial-', dir=path.parent)
|
|
try:
|
|
with os.fdopen(fd, 'wb') as stream:
|
|
stream.write(data)
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
os.chmod(temp, 0o644)
|
|
os.replace(temp, path)
|
|
finally:
|
|
if os.path.exists(temp):
|
|
os.unlink(temp)
|
|
|
|
|
|
def bundle():
|
|
manifest = json.loads((ROOT / 'bundle.json').read_text())
|
|
if set(manifest['files']) != ALLOWED:
|
|
raise ValueError('bundle allowlist mismatch')
|
|
result = {}
|
|
for relative, expected in manifest['files'].items():
|
|
path = ROOT / 'payload' / relative
|
|
if path.is_symlink():
|
|
raise ValueError('source symlink refused')
|
|
data = path.read_bytes()
|
|
if digest(data) != expected:
|
|
raise ValueError(f'bundle digest mismatch: {relative}')
|
|
result[relative] = data
|
|
return result
|
|
|
|
|
|
def execute(action, home):
|
|
if not home.is_absolute() or not home.is_dir():
|
|
raise ValueError('--target-home must be an existing absolute directory')
|
|
files = bundle()
|
|
paths = {r: safe(home, r) for r in files}
|
|
journal = safe(home, 'editorial-v4/.installer/transaction.json')
|
|
if action == 'verify':
|
|
bad = [r for r, p in paths.items() if not p.exists() or p.read_bytes() != files[r]]
|
|
if bad:
|
|
raise ValueError('verification mismatch: ' + ', '.join(bad))
|
|
return {'status': 'configured_only', 'files': len(files), 'workflow_verified': False}
|
|
lock = safe(home, 'editorial-v4/.installer/lock')
|
|
lock.parent.mkdir(parents=True, exist_ok=True)
|
|
with lock.open('a') as stream:
|
|
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
if action == 'rollback':
|
|
if not journal.exists():
|
|
return {'status': 'nothing_to_rollback'}
|
|
state = json.loads(journal.read_text())
|
|
if set(state['before']) != ALLOWED or set(state['installed']) != ALLOWED:
|
|
raise ValueError('invalid rollback allowlist')
|
|
# Refuse external edits rather than destroying another writer\'s work.
|
|
for r, p in paths.items():
|
|
current = p.read_bytes() if p.exists() else None
|
|
before = state['before'][r]
|
|
old = base64.b64decode(before['data']) if before else None
|
|
if current != old and (current is None or digest(current) != state['installed'][r]):
|
|
raise ValueError(f'rollback conflict: {r}')
|
|
restore(paths, state['before'])
|
|
journal.unlink()
|
|
return {'status': 'rolled_back'}
|
|
changes = [r for r, p in paths.items() if not p.exists() or p.read_bytes() != files[r]]
|
|
if not changes:
|
|
return {'status': 'unchanged', 'files': len(files)}
|
|
if journal.exists():
|
|
raise ValueError('existing transaction: rollback before upgrade or recovery')
|
|
before = {r: {'data': base64.b64encode(p.read_bytes()).decode(),
|
|
'mode': p.stat().st_mode & 0o777} if p.exists() else None
|
|
for r, p in paths.items()}
|
|
state = {'before': before, 'installed': {r: digest(v) for r, v in files.items()}}
|
|
atomic(journal, json.dumps(state, sort_keys=True).encode())
|
|
try:
|
|
for r in changes:
|
|
atomic(paths[r], files[r])
|
|
except BaseException:
|
|
restore(paths, before)
|
|
journal.unlink()
|
|
raise
|
|
return {'status': 'installed_config_only', 'files': len(files)}
|
|
|
|
|
|
def restore(paths, before):
|
|
for r, p in paths.items():
|
|
old = before[r]
|
|
if old is None:
|
|
p.unlink(missing_ok=True)
|
|
else:
|
|
atomic(p, base64.b64decode(old['data']))
|
|
os.chmod(p, old['mode'])
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('action', choices=['install', 'verify', 'rollback'])
|
|
parser.add_argument('--target-home', type=Path, required=True)
|
|
args = parser.parse_args()
|
|
try:
|
|
print(json.dumps(execute(args.action, args.target_home), sort_keys=True))
|
|
except (OSError, ValueError, KeyError) as error:
|
|
parser.exit(1, f'{error}\n')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|