- Refactor tests to achieve 100% Zero-Mocks compliance (remove unittest.mock, add tests.helpers.env_override and stdlib redirects) - Extract testable parsing methods in package managers and inspector - Add tests/test_security.py with 5 negative AppSec test cases (Zip Slip, Root Gate, Tampering SHA-256, Secret Sanitization, and AST check for zero shell=True) - Expand is_sanitized_target to redact all private SSH/TLS keys (*.key, *.pem, id_*) - Split Gitea CI/CD pipelines into test-and-lint.yaml and build-and-release.yaml - Add .gitleaks.toml configuration - Formally close v1.0.0 genesis plan in docs/plans/linux-backuper/00-status.md as immutable ADR - Bump version to v2.0.0 across __init__.py, man page, tests, and documentation
301 lines
13 KiB
Python
301 lines
13 KiB
Python
from contextlib import redirect_stdout
|
|
import io
|
|
import json
|
|
import os
|
|
import stat
|
|
import sys
|
|
import tarfile
|
|
import tempfile
|
|
import unittest
|
|
|
|
from linux_backuper.cli import main
|
|
from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_CORRUPTED, EXIT_DRY_RUN
|
|
from tests.helpers import env_override
|
|
|
|
class TestCliTracerBullet(unittest.TestCase):
|
|
def setUp(self):
|
|
self.temp_dir = tempfile.mkdtemp(prefix="test_linux_backuper_")
|
|
self.backup_dir = os.path.join(self.temp_dir, "backups")
|
|
os.makedirs(self.backup_dir, exist_ok=True)
|
|
# Mock etc directory with dummy file
|
|
self.mock_etc = os.path.join(self.temp_dir, "etc")
|
|
os.makedirs(self.mock_etc, exist_ok=True)
|
|
with open(os.path.join(self.mock_etc, "hostname"), "w") as f:
|
|
f.write("test-host.local\n")
|
|
with open(os.path.join(self.mock_etc, "sample.conf"), "w") as f:
|
|
f.write("key=value\n")
|
|
|
|
def tearDown(self):
|
|
import shutil
|
|
shutil.rmtree(self.temp_dir, ignore_errors=True)
|
|
|
|
def test_version_flag(self):
|
|
stdout = io.StringIO()
|
|
with redirect_stdout(stdout):
|
|
with self.assertRaises(SystemExit) as cm:
|
|
main(["--version"])
|
|
self.assertEqual(cm.exception.code, EXIT_SUCCESS)
|
|
self.assertIn("2.0.0", stdout.getvalue())
|
|
|
|
def test_help_flag(self):
|
|
stdout = io.StringIO()
|
|
with redirect_stdout(stdout):
|
|
with self.assertRaises(SystemExit) as cm:
|
|
main(["--help"])
|
|
self.assertEqual(cm.exception.code, EXIT_SUCCESS)
|
|
self.assertIn("linux-backuper", stdout.getvalue())
|
|
self.assertIn("snapshot", stdout.getvalue())
|
|
|
|
def test_snapshot_tracer_bullet_creates_archive(self):
|
|
stdout = io.StringIO()
|
|
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
|
exit_code = main([
|
|
"snapshot",
|
|
"--target-dir", self.backup_dir,
|
|
"--paths", self.mock_etc,
|
|
"--profile", "quick",
|
|
"--json"
|
|
])
|
|
self.assertEqual(exit_code, EXIT_SUCCESS)
|
|
|
|
output_data = json.loads(stdout.getvalue().strip())
|
|
self.assertIn("snapshot_id", output_data)
|
|
self.assertIn("archive_path", output_data)
|
|
|
|
archive_path = output_data["archive_path"]
|
|
self.assertTrue(os.path.exists(archive_path))
|
|
|
|
# Check file permissions (0600 on POSIX)
|
|
file_mode = stat.S_IMODE(os.stat(archive_path).st_mode)
|
|
self.assertEqual(file_mode, 0o600)
|
|
|
|
# Verify tar members: manifest.json MUST be the very first member
|
|
with tarfile.open(archive_path, "r:gz") as tar:
|
|
members = tar.getmembers()
|
|
self.assertGreater(len(members), 0)
|
|
self.assertEqual(members[0].name, "manifest.json")
|
|
|
|
# Extract manifest and verify structure
|
|
manifest_file = tar.extractfile(members[0])
|
|
manifest = json.loads(manifest_file.read().decode("utf-8"))
|
|
self.assertEqual(manifest["snapshot_id"], output_data["snapshot_id"])
|
|
self.assertEqual(manifest["profile"], "quick")
|
|
self.assertIn("os", manifest)
|
|
self.assertIn("files_sha256", manifest)
|
|
|
|
def test_list_command(self):
|
|
# First create a snapshot
|
|
with redirect_stdout(io.StringIO()), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
|
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc])
|
|
|
|
# Now test listing
|
|
stdout = io.StringIO()
|
|
with redirect_stdout(stdout):
|
|
exit_code = main(["list", "--target-dir", self.backup_dir, "--json"])
|
|
self.assertEqual(exit_code, EXIT_SUCCESS)
|
|
|
|
listed = json.loads(stdout.getvalue().strip())
|
|
self.assertEqual(len(listed), 1)
|
|
self.assertIn("snapshot_id", listed[0])
|
|
self.assertEqual(listed[0]["profile"], "quick")
|
|
|
|
def test_verify_command(self):
|
|
stdout = io.StringIO()
|
|
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
|
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
|
|
snap_data = json.loads(stdout.getvalue().strip())
|
|
snap_id = snap_data["snapshot_id"]
|
|
|
|
# Verify should succeed on untouched archive
|
|
with redirect_stdout(io.StringIO()):
|
|
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
|
|
self.assertEqual(exit_code, EXIT_SUCCESS)
|
|
|
|
# Corrupt archive CRC
|
|
archive_path = snap_data["archive_path"]
|
|
with open(archive_path, "r+b") as f:
|
|
f.seek(-4, os.SEEK_END)
|
|
f.write(b"\x00\x00\x00\x00")
|
|
|
|
# Verify should detect corruption and return EXIT_CORRUPTED (3)
|
|
with redirect_stdout(io.StringIO()):
|
|
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
|
|
self.assertEqual(exit_code, EXIT_CORRUPTED)
|
|
|
|
def test_snapshot_sanitize_redacts_secrets(self):
|
|
# Create sensitive files in mock_etc
|
|
shadow_path = os.path.join(self.mock_etc, "shadow")
|
|
with open(shadow_path, "w") as f:
|
|
f.write("root:$6$secretpasswordhash:19000:0:99999:7:::\n")
|
|
ssh_key_path = os.path.join(self.mock_etc, "ssh_host_ed25519_key")
|
|
with open(ssh_key_path, "w") as f:
|
|
f.write("-----BEGIN OPENSSH PRIVATE KEY-----\nsecret\n-----END OPENSSH PRIVATE KEY-----\n")
|
|
|
|
stdout = io.StringIO()
|
|
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
|
exit_code = main([
|
|
"snapshot",
|
|
"--target-dir", self.backup_dir,
|
|
"--paths", self.mock_etc,
|
|
"--sanitize",
|
|
"--json"
|
|
])
|
|
self.assertEqual(exit_code, EXIT_SUCCESS)
|
|
|
|
snap_data = json.loads(stdout.getvalue().strip())
|
|
archive_path = snap_data["archive_path"]
|
|
|
|
with tarfile.open(archive_path, "r:gz") as tar:
|
|
names = tar.getnames()
|
|
# Sensitive files must NOT be in archive data/
|
|
self.assertFalse(any("data" in n and "shadow" in n for n in names))
|
|
self.assertFalse(any("data" in n and "ssh_host_ed25519_key" in n for n in names))
|
|
# meta/sanitized.txt must exist and list them
|
|
self.assertIn("meta/sanitized.txt", names)
|
|
sanitized_log = tar.extractfile("meta/sanitized.txt").read().decode("utf-8")
|
|
self.assertIn("shadow", sanitized_log)
|
|
self.assertIn("ssh_host_ed25519_key", sanitized_log)
|
|
|
|
def test_snapshot_no_compression(self):
|
|
stdout = io.StringIO()
|
|
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
|
exit_code = main([
|
|
"snapshot",
|
|
"--target-dir", self.backup_dir,
|
|
"--paths", self.mock_etc,
|
|
"--no-compression",
|
|
"--json"
|
|
])
|
|
self.assertEqual(exit_code, EXIT_SUCCESS)
|
|
|
|
snap_data = json.loads(stdout.getvalue().strip())
|
|
archive_path = snap_data["archive_path"]
|
|
self.assertTrue(archive_path.endswith(".tar"))
|
|
|
|
# Verify it is openable as uncompressed tar
|
|
with tarfile.open(archive_path, "r:") as tar:
|
|
self.assertEqual(tar.getmembers()[0].name, "manifest.json")
|
|
|
|
# Verify command works on uncompressed tar
|
|
snap_id = snap_data["snapshot_id"]
|
|
with redirect_stdout(io.StringIO()):
|
|
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 redirect_stdout(stdout), env_override({"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 redirect_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 redirect_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 redirect_stdout(stdout), env_override({"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 redirect_stdout(stdout), env_override({"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 redirect_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 redirect_stdout(stdout), env_override({"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 redirect_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 redirect_stdout(stdout), env_override({"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 redirect_stdout(stdout_restore), env_override({"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()
|