#!/usr/bin/env python3 """Small-file backup recovery check. Never restores over an existing directory.""" import argparse import hashlib import json import os from pathlib import Path import re import stat import sys def sha256_file(path): h = hashlib.sha256() with Path(path).open('rb') as stream: for block in iter(lambda: stream.read(1024 * 1024), b''): h.update(block) return h.hexdigest() def recover(source, destination, expected, max_bytes=8 * 1024 * 1024): source, destination = Path(source), Path(destination) if not re.fullmatch(r'[0-9a-f]{64}', expected): raise ValueError('Expected SHA256 must be 64 lowercase hexadecimal characters') if source.is_symlink() or not source.is_file(): raise ValueError('Source must be a regular file, not a symbolic link') if max_bytes < 1 or source.stat().st_size > max_bytes: raise ValueError('Source exceeds the small-file test size limit') if sha256_file(source) != expected: raise ValueError('Backup differs from expected hash; destination was not created') if destination.exists() or destination.is_symlink(): raise ValueError('Destination directory must be new; existing data will not be overwritten') # Explicit chmod matters on systems where inherited ACLs override mkdir defaults. destination.mkdir(mode=0o700) os.chmod(destination, 0o700) target = destination / source.name created = False try: if os.name == 'posix' and stat.S_IMODE(destination.stat().st_mode) != 0o700: raise ValueError('Destination directory is not private') fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) created = True with os.fdopen(fd, 'wb') as output, source.open('rb') as input_file: for block in iter(lambda: input_file.read(1024 * 1024), b''): output.write(block) output.flush() os.fsync(output.fileno()) os.chmod(target, 0o600) restored = sha256_file(target) if restored != expected or sha256_file(source) != expected: raise ValueError('Copy verification failed; source may have changed during the test') return {'result': 'verified', 'bytes': target.stat().st_size, 'sha256': restored, 'backup_unchanged': True, 'restored_file': target.name, 'code_executed': False} except BaseException: if created and target.exists(): target.unlink() try: destination.rmdir() except OSError: pass # Never delete unrelated files to clean up a failed test. raise def main(argv=None): p = argparse.ArgumentParser(description=__doc__) p.add_argument('backup_file', help='A small non-secret file in a real backup destination') p.add_argument('new_destination_dir', help='New private directory, never the live service path') p.add_argument('--expected-sha256', required=True, help='Hash measured from a trusted reference') p.add_argument('--max-bytes', type=int, default=8 * 1024 * 1024) args = p.parse_args(argv) try: result = recover(args.backup_file, args.new_destination_dir, args.expected_sha256, args.max_bytes) except (ValueError, OSError) as error: # Do not dump private source/destination paths from OS exceptions. text = str(error) if isinstance(error, ValueError) else type(error).__name__ print(json.dumps({'result': 'failed', 'reason': text}), file=sys.stderr) return 2 print(json.dumps(result)) return 0 if __name__ == '__main__': raise SystemExit(main())