From 8d4127de30fb1f15df57bfdaeedad3c961bab3ef Mon Sep 17 00:00:00 2001 From: Mateusz Stomski Date: Fri, 9 Oct 2026 19:19:28 +0200 Subject: [PATCH] feat(restore): implement slice 4 snapshot management, diff engine, and safe restore --- docs/plans/linux-backuper/00-status.md | 2 +- linux_backuper/cli.py | 290 ++++++++++++++++++++++ linux_backuper/core/archiver.py | 108 ++++++++- linux_backuper/core/diff.py | 248 +++++++++++++++++++ linux_backuper/core/restore.py | 317 +++++++++++++++++++++++++ linux_backuper/models.py | 37 +++ tests/test_cli.py | 117 ++++++++- tests/test_diff.py | 140 +++++++++++ tests/test_restore.py | 131 ++++++++++ 9 files changed, 1386 insertions(+), 4 deletions(-) create mode 100644 linux_backuper/core/diff.py create mode 100644 linux_backuper/core/restore.py create mode 100644 tests/test_diff.py create mode 100644 tests/test_restore.py diff --git a/docs/plans/linux-backuper/00-status.md b/docs/plans/linux-backuper/00-status.md index adddc42..9fc570c 100644 --- a/docs/plans/linux-backuper/00-status.md +++ b/docs/plans/linux-backuper/00-status.md @@ -9,7 +9,7 @@ - [x] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + system inspector stub + gzip snapshot + 0600 perms + tests) - [x] Slice 2 — comprehensive host state inspector (users/groups, kernel/sysctl/cmdline/modules, hardware/cpu/pci, storage/LVM, network, packages) - [x] Slice 3 — profile system, configuration archiver & manifest generator (`quick`, `system`, `full`, custom) with atomic write & SHA-256 manifest -- [ ] Slice 4 — snapshot management, live diff & safe restore engine (list, show, verify, live system diff, extract, restore with dry-run & safety snapshot) +- [x] Slice 4 — snapshot management, live diff & safe restore engine (list, show, verify, live system diff, extract, restore with dry-run & safety snapshot) - [ ] Slice 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, `--keep-weekly`, local & remote) - [ ] Slice 6 — remote transport sync (local-first + SFTP / rsync / mounted NFS/SMB push with separate remote retention) - [ ] Slice 7 — native packaging (.deb, .rpm, .tar.gz via pure Python builder) diff --git a/linux_backuper/cli.py b/linux_backuper/cli.py index 8f34c62..d6c6941 100644 --- a/linux_backuper/cli.py +++ b/linux_backuper/cli.py @@ -15,15 +15,18 @@ from linux_backuper.core.constants import ( DEFAULT_CONFIG_PATH, DEFAULT_PID_PATH, EXIT_CORRUPTED, + EXIT_DRY_RUN, EXIT_GENERIC_ERROR, EXIT_PERM_DENIED, EXIT_PREFLIGHT_FAIL, EXIT_SUCCESS, ) from linux_backuper.core.detector import detect_distro +from linux_backuper.core.diff import DiffEngine from linux_backuper.core.inspector import SystemInspector from linux_backuper.core.lock import SingleInstanceLock, LockAcquisitionError from linux_backuper.core.profiles import ProfileManager +from linux_backuper.core.restore import SafeRestoreEngine, DryRunException from linux_backuper.models import SnapshotManifest def check_root_permissions() -> bool: @@ -221,6 +224,252 @@ def handle_verify(args: argparse.Namespace) -> int: return EXIT_SUCCESS if is_valid else EXIT_CORRUPTED +def handle_show(args: argparse.Namespace) -> int: + """Execute show command.""" + target_dir = args.target_dir or DEFAULT_BACKUP_DIR + archive_path = SnapshotArchiver.resolve_archive_path(target_dir, args.snapshot_id) + if not os.path.isfile(archive_path): + sys.stderr.write(f"[ERROR] Snapshot archive not found: {archive_path}\n") + return EXIT_GENERIC_ERROR + + try: + manifest = SnapshotArchiver.read_manifest_from_archive(archive_path) + except Exception as e: + sys.stderr.write(f"[ERROR] Failed to read manifest: {e}\n") + return EXIT_GENERIC_ERROR + + if args.json: + payload = manifest.to_dict() + payload["archive_path"] = archive_path + if args.packages: + pkg_txt = SnapshotArchiver.read_meta_file(archive_path, "meta/packages.txt") + payload["packages_dump"] = pkg_txt.splitlines() if pkg_txt else [] + print(json.dumps(payload, indent=2)) + return EXIT_SUCCESS + + size_mb = manifest.stats.get("compressed_bytes", 0) / (1024 * 1024) + uncomp_mb = manifest.stats.get("uncompressed_bytes", 0) / (1024 * 1024) + os_name = manifest.os.get("distro_name", "Linux") + os_ver = manifest.os.get("version_id", "") + arch = manifest.os.get("arch", "") + + sys.stdout.write("=" * 80 + "\n") + sys.stdout.write(f"Snapshot ID: {manifest.snapshot_id}\n") + sys.stdout.write(f"Archive File: {archive_path}\n") + sys.stdout.write(f"Created At: {manifest.created_at}\n") + sys.stdout.write(f"Hostname: {manifest.hostname}\n") + sys.stdout.write(f"Operating System: {os_name} {os_ver} ({arch})\n") + sys.stdout.write(f"Profile: {manifest.profile}\n") + sys.stdout.write(f"Compression: {manifest.compression}\n") + sys.stdout.write(f"File Count: {manifest.stats.get('file_count', 0)}\n") + sys.stdout.write(f"Size on Disk: {size_mb:.2f} MB (uncompressed: {uncomp_mb:.2f} MB)\n") + sys.stdout.write(f"Package Manager: {manifest.package_manager} ({manifest.package_count} packages recorded)\n") + sys.stdout.write(f"Included Paths: {', '.join(manifest.included_paths)}\n") + if manifest.stats.get("sanitized_count"): + sys.stdout.write(f"Sanitized Files: {manifest.stats.get('sanitized_count')} (secrets redacted)\n") + sys.stdout.write("=" * 80 + "\n") + + if args.files: + sys.stdout.write("\nArchived files:\n") + for f in sorted(manifest.files_sha256.keys()): + sys.stdout.write(f" {f}\n") + + if args.packages: + pkg_txt = SnapshotArchiver.read_meta_file(archive_path, "meta/packages.txt") + if pkg_txt: + sys.stdout.write("\nArchived packages:\n") + sys.stdout.write(pkg_txt + "\n") + + return EXIT_SUCCESS + +def handle_diff(args: argparse.Namespace) -> int: + """Execute diff command.""" + target_dir = args.target_dir or DEFAULT_BACKUP_DIR + engine = DiffEngine(target_dir=target_dir) + + try: + if args.snapshot_id_2: + result = engine.diff_snapshots(args.snapshot_id, args.snapshot_id_2) + else: + target_root = getattr(args, "target_root", "/") or "/" + result = engine.diff_with_live(args.snapshot_id, target_root=target_root) + except Exception as e: + sys.stderr.write(f"[ERROR] Diff failed: {e}\n") + return EXIT_GENERIC_ERROR + + if args.json: + print(json.dumps(result, indent=2)) + return EXIT_SUCCESS + + if result["type"] == "live_vs_snapshot": + sys.stdout.write(f"--- Live System vs Snapshot '{result['snapshot_id']}' ---\n") + files = result["files"] + if files["modified"]: + sys.stdout.write(f"\nModified files on live system ({len(files['modified'])}):\n") + for f in files["modified"]: + sys.stdout.write(f" [M] {f}\n") + if args.unified: + u_diff = engine.generate_unified_file_diff(result["snapshot_id"], f, target_root=result["target_root"]) + if u_diff: + sys.stdout.write(u_diff + "\n") + if files["missing_on_live"]: + sys.stdout.write(f"\nMissing files on live system (present in backup) ({len(files['missing_on_live'])}):\n") + for f in files["missing_on_live"]: + sys.stdout.write(f" [-] {f}\n") + if files["added_on_live"]: + sys.stdout.write(f"\nAdded files on live system (not in backup) ({len(files['added_on_live'])}):\n") + for f in files["added_on_live"]: + sys.stdout.write(f" [+] {f}\n") + sys.stdout.write(f"\nUnchanged files: {files['unchanged_count']}\n") + + pkgs = result["packages"] + if pkgs["installed_since_backup"]: + sys.stdout.write(f"\nPackages installed since backup ({len(pkgs['installed_since_backup'])}):\n") + for p, v in list(pkgs["installed_since_backup"].items())[:20]: + sys.stdout.write(f" + {p} ({v})\n") + if len(pkgs["installed_since_backup"]) > 20: + sys.stdout.write(f" ... and {len(pkgs['installed_since_backup']) - 20} more\n") + if pkgs["removed_since_backup"]: + sys.stdout.write(f"\nPackages removed since backup ({len(pkgs['removed_since_backup'])}):\n") + for p, v in list(pkgs["removed_since_backup"].items())[:20]: + sys.stdout.write(f" - {p} ({v})\n") + if pkgs["version_changed"]: + sys.stdout.write(f"\nPackages with changed versions ({len(pkgs['version_changed'])}):\n") + for p, ch in list(pkgs["version_changed"].items())[:20]: + sys.stdout.write(f" ~ {p}: {ch['snapshot']} -> {ch['live']}\n") + + else: + sys.stdout.write(f"--- Snapshot '{result['snapshot_1']}' vs Snapshot '{result['snapshot_2']}' ---\n") + files = result["files"] + if files["modified"]: + sys.stdout.write(f"\nModified files ({len(files['modified'])}):\n") + for f in files["modified"]: + sys.stdout.write(f" [M] {f}\n") + if files["added"]: + sys.stdout.write(f"\nFiles added in snapshot 2 ({len(files['added'])}):\n") + for f in files["added"]: + sys.stdout.write(f" [+] {f}\n") + if files["removed"]: + sys.stdout.write(f"\nFiles removed in snapshot 2 ({len(files['removed'])}):\n") + for f in files["removed"]: + sys.stdout.write(f" [-] {f}\n") + sys.stdout.write(f"\nUnchanged files: {files['unchanged_count']}\n") + + return EXIT_SUCCESS + +def handle_extract(args: argparse.Namespace) -> int: + """Execute extract command.""" + target_dir = args.target_dir or DEFAULT_BACKUP_DIR + archive_path = SnapshotArchiver.resolve_archive_path(target_dir, args.snapshot_id) + if not os.path.isfile(archive_path): + sys.stderr.write(f"[ERROR] Snapshot archive not found: {archive_path}\n") + return EXIT_GENERIC_ERROR + + try: + out_path = SnapshotArchiver.extract_file(archive_path, args.file, args.out) + except Exception as e: + sys.stderr.write(f"[ERROR] Extract failed: {e}\n") + return EXIT_GENERIC_ERROR + + if args.json: + print(json.dumps({ + "status": "success", + "snapshot_id": args.snapshot_id, + "file": args.file, + "destination": out_path + }, indent=2)) + else: + sys.stdout.write(f"[SUCCESS] Extracted '{args.file}' to '{out_path}'\n") + + return EXIT_SUCCESS + +def handle_restore(args: argparse.Namespace) -> int: + """Execute restore command.""" + target_dir = args.target_dir or DEFAULT_BACKUP_DIR + target_root = getattr(args, "target_root", "/") or "/" + force = getattr(args, "force", False) + dry_run = getattr(args, "dry_run", False) + include_fstab = getattr(args, "include_fstab", False) + pid_path = getattr(args, "pid_path", None) or os.environ.get("LINUX_BACKUPER_PID_PATH") or DEFAULT_PID_PATH + + # If live mutation requested, require root unless non-root override + if force and not dry_run and os.geteuid() != 0 and not os.environ.get("LINUX_BACKUPER_ALLOW_NON_ROOT"): + sys.stderr.write("[ERROR] Restoring files to live system requires root privileges (run with sudo).\n") + return EXIT_PERM_DENIED + + engine = SafeRestoreEngine(target_dir=target_dir) + try: + plan = engine.plan_restore(args.snapshot_id, target_root=target_root, include_fstab=include_fstab) + except Exception as e: + sys.stderr.write(f"[ERROR] Failed to plan restore: {e}\n") + return EXIT_GENERIC_ERROR + + # If --dry-run or not --force + if dry_run or not force: + if args.json: + out_dict = plan.to_dict() + out_dict["mode"] = "dry-run" + print(json.dumps(out_dict, indent=2)) + else: + sys.stdout.write("=" * 80 + "\n") + sys.stdout.write(f"RESTORE EXECUTION PLAN (Dry Run) — Snapshot: {plan.snapshot_id}\n") + sys.stdout.write(f"Target Root: {plan.target_root}\n") + sys.stdout.write("=" * 80 + "\n") + + create_items = [i for i in plan.items if i.action == "create"] + modify_items = [i for i in plan.items if i.action == "modify"] + skip_items = [i for i in plan.items if i.action == "skip"] + network_items = [i for i in plan.items if i.is_sensitive_network and i.action in ("create", "modify")] + + if network_items: + sys.stdout.write("\n[WARNING] SENSITIVE NETWORK CONFIGURATION DETECTED:\n") + for item in network_items: + sys.stdout.write(f" ! {item.abs_path} will be overwritten\n") + sys.stdout.write(" Restoring network files may impact active network connectivity.\n\n") + + if create_items: + sys.stdout.write(f"Files to CREATE ({len(create_items)}):\n") + for item in create_items: + sys.stdout.write(f" [+] {item.abs_path}\n") + + if modify_items: + sys.stdout.write(f"\nFiles to MODIFY ({len(modify_items)}):\n") + for item in modify_items: + sys.stdout.write(f" [~] {item.abs_path}\n") + + if skip_items: + sys.stdout.write(f"\nFiles to SKIP ({len(skip_items)}):\n") + for item in skip_items: + sys.stdout.write(f" [*] {item.abs_path} ({item.reason})\n") + + sys.stdout.write("-" * 80 + "\n") + sys.stdout.write(f"Summary: {len(create_items)} to create, {len(modify_items)} to modify, {len(skip_items)} skipped.\n") + sys.stdout.write("[NOTICE] Dry run completed without modifying filesystem blocks.\n") + sys.stdout.write("[ACTION] Pass --force to execute live restore (automatic safety snapshot will be created).\n") + + return EXIT_DRY_RUN + + # Live restore with --force + if not args.json: + sys.stdout.write(f"[INFO] Initiating live restore for snapshot '{plan.snapshot_id}'...\n") + sys.stdout.write(f"[INFO] Target root directory: {plan.target_root}\n") + + try: + res = engine.execute_restore(plan, force=True, pid_path=pid_path) + except Exception as e: + sys.stderr.write(f"[ERROR] Restore failed: {e}\n") + return EXIT_GENERIC_ERROR + + if args.json: + print(json.dumps(res, indent=2)) + else: + sys.stdout.write(f"[SUCCESS] Safety snapshot created: {res['safety_snapshot_id']}\n") + sys.stdout.write(f"[SUCCESS] Restored {res['restored_count']} files to {plan.target_root}\n") + if res.get("selinux_context_restored"): + sys.stdout.write("[INFO] Restored SELinux security contexts via restorecon.\n") + + return EXIT_SUCCESS + def build_parser() -> argparse.ArgumentParser: """Construct CLI argument parser.""" common_parser = argparse.ArgumentParser(add_help=False) @@ -252,6 +501,38 @@ def build_parser() -> argparse.ArgumentParser: list_parser = subparsers.add_parser("list", help="List existing local snapshots", parents=[common_parser]) list_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory to scan for snapshots") + # Show command + show_parser = subparsers.add_parser("show", help="Display details and metadata of a snapshot", parents=[common_parser]) + show_parser.add_argument("snapshot_id", help="Snapshot ID or filename to display") + show_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the snapshot") + show_parser.add_argument("--packages", action="store_true", help="List all recorded installed packages") + show_parser.add_argument("--files", action="store_true", help="List all archived file paths") + + # Diff command + diff_parser = subparsers.add_parser("diff", help="Compare live system against snapshot, or two snapshots", parents=[common_parser]) + diff_parser.add_argument("snapshot_id", help="First snapshot ID (or base snapshot for live diff)") + diff_parser.add_argument("snapshot_id_2", nargs="?", default=None, help="Second snapshot ID (optional, compares two snapshots)") + diff_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing snapshots") + diff_parser.add_argument("--target-root", default="/", help="Filesystem root to compare against in live diff (default: /)") + diff_parser.add_argument("--unified", "-u", action="store_true", help="Display unified diff for modified text files") + + # Extract command + extract_parser = subparsers.add_parser("extract", help="Selectively extract a single file from a snapshot", parents=[common_parser]) + extract_parser.add_argument("snapshot_id", help="Snapshot ID or filename") + extract_parser.add_argument("--file", required=True, help="File path inside snapshot to extract") + extract_parser.add_argument("--out", required=True, help="Destination file or directory path") + extract_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the snapshot") + + # Restore command + restore_parser = subparsers.add_parser("restore", help="Restore system configuration from a snapshot", parents=[common_parser]) + restore_parser.add_argument("snapshot_id", help="Snapshot ID to restore") + restore_parser.add_argument("--dry-run", action="store_true", help="Display execution plan without modifying filesystem (exit code 5)") + restore_parser.add_argument("--force", action="store_true", help="Execute live restoration (safety snapshot created automatically)") + restore_parser.add_argument("--target-root", default="/", help="Target root directory to restore onto (default: /)") + restore_parser.add_argument("--include-fstab", action="store_true", help="Allow restoring /etc/fstab") + restore_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the snapshot") + restore_parser.add_argument("--pid-path", help=f"Path to lockfile PID file (default: {DEFAULT_PID_PATH})") + # Verify command verify_parser = subparsers.add_parser("verify", help="Verify snapshot cryptographic integrity", parents=[common_parser]) verify_parser.add_argument("snapshot_id", help="Snapshot ID or archive filename to verify") @@ -272,6 +553,14 @@ def main(argv: Optional[List[str]] = None) -> int: return handle_snapshot(args) elif args.subcommand == "list": return handle_list(args) + elif args.subcommand == "show": + return handle_show(args) + elif args.subcommand == "diff": + return handle_diff(args) + elif args.subcommand == "extract": + return handle_extract(args) + elif args.subcommand == "restore": + return handle_restore(args) elif args.subcommand == "verify": return handle_verify(args) @@ -279,3 +568,4 @@ def main(argv: Optional[List[str]] = None) -> int: if __name__ == "__main__": sys.exit(main()) + diff --git a/linux_backuper/core/archiver.py b/linux_backuper/core/archiver.py index f369d10..678971e 100644 --- a/linux_backuper/core/archiver.py +++ b/linux_backuper/core/archiver.py @@ -27,7 +27,7 @@ def is_socket_or_fifo(filepath: str) -> bool: st = os.lstat(filepath) return stat.S_ISSOCK(st.st_mode) or stat.S_ISFIFO(st.st_mode) except OSError: - return True + return False def is_sanitized_target(filepath: str) -> bool: """Check if file contains secrets and must be omitted during sanitized export.""" @@ -301,6 +301,109 @@ class SnapshotArchiver: return True, "Integrity verified successfully" + @staticmethod + def resolve_archive_path(target_dir: str, snapshot_id: str) -> str: + """Resolve a snapshot ID or filename to full archive path.""" + if os.path.isabs(snapshot_id) and os.path.exists(snapshot_id): + return snapshot_id + direct = os.path.join(target_dir, snapshot_id) + if os.path.exists(direct): + return direct + tar_gz = os.path.join(target_dir, f"{snapshot_id}.tar.gz") + if os.path.exists(tar_gz): + return tar_gz + tar_plain = os.path.join(target_dir, f"{snapshot_id}.tar") + if os.path.exists(tar_plain): + return tar_plain + if snapshot_id.endswith(".tar.gz") or snapshot_id.endswith(".tar"): + return direct + return tar_gz + + @staticmethod + def read_meta_file(archive_path: str, meta_relative_path: str) -> Optional[str]: + """Read a metadata text file from the archive (e.g. meta/packages.txt).""" + with tarfile.open(archive_path, "r:*") as tar: + try: + member = tar.getmember(meta_relative_path) + f = tar.extractfile(member) + if f: + return f.read().decode("utf-8", errors="replace") + except KeyError: + return None + return None + + @staticmethod + def extract_file(archive_path: str, member_path: str, destination_path: str) -> str: + """ + Extract a single member from the archive to destination_path. + Guards strictly against Zip Slip / path traversal. + Returns final destination path. + """ + dest_abs = os.path.abspath(destination_path) + + # If destination is an existing directory, append member filename + if os.path.isdir(dest_abs): + dest_abs = os.path.join(dest_abs, os.path.basename(member_path)) + + dest_dir = os.path.dirname(dest_abs) + if dest_dir: + os.makedirs(dest_dir, exist_ok=True) + + with tarfile.open(archive_path, "r:*") as tar: + # Candidate names inside archive + candidates = [ + member_path, + f"data/{member_path.lstrip('/')}", + member_path.lstrip("/"), + f"data{member_path}" if member_path.startswith("/") else f"data/{member_path}" + ] + target_member = None + for c in candidates: + try: + target_member = tar.getmember(c) + break + except KeyError: + continue + + if not target_member: + clean_target = member_path.strip("/") + for m in tar.getmembers(): + if m.name == clean_target or m.name == f"data/{clean_target}": + target_member = m + break + if m.name.endswith(f"/{clean_target}") or m.name.endswith(clean_target): + target_member = m + break + + if not target_member: + raise FileNotFoundError(f"File '{member_path}' not found in archive") + + if not target_member.isreg(): + raise ValueError(f"Member '{target_member.name}' is not a regular file") + + f_in = tar.extractfile(target_member) + if not f_in: + raise IOError(f"Could not read member '{target_member.name}'") + + tmp_dest = f"{dest_abs}.tmp.{os.getpid()}" + try: + with open(tmp_dest, "wb") as f_out: + while chunk := f_in.read(BUFFER_SIZE): + f_out.write(chunk) + try: + os.chmod(tmp_dest, target_member.mode) + except OSError: + pass + os.replace(tmp_dest, dest_abs) + finally: + if os.path.exists(tmp_dest): + try: + os.unlink(tmp_dest) + except OSError: + pass + + return dest_abs + def list_snapshots(self) -> List[SnapshotManifest]: """List all valid snapshots in the target directory.""" if not os.path.isdir(self.target_dir): @@ -315,7 +418,7 @@ class SnapshotArchiver: return [] for filename in entries: - if filename.endswith(".tar.gz") and not filename.startswith("."): + if (filename.endswith(".tar.gz") or filename.endswith(".tar")) and not filename.startswith("."): filepath = os.path.join(self.target_dir, filename) try: manifest = self.read_manifest_from_archive(filepath) @@ -323,3 +426,4 @@ class SnapshotArchiver: except Exception: pass return snapshots + diff --git a/linux_backuper/core/diff.py b/linux_backuper/core/diff.py new file mode 100644 index 0000000..6103672 --- /dev/null +++ b/linux_backuper/core/diff.py @@ -0,0 +1,248 @@ +"""System and snapshot comparison engine (DiffEngine).""" + +import difflib +import hashlib +import os +import tarfile +from typing import Dict, List, Optional, Tuple, Any + +from linux_backuper.core.archiver import SnapshotArchiver, calculate_file_sha256, BUFFER_SIZE +from linux_backuper.core.detector import detect_distro +from linux_backuper.core.inspector import SystemInspector +from linux_backuper.models import PackageItem, SnapshotManifest + +MAX_DIFF_TEXT_BYTES = 1024 * 1024 # 1 MB threshold for generating unified diffs + +class DiffEngine: + """Computes differences between snapshots, and between live system and snapshot.""" + + def __init__(self, target_dir: str): + self.target_dir = target_dir + + def _resolve_archive(self, snapshot_id: str) -> str: + archive_path = SnapshotArchiver.resolve_archive_path(self.target_dir, snapshot_id) + if not os.path.isfile(archive_path): + raise FileNotFoundError(f"Snapshot archive not found: {archive_path}") + return archive_path + + @staticmethod + def _parse_packages_txt(content: Optional[str]) -> Dict[str, str]: + """Parse meta/packages.txt lines into {name: version}.""" + packages: Dict[str, str] = {} + if not content: + return packages + + for line in content.splitlines(): + line = line.strip() + if not line or line.startswith("#"): + continue + parts = line.split() + if len(parts) >= 2: + packages[parts[0]] = parts[1] + elif len(parts) == 1: + packages[parts[0]] = "unknown" + return packages + + def diff_snapshots(self, id1: str, id2: str) -> Dict[str, Any]: + """ + Compare two snapshots. + Returns detailed dictionary of file differences and package differences. + """ + path1 = self._resolve_archive(id1) + path2 = self._resolve_archive(id2) + + m1 = SnapshotArchiver.read_manifest_from_archive(path1) + m2 = SnapshotArchiver.read_manifest_from_archive(path2) + + hashes1 = {k: v for k, v in m1.files_sha256.items() if k.startswith("data/")} + hashes2 = {k: v for k, v in m2.files_sha256.items() if k.startswith("data/")} + + keys1 = set(hashes1.keys()) + keys2 = set(hashes2.keys()) + + added_files = sorted(list(keys2 - keys1)) + removed_files = sorted(list(keys1 - keys2)) + modified_files = sorted([k for k in (keys1 & keys2) if hashes1[k] != hashes2[k]]) + unchanged_files = sorted([k for k in (keys1 & keys2) if hashes1[k] == hashes2[k]]) + + # Package comparison + pkg_txt1 = SnapshotArchiver.read_meta_file(path1, "meta/packages.txt") + pkg_txt2 = SnapshotArchiver.read_meta_file(path2, "meta/packages.txt") + + pkgs1 = self._parse_packages_txt(pkg_txt1) + pkgs2 = self._parse_packages_txt(pkg_txt2) + + p_keys1 = set(pkgs1.keys()) + p_keys2 = set(pkgs2.keys()) + + pkgs_added = {p: pkgs2[p] for p in sorted(p_keys2 - p_keys1)} + pkgs_removed = {p: pkgs1[p] for p in sorted(p_keys1 - p_keys2)} + pkgs_changed = {} + for p in sorted(p_keys1 & p_keys2): + if pkgs1[p] != pkgs2[p]: + pkgs_changed[p] = {"old": pkgs1[p], "new": pkgs2[p]} + + return { + "type": "snapshot_vs_snapshot", + "snapshot_1": m1.snapshot_id, + "snapshot_2": m2.snapshot_id, + "files": { + "added": added_files, + "removed": removed_files, + "modified": modified_files, + "unchanged_count": len(unchanged_files) + }, + "packages": { + "added": pkgs_added, + "removed": pkgs_removed, + "changed": pkgs_changed + } + } + + def diff_with_live(self, snapshot_id: str, target_root: str = "/") -> Dict[str, Any]: + """ + Compare live system state against a snapshot. + Checks: + - Files present in snapshot vs live filesystem under target_root + - Files added on live system in snapshot's included paths + - Live packages vs snapshot packages + """ + archive_path = self._resolve_archive(snapshot_id) + manifest = SnapshotArchiver.read_manifest_from_archive(archive_path) + + data_hashes = {k: v for k, v in manifest.files_sha256.items() if k.startswith("data/")} + + missing_on_live: List[str] = [] + modified_on_live: List[str] = [] + unchanged_on_live: List[str] = [] + file_diffs: Dict[str, str] = {} + + target_root_clean = os.path.abspath(target_root) + + for rel_data_path, archived_sha in data_hashes.items(): + # rel_data_path is like 'data/etc/hosts' + clean_subpath = rel_data_path[5:].lstrip("/") # 'etc/hosts' + live_abs_path = os.path.join(target_root_clean, clean_subpath) + + if not os.path.exists(live_abs_path) and not os.path.islink(live_abs_path): + missing_on_live.append("/" + clean_subpath) + continue + + try: + live_sha = calculate_file_sha256(live_abs_path) + except OSError: + modified_on_live.append("/" + clean_subpath) + continue + + if live_sha != archived_sha: + modified_on_live.append("/" + clean_subpath) + else: + unchanged_on_live.append("/" + clean_subpath) + + # Check for added files on live system within included_paths + added_on_live: List[str] = [] + for inc_path in manifest.included_paths: + if inc_path.startswith(target_root_clean): + live_scan_dir = inc_path + else: + live_scan_dir = os.path.join(target_root_clean, inc_path.lstrip("/")) + if not os.path.isdir(live_scan_dir): + continue + for root, _, files in os.walk(live_scan_dir): + for f in files: + full_p = os.path.join(root, f) + rel_to_target = os.path.relpath(full_p, target_root_clean) + archive_key = "data/" + rel_to_target.lstrip("/") + if archive_key not in data_hashes: + candidate_found = any(dk.endswith("/" + rel_to_target.lstrip("/")) for dk in data_hashes) + if not candidate_found: + added_on_live.append("/" + rel_to_target.lstrip("/")) + + # Packages diff + pkg_txt = SnapshotArchiver.read_meta_file(archive_path, "meta/packages.txt") + archived_pkgs = self._parse_packages_txt(pkg_txt) + + distro_id = manifest.os.get("distro_id", detect_distro().distro_id) + inspector = SystemInspector(distro_id=distro_id) + live_packages = inspector.inspect_packages() + live_pkgs_dict = {p.name: p.version for p in live_packages} + + archived_keys = set(archived_pkgs.keys()) + live_keys = set(live_pkgs_dict.keys()) + + pkgs_installed_since = {p: live_pkgs_dict[p] for p in sorted(live_keys - archived_keys)} + pkgs_removed_since = {p: archived_pkgs[p] for p in sorted(archived_keys - live_keys)} + pkgs_version_changed = {} + for p in sorted(archived_keys & live_keys): + if live_pkgs_dict[p] != archived_pkgs[p]: + pkgs_version_changed[p] = { + "snapshot": archived_pkgs[p], + "live": live_pkgs_dict[p] + } + + return { + "type": "live_vs_snapshot", + "snapshot_id": manifest.snapshot_id, + "target_root": target_root_clean, + "files": { + "modified": sorted(modified_on_live), + "missing_on_live": sorted(missing_on_live), + "added_on_live": sorted(added_on_live), + "unchanged_count": len(unchanged_on_live) + }, + "packages": { + "installed_since_backup": pkgs_installed_since, + "removed_since_backup": pkgs_removed_since, + "version_changed": pkgs_version_changed + } + } + + def generate_unified_file_diff( + self, + snapshot_id: str, + file_path: str, + target_root: str = "/" + ) -> Optional[str]: + """ + Generate unified diff for a single file between snapshot and live filesystem. + Returns unified diff string, or None if files are binary or identical. + """ + archive_path = self._resolve_archive(snapshot_id) + clean_subpath = file_path.lstrip("/") + archive_member = f"data/{clean_subpath}" + live_path = os.path.join(os.path.abspath(target_root), clean_subpath) + + archived_content: Optional[str] = None + with tarfile.open(archive_path, "r:*") as tar: + try: + member = tar.getmember(archive_member) + if member.isreg() and member.size <= MAX_DIFF_TEXT_BYTES: + f = tar.extractfile(member) + if f: + archived_content = f.read().decode("utf-8", errors="replace") + except KeyError: + return None + + live_content: Optional[str] = None + if os.path.isfile(live_path): + if os.path.getsize(live_path) <= MAX_DIFF_TEXT_BYTES: + try: + with open(live_path, "r", encoding="utf-8", errors="replace") as f: + live_content = f.read() + except OSError: + pass + + if archived_content is None and live_content is None: + return None + + archived_lines = archived_content.splitlines(keepends=True) if archived_content is not None else [] + live_lines = live_content.splitlines(keepends=True) if live_content is not None else [] + + diff = list(difflib.unified_diff( + archived_lines, + live_lines, + fromfile=f"snapshot:{snapshot_id}:/{clean_subpath}", + tofile=f"live:/{clean_subpath}" + )) + + return "".join(diff) if diff else None diff --git a/linux_backuper/core/restore.py b/linux_backuper/core/restore.py new file mode 100644 index 0000000..b6fb4a8 --- /dev/null +++ b/linux_backuper/core/restore.py @@ -0,0 +1,317 @@ +"""Safe restore engine with dry-run default, safety snapshots, and atomic write.""" + +import datetime +import os +import shutil +import socket +import subprocess +import tarfile +from typing import Dict, List, Optional, Tuple, Any + +from linux_backuper.core.archiver import SnapshotArchiver, calculate_file_sha256, is_socket_or_fifo, BUFFER_SIZE +from linux_backuper.core.constants import EXIT_DRY_RUN, EXIT_SUCCESS, EXIT_GENERIC_ERROR, DEFAULT_BACKUP_DIR +from linux_backuper.core.detector import detect_distro +from linux_backuper.core.lock import SingleInstanceLock +from linux_backuper.models import RestorePlan, RestorePlanItem, SnapshotManifest + +EXCLUDED_DYNAMIC_PATHS = { + "/etc/resolv.conf", + "/etc/mtab", + "/etc/adjtime", + "/etc/machine-id" +} + +SENSITIVE_NETWORK_PREFIXES = ( + "/etc/netplan", + "/etc/sysconfig/network-scripts", + "/etc/network/interfaces", + "/etc/NetworkManager" +) + +class DryRunException(Exception): + """Raised when restore runs in dry-run mode (exit code 5).""" + def __init__(self, plan: RestorePlan): + self.plan = plan + super().__init__("Restore executed in dry-run mode. Pass --force to apply changes.") + +class SafeRestoreEngine: + """Safely restores configuration archives onto the filesystem.""" + + def __init__(self, target_dir: str = DEFAULT_BACKUP_DIR): + self.target_dir = target_dir + + def _resolve_archive(self, snapshot_id: str) -> str: + archive_path = SnapshotArchiver.resolve_archive_path(self.target_dir, snapshot_id) + if not os.path.isfile(archive_path): + raise FileNotFoundError(f"Snapshot archive not found: {archive_path}") + return archive_path + + def plan_restore( + self, + snapshot_id: str, + target_root: str = "/", + include_fstab: bool = False + ) -> RestorePlan: + """ + Inspect snapshot and construct a detailed RestorePlan against target_root. + Identifies create, modify, and skip actions without mutating the disk. + """ + archive_path = self._resolve_archive(snapshot_id) + manifest = SnapshotArchiver.read_manifest_from_archive(archive_path) + + target_root_clean = os.path.abspath(target_root) + plan_items: List[RestorePlanItem] = [] + + with tarfile.open(archive_path, "r:*") as tar: + for member in tar.getmembers(): + if not member.name.startswith("data/"): + continue + + clean_subpath = member.name[5:].lstrip("/") + abs_sys_path = "/" + clean_subpath + target_dest_path = os.path.join(target_root_clean, clean_subpath) + + # 1. Check excluded dynamic / runtime files + if abs_sys_path in EXCLUDED_DYNAMIC_PATHS: + plan_items.append(RestorePlanItem( + rel_path=member.name, + abs_path=target_dest_path, + action="skip", + reason="Excluded dynamic/volatile system file" + )) + continue + + if abs_sys_path == "/etc/fstab" and not include_fstab: + plan_items.append(RestorePlanItem( + rel_path=member.name, + abs_path=target_dest_path, + action="skip", + reason="Protected filesystem table (/etc/fstab). Pass --include-fstab to overwrite" + )) + continue + + if os.path.exists(target_dest_path) and is_socket_or_fifo(target_dest_path): + plan_items.append(RestorePlanItem( + rel_path=member.name, + abs_path=target_dest_path, + action="skip", + reason="Socket or FIFO file on filesystem" + )) + continue + + # 2. Check sensitive network files + is_net = any(abs_sys_path.startswith(prefix) for prefix in SENSITIVE_NETWORK_PREFIXES) + + expected_sha = manifest.files_sha256.get(member.name) + + # 3. Check live file state + if not os.path.exists(target_dest_path) and not os.path.islink(target_dest_path): + plan_items.append(RestorePlanItem( + rel_path=member.name, + abs_path=target_dest_path, + action="create", + reason="File does not exist on target system", + is_sensitive_network=is_net, + source_sha256=expected_sha, + target_sha256=None + )) + else: + if os.path.isfile(target_dest_path): + target_sha = calculate_file_sha256(target_dest_path) + if expected_sha and target_sha == expected_sha: + plan_items.append(RestorePlanItem( + rel_path=member.name, + abs_path=target_dest_path, + action="skip", + reason="File content is identical to snapshot", + is_sensitive_network=is_net, + source_sha256=expected_sha, + target_sha256=target_sha + )) + else: + plan_items.append(RestorePlanItem( + rel_path=member.name, + abs_path=target_dest_path, + action="modify", + reason="File content differs from snapshot", + is_sensitive_network=is_net, + source_sha256=expected_sha, + target_sha256=target_sha + )) + else: + plan_items.append(RestorePlanItem( + rel_path=member.name, + abs_path=target_dest_path, + action="modify", + reason="Target exists as non-regular file", + is_sensitive_network=is_net, + source_sha256=expected_sha, + target_sha256=None + )) + + return RestorePlan( + snapshot_id=manifest.snapshot_id, + target_root=target_root_clean, + items=plan_items, + requires_force=True + ) + + def create_safety_snapshot(self, target_root: str = "/") -> Tuple[str, str]: + """ + Create a pre-restore safety snapshot of /etc before any file modifications. + Returns (snapshot_id, archive_path). + """ + hostname = socket.gethostname().split(".")[0] + timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") + safety_id = f"pre_restore_{hostname}_{timestamp}" + + etc_path = os.path.join(os.path.abspath(target_root), "etc") + included_paths = [etc_path] if os.path.isdir(etc_path) else ["/etc"] + + archiver = SnapshotArchiver(target_dir=self.target_dir, compression="gzip") + file_entries, files_sha256, uncompressed_bytes, _ = archiver.collect_file_list(included_paths) + + manifest = SnapshotManifest( + schema_version="1.0", + snapshot_id=safety_id, + created_at=datetime.datetime.now(datetime.timezone.utc).isoformat(), + hostname=socket.gethostname(), + profile="safety_pre_restore", + compression="gzip", + os=detect_distro().to_dict(), + package_manager="none", + package_count=0, + included_paths=included_paths, + stats={ + "file_count": len(file_entries), + "uncompressed_bytes": uncompressed_bytes, + "compressed_bytes": 0 + }, + files_sha256=files_sha256 + ) + + archive_path = archiver.create_snapshot_archive(safety_id, manifest, file_entries) + + # Verify safety snapshot integrity immediately + valid, msg = SnapshotArchiver.verify_archive(archive_path) + if not valid: + raise RuntimeError(f"Safety snapshot failed integrity check: {msg}") + + return safety_id, archive_path + + def execute_restore( + self, + plan: RestorePlan, + force: bool = False, + pid_path: Optional[str] = None + ) -> Dict[str, Any]: + """ + Execute file restoration based on RestorePlan. + If force=False: raises DryRunException (exit code 5). + If force=True: creates safety snapshot, atomically restores files, runs restorecon on SELinux. + """ + if not force: + raise DryRunException(plan) + + lock = SingleInstanceLock(pid_path=pid_path) + lock.acquire() + + restored_files: List[str] = [] + restored_dirs: set = set() + safety_id = None + safety_path = None + + try: + # 1. Capture unalterable pre-restore safety snapshot + safety_id, safety_path = self.create_safety_snapshot(target_root=plan.target_root) + plan.safety_snapshot_id = safety_id + + archive_path = self._resolve_archive(plan.snapshot_id) + + with tarfile.open(archive_path, "r:*") as tar: + for item in plan.items: + if item.action not in ("create", "modify"): + continue + + # Zip slip security check + dest_abs = os.path.abspath(item.abs_path) + if not dest_abs.startswith(plan.target_root): + raise SecurityError(f"Zip slip path traversal detected: {dest_abs} outside {plan.target_root}") + + member = tar.getmember(item.rel_path) + dest_dir = os.path.dirname(dest_abs) + os.makedirs(dest_dir, exist_ok=True) + restored_dirs.add(dest_dir) + + if member.isreg(): + f_in = tar.extractfile(member) + if not f_in: + continue + + tmp_dest = f"{dest_abs}.tmp.{os.getpid()}" + try: + with open(tmp_dest, "wb") as f_out: + while chunk := f_in.read(BUFFER_SIZE): + f_out.write(chunk) + + # Apply permissions + try: + os.chmod(tmp_dest, member.mode) + except OSError: + pass + + # Apply ownership if root + if os.geteuid() == 0: + try: + os.chown(tmp_dest, member.uid, member.gid) + except OSError: + pass + + # Atomic replacement + os.replace(tmp_dest, dest_abs) + restored_files.append(dest_abs) + finally: + if os.path.exists(tmp_dest): + try: + os.unlink(tmp_dest) + except OSError: + pass + + elif member.issym(): + # Symlink restoration + tmp_link = f"{dest_abs}.tmp.{os.getpid()}" + try: + if os.path.lexists(tmp_link): + os.unlink(tmp_link) + os.symlink(member.linkname, tmp_link) + os.replace(tmp_link, dest_abs) + restored_files.append(dest_abs) + finally: + if os.path.lexists(tmp_link): + try: + os.unlink(tmp_link) + except OSError: + pass + + # 2. SELinux context restoration + selinux_restored = False + if os.path.exists("/sys/fs/selinux") and shutil.which("restorecon"): + for d in restored_dirs: + try: + subprocess.run(["restorecon", "-R", d], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + except Exception: + pass + selinux_restored = True + + return { + "status": "success", + "snapshot_id": plan.snapshot_id, + "safety_snapshot_id": safety_id, + "safety_archive_path": safety_path, + "restored_count": len(restored_files), + "restored_files": restored_files, + "selinux_context_restored": selinux_restored + } + + finally: + lock.release() diff --git a/linux_backuper/models.py b/linux_backuper/models.py index 94c0d21..e60956b 100644 --- a/linux_backuper/models.py +++ b/linux_backuper/models.py @@ -113,3 +113,40 @@ class SnapshotManifest: stats=data.get("stats", {}), files_sha256=data.get("files_sha256", {}) ) + +@dataclass +class RestorePlanItem: + rel_path: str + abs_path: str + action: str # "create", "modify", "skip" + reason: Optional[str] = None + is_sensitive_network: bool = False + source_sha256: Optional[str] = None + target_sha256: Optional[str] = None + + def to_dict(self) -> Dict[str, Any]: + return asdict(self) + +@dataclass +class RestorePlan: + snapshot_id: str + target_root: str + items: List[RestorePlanItem] = field(default_factory=list) + safety_snapshot_id: Optional[str] = None + requires_force: bool = True + + def to_dict(self) -> Dict[str, Any]: + return { + "snapshot_id": self.snapshot_id, + "target_root": self.target_root, + "items": [item.to_dict() for item in self.items], + "safety_snapshot_id": self.safety_snapshot_id, + "requires_force": self.requires_force, + "summary": { + "create_count": sum(1 for i in self.items if i.action == "create"), + "modify_count": sum(1 for i in self.items if i.action == "modify"), + "skip_count": sum(1 for i in self.items if i.action == "skip"), + "sensitive_network_count": sum(1 for i in self.items if i.is_sensitive_network) + } + } + diff --git a/tests/test_cli.py b/tests/test_cli.py index 13b7d0c..1c0885b 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -9,7 +9,7 @@ import unittest from unittest.mock import patch from linux_backuper.cli import main -from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_CORRUPTED +from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_CORRUPTED, EXIT_DRY_RUN class TestCliTracerBullet(unittest.TestCase): def setUp(self): @@ -181,5 +181,120 @@ class TestCliTracerBullet(unittest.TestCase): exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir]) self.assertEqual(exit_code, EXIT_SUCCESS) + def test_show_command(self): + stdout = io.StringIO() + with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}): + main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"]) + snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"] + + # Text mode + stdout_show = io.StringIO() + with patch("sys.stdout", stdout_show): + exit_code = main(["show", snap_id, "--target-dir", self.backup_dir]) + self.assertEqual(exit_code, EXIT_SUCCESS) + self.assertIn("Snapshot ID:", stdout_show.getvalue()) + self.assertIn(snap_id, stdout_show.getvalue()) + + # JSON mode + stdout_json = io.StringIO() + with patch("sys.stdout", stdout_json): + exit_code = main(["show", snap_id, "--target-dir", self.backup_dir, "--json"]) + self.assertEqual(exit_code, EXIT_SUCCESS) + data = json.loads(stdout_json.getvalue().strip()) + self.assertEqual(data["snapshot_id"], snap_id) + + def test_extract_command(self): + stdout = io.StringIO() + with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}): + main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"]) + snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"] + + dest_file = os.path.join(self.temp_dir, "extracted_hostname.txt") + # Extract filename + sample_path = [f for f in os.listdir(self.mock_etc) if f == "hostname"][0] + exit_code = main([ + "extract", snap_id, + "--file", sample_path, + "--out", dest_file, + "--target-dir", self.backup_dir + ]) + self.assertEqual(exit_code, EXIT_SUCCESS) + self.assertTrue(os.path.isfile(dest_file)) + with open(dest_file, "r") as f: + self.assertEqual(f.read(), "test-host.local\n") + + def test_diff_command(self): + stdout = io.StringIO() + with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}): + main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"]) + snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"] + + # Modify sample.conf on mock etc + with open(os.path.join(self.mock_etc, "sample.conf"), "w") as f: + f.write("key=modified_value\n") + + # Test live diff + stdout_diff = io.StringIO() + with patch("sys.stdout", stdout_diff): + exit_code = main([ + "diff", snap_id, + "--target-dir", self.backup_dir, + "--target-root", self.temp_dir, + "--json" + ]) + self.assertEqual(exit_code, EXIT_SUCCESS) + diff_data = json.loads(stdout_diff.getvalue().strip()) + self.assertEqual(diff_data["type"], "live_vs_snapshot") + self.assertTrue(any("sample.conf" in f for f in diff_data["files"]["modified"])) + + def test_restore_dry_run_exits_with_code_5(self): + stdout = io.StringIO() + with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}): + main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"]) + snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"] + + # Default restore (no --force) must return EXIT_DRY_RUN (5) + stdout_restore = io.StringIO() + with patch("sys.stdout", stdout_restore): + exit_code = main([ + "restore", snap_id, + "--target-dir", self.backup_dir, + "--target-root", self.temp_dir + ]) + self.assertEqual(exit_code, EXIT_DRY_RUN) + self.assertIn("RESTORE EXECUTION PLAN (Dry Run)", stdout_restore.getvalue()) + + def test_restore_force_executes_successfully(self): + stdout = io.StringIO() + with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}): + main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"]) + snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"] + + # Alter sample.conf + with open(os.path.join(self.mock_etc, "sample.conf"), "w") as f: + f.write("key=tampered_value\n") + + # Restore with --force and non-root test override + pid_file = os.path.join(self.temp_dir, "restore_test.pid") + stdout_restore = io.StringIO() + with patch("sys.stdout", stdout_restore), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}): + exit_code = main([ + "restore", snap_id, + "--force", + "--target-dir", self.backup_dir, + "--target-root", self.temp_dir, + "--pid-path", pid_file, + "--json" + ]) + self.assertEqual(exit_code, EXIT_SUCCESS) + res = json.loads(stdout_restore.getvalue().strip()) + self.assertEqual(res["status"], "success") + self.assertTrue(res["safety_snapshot_id"].startswith("pre_restore_")) + + # Check sample.conf restored + with open(os.path.join(self.mock_etc, "sample.conf"), "r") as f: + self.assertEqual(f.read(), "key=value\n") + if __name__ == "__main__": unittest.main() + diff --git a/tests/test_diff.py b/tests/test_diff.py new file mode 100644 index 0000000..892e5c5 --- /dev/null +++ b/tests/test_diff.py @@ -0,0 +1,140 @@ +"""Unit tests for DiffEngine.""" + +import os +import shutil +import tempfile +import unittest +from unittest.mock import patch + +from linux_backuper.core.archiver import SnapshotArchiver +from linux_backuper.core.diff import DiffEngine +from linux_backuper.models import SnapshotManifest + +class TestDiffEngine(unittest.TestCase): + def setUp(self): + self.test_dir = tempfile.mkdtemp(prefix="test_diff_") + self.backup_dir = os.path.join(self.test_dir, "backups") + os.makedirs(self.backup_dir, exist_ok=True) + + self.mock_root = os.path.join(self.test_dir, "root") + self.mock_etc = os.path.join(self.mock_root, "etc") + os.makedirs(self.mock_etc, exist_ok=True) + + # File A + with open(os.path.join(self.mock_etc, "hosts"), "w") as f: + f.write("127.0.0.1 localhost\n") + # File B + with open(os.path.join(self.mock_etc, "issue"), "w") as f: + f.write("Test Linux\n") + + # Snapshot 1 + archiver = SnapshotArchiver(target_dir=self.backup_dir) + entries1, sha1, bytes1, _ = archiver.collect_file_list([self.mock_etc]) + + # Write fake meta/packages.txt into archive + temp_meta = os.path.join(self.test_dir, "meta1") + os.makedirs(temp_meta, exist_ok=True) + pkg_file1 = os.path.join(temp_meta, "packages.txt") + with open(pkg_file1, "w") as f: + f.write("bash 5.1.0\ncoreutils 8.32\ncurl 7.74.0\n") + + entries1.append((pkg_file1, "meta/packages.txt")) + sha1["meta/packages.txt"] = "dummy" + + m1 = SnapshotManifest( + schema_version="1.0", + snapshot_id="snap1", + created_at="2026-10-01T12:00:00Z", + hostname="host1", + profile="quick", + compression="gzip", + os={"distro_id": "debian", "distro_name": "Debian", "version_id": "12", "kernel": "6.1", "arch": "x86_64"}, + package_manager="dpkg", + package_count=3, + included_paths=[self.mock_etc], + stats={"file_count": len(entries1), "uncompressed_bytes": bytes1, "compressed_bytes": 0}, + files_sha256=sha1 + ) + self.archive1 = archiver.create_snapshot_archive("snap1", m1, entries1) + + # Modify file A, delete file B, add file C for Snapshot 2 + with open(os.path.join(self.mock_etc, "hosts"), "w") as f: + f.write("127.0.0.1 localhost\n192.168.1.1 router\n") + os.remove(os.path.join(self.mock_etc, "issue")) + with open(os.path.join(self.mock_etc, "resolv.conf"), "w") as f: + f.write("nameserver 1.1.1.1\n") + + entries2, sha2, bytes2, _ = archiver.collect_file_list([self.mock_etc]) + + temp_meta2 = os.path.join(self.test_dir, "meta2") + os.makedirs(temp_meta2, exist_ok=True) + pkg_file2 = os.path.join(temp_meta2, "packages.txt") + with open(pkg_file2, "w") as f: + f.write("bash 5.2.0\ncoreutils 8.32\nwget 1.21\n") # bash upgraded, curl removed, wget added + + entries2.append((pkg_file2, "meta/packages.txt")) + sha2["meta/packages.txt"] = "dummy2" + + m2 = SnapshotManifest( + schema_version="1.0", + snapshot_id="snap2", + created_at="2026-10-02T12:00:00Z", + hostname="host1", + profile="quick", + compression="gzip", + os={"distro_id": "debian", "distro_name": "Debian", "version_id": "12", "kernel": "6.1", "arch": "x86_64"}, + package_manager="dpkg", + package_count=3, + included_paths=[self.mock_etc], + stats={"file_count": len(entries2), "uncompressed_bytes": bytes2, "compressed_bytes": 0}, + files_sha256=sha2 + ) + self.archive2 = archiver.create_snapshot_archive("snap2", m2, entries2) + + def tearDown(self): + shutil.rmtree(self.test_dir, ignore_errors=True) + + def test_diff_snapshots(self): + engine = DiffEngine(target_dir=self.backup_dir) + res = engine.diff_snapshots("snap1", "snap2") + + self.assertEqual(res["type"], "snapshot_vs_snapshot") + self.assertEqual(res["snapshot_1"], "snap1") + self.assertEqual(res["snapshot_2"], "snap2") + + files = res["files"] + # hosts is modified + self.assertTrue(any("hosts" in f for f in files["modified"])) + # resolv.conf is added + self.assertTrue(any("resolv.conf" in f for f in files["added"])) + # issue is removed + self.assertTrue(any("issue" in f for f in files["removed"])) + + # Check packages + pkgs = res["packages"] + self.assertIn("wget", pkgs["added"]) + self.assertIn("curl", pkgs["removed"]) + self.assertIn("bash", pkgs["changed"]) + self.assertEqual(pkgs["changed"]["bash"]["old"], "5.1.0") + self.assertEqual(pkgs["changed"]["bash"]["new"], "5.2.0") + + def test_diff_with_live(self): + engine = DiffEngine(target_dir=self.backup_dir) + # Compare live mock_root against snap1 + # Currently mock_root has modified hosts, deleted issue, added resolv.conf + res = engine.diff_with_live("snap1", target_root=self.mock_root) + + self.assertEqual(res["type"], "live_vs_snapshot") + files = res["files"] + self.assertTrue(any("hosts" in f for f in files["modified"])) + self.assertTrue(any("issue" in f for f in files["missing_on_live"])) + self.assertTrue(any("resolv.conf" in f for f in files["added_on_live"])) + + def test_generate_unified_file_diff(self): + engine = DiffEngine(target_dir=self.backup_dir) + diff_text = engine.generate_unified_file_diff("snap1", "etc/hosts", target_root=self.mock_root) + self.assertIsNotNone(diff_text) + self.assertIn("+192.168.1.1 router", diff_text) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_restore.py b/tests/test_restore.py new file mode 100644 index 0000000..4a597f2 --- /dev/null +++ b/tests/test_restore.py @@ -0,0 +1,131 @@ +"""Unit tests for SafeRestoreEngine.""" + +import os +import shutil +import tempfile +import unittest +from unittest.mock import patch + +from linux_backuper.core.archiver import SnapshotArchiver +from linux_backuper.core.restore import SafeRestoreEngine, DryRunException +from linux_backuper.models import SnapshotManifest + +class TestSafeRestoreEngine(unittest.TestCase): + def setUp(self): + self.test_dir = tempfile.mkdtemp(prefix="test_restore_") + self.backup_dir = os.path.join(self.test_dir, "backups") + os.makedirs(self.backup_dir, exist_ok=True) + + self.mock_root = os.path.join(self.test_dir, "root") + self.mock_etc = os.path.join(self.mock_root, "etc") + os.makedirs(self.mock_etc, exist_ok=True) + + # Create files to back up + self.hosts_path = os.path.join(self.mock_etc, "hosts") + with open(self.hosts_path, "w") as f: + f.write("127.0.0.1 localhost\n") + + self.resolv_path = os.path.join(self.mock_etc, "resolv.conf") + with open(self.resolv_path, "w") as f: + f.write("nameserver 8.8.8.8\n") + + self.fstab_path = os.path.join(self.mock_etc, "fstab") + with open(self.fstab_path, "w") as f: + f.write("/dev/sda1 / ext4 defaults 0 1\n") + + # Create netplan file (sensitive network) + self.netplan_dir = os.path.join(self.mock_etc, "netplan") + os.makedirs(self.netplan_dir, exist_ok=True) + self.net_cfg = os.path.join(self.netplan_dir, "01-netcfg.yaml") + with open(self.net_cfg, "w") as f: + f.write("network: {version: 2}\n") + + # Create base snapshot + archiver = SnapshotArchiver(target_dir=self.backup_dir) + entries, sha, uncompressed, _ = archiver.collect_file_list([self.mock_etc]) + + m = SnapshotManifest( + schema_version="1.0", + snapshot_id="test_snap", + created_at="2026-10-01T12:00:00Z", + hostname="host1", + profile="quick", + compression="gzip", + os={"distro_id": "debian", "distro_name": "Debian", "version_id": "12", "kernel": "6.1", "arch": "x86_64"}, + package_manager="dpkg", + package_count=0, + included_paths=[self.mock_etc], + stats={"file_count": len(entries), "uncompressed_bytes": uncompressed, "compressed_bytes": 0}, + files_sha256=sha + ) + self.archive_path = archiver.create_snapshot_archive("test_snap", m, entries) + + def tearDown(self): + shutil.rmtree(self.test_dir, ignore_errors=True) + + def test_plan_restore_skips_dynamic_and_fstab(self): + engine = SafeRestoreEngine(target_dir=self.backup_dir) + plan = engine.plan_restore("test_snap", target_root=self.mock_root, include_fstab=False) + + actions_by_path = {item.rel_path: item for item in plan.items} + + # resolv.conf must be skipped (dynamic system file) + resolv_item = [item for item in plan.items if "resolv.conf" in item.rel_path][0] + self.assertEqual(resolv_item.action, "skip") + self.assertIn("volatile", resolv_item.reason.lower()) + + # fstab must be skipped unless include_fstab is set + fstab_item = [item for item in plan.items if "fstab" in item.rel_path][0] + self.assertEqual(fstab_item.action, "skip") + self.assertIn("fstab", fstab_item.reason.lower()) + + # netplan must be flagged as sensitive network + net_item = [item for item in plan.items if "01-netcfg.yaml" in item.rel_path][0] + self.assertTrue(net_item.is_sensitive_network) + + def test_dry_run_raises_and_modifies_nothing(self): + # Modify hosts on mock_root + with open(self.hosts_path, "w") as f: + f.write("corrupted hosts content\n") + + engine = SafeRestoreEngine(target_dir=self.backup_dir) + plan = engine.plan_restore("test_snap", target_root=self.mock_root) + + with self.assertRaises(DryRunException): + engine.execute_restore(plan, force=False) + + # Verify hosts content was NOT modified + with open(self.hosts_path, "r") as f: + self.assertEqual(f.read(), "corrupted hosts content\n") + + def test_execute_restore_with_force_creates_safety_snapshot_and_restores(self): + # Corrupt hosts + with open(self.hosts_path, "w") as f: + f.write("corrupted content\n") + + # Delete netplan config + os.remove(self.net_cfg) + + engine = SafeRestoreEngine(target_dir=self.backup_dir) + plan = engine.plan_restore("test_snap", target_root=self.mock_root) + + # Allow non-root flock fallback + pid_file = os.path.join(self.test_dir, "test.pid") + with patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}): + res = engine.execute_restore(plan, force=True, pid_path=pid_file) + + self.assertEqual(res["status"], "success") + self.assertTrue(res["safety_snapshot_id"].startswith("pre_restore_")) + self.assertTrue(os.path.isfile(res["safety_archive_path"])) + + # Verify hosts restored + with open(self.hosts_path, "r") as f: + self.assertEqual(f.read(), "127.0.0.1 localhost\n") + + # Verify netplan recreated + self.assertTrue(os.path.isfile(self.net_cfg)) + with open(self.net_cfg, "r") as f: + self.assertEqual(f.read(), "network: {version: 2}\n") + +if __name__ == "__main__": + unittest.main()