76 lines
3.6 KiB
Python
76 lines
3.6 KiB
Python
"""Verify rollback material, or restore it into a NEW LOCAL directory only."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path, PurePosixPath
|
|
import sys
|
|
import zipfile
|
|
|
|
MAX_TOTAL = 128 * 1024 * 1024
|
|
|
|
|
|
def verify(snapshot):
|
|
plan = json.loads((snapshot / 'rollback-plan.json').read_text(encoding='utf-8'))
|
|
if plan.get('archive') != 'rollback-before.zip': raise ValueError('Unexpected rollback archive')
|
|
archive = snapshot / plan['archive']
|
|
if archive.is_symlink(): raise ValueError('Symlink archive refused')
|
|
if archive.stat().st_size > MAX_TOTAL: raise ValueError('Archive too large')
|
|
if hashlib.sha256(archive.read_bytes()).hexdigest() != plan['archive_sha256']:
|
|
raise ValueError('Rollback archive checksum mismatch')
|
|
records = plan['files']
|
|
expected = {row['path']: row for row in records}
|
|
if len(expected) != len(records): raise ValueError('Duplicate rollback manifest paths')
|
|
with zipfile.ZipFile(archive) as zipped:
|
|
names = zipped.namelist()
|
|
if len(set(names)) != len(names) or set(names) != set(expected):
|
|
raise ValueError('Rollback members differ from manifest')
|
|
if sum(info.file_size for info in zipped.infolist()) > MAX_TOTAL: raise ValueError('Archive expands beyond limit')
|
|
for name in names:
|
|
path = PurePosixPath(name)
|
|
if path.is_absolute() or '..' in path.parts or '\\' in name or ':' in name:
|
|
raise ValueError('Unsafe rollback member')
|
|
if not name.startswith(('apps/system_manage/', 'apps/static/admin/', 'ui/src/', 'ui/dist/admin/')):
|
|
raise ValueError('Rollback member outside application scope')
|
|
if zipped.getinfo(name).file_size != expected[name]['size']: raise ValueError('Member size mismatch')
|
|
raw = zipped.read(name)
|
|
if hashlib.sha256(raw).hexdigest() != expected[name]['sha256']:
|
|
raise ValueError('Rollback file checksum mismatch')
|
|
return plan
|
|
|
|
|
|
def restore(snapshot, destination):
|
|
plan = verify(snapshot)
|
|
if destination.exists(): raise ValueError('Destination must be a new local directory')
|
|
if any(parent.is_symlink() for parent in [destination, *destination.parents]):
|
|
raise ValueError('Symlink destination refused')
|
|
destination.mkdir(parents=True, exist_ok=False)
|
|
with zipfile.ZipFile(snapshot / plan['archive']) as zipped:
|
|
for row in plan['files']:
|
|
file = destination / row['path']
|
|
file.parent.mkdir(parents=True, exist_ok=True)
|
|
with file.open('xb') as stream: stream.write(zipped.read(row['path']))
|
|
(destination / 'LOCAL_ONLY.txt').write_text(
|
|
'This is a local reconstruction for review. No remote files were restored or removed.\n', encoding='utf-8')
|
|
return len(plan['files'])
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('snapshot', type=Path)
|
|
parser.add_argument('--destination', type=Path, help='Optional new LOCAL reconstruction directory')
|
|
args = parser.parse_args()
|
|
snapshot = args.snapshot.resolve()
|
|
if args.destination:
|
|
count = restore(snapshot, args.destination.absolute())
|
|
print(json.dumps({'restored_local_files': count, 'remote_mutation': False}))
|
|
else:
|
|
plan = verify(snapshot)
|
|
print(json.dumps({'verified_files': len(plan['files']), 'remote_mutation': False}))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
try: main()
|
|
except (OSError, ValueError, KeyError, zipfile.BadZipFile) as exc:
|
|
print('Local rollback verification failed: ' + type(exc).__name__, file=sys.stderr)
|
|
sys.exit(1)
|