feat: modernize to Software Factory standards, add AppSec suite, and bump to v2.0.0
- 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
This commit is contained in:
1 parent
3e5f2ab498
commit
4b3346fd74
22 files changed
+577
-203
No files matched your search
@@ -0,0 +1,21 @@
|
||||
"""Test helpers providing pure standard library utilities without mocks."""
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
from typing import Dict, Iterator, Optional
|
||||
|
||||
@contextlib.contextmanager
|
||||
def env_override(env_dict: Dict[str, str]) -> Iterator[None]:
|
||||
"""Context manager to safely override environment variables and restore original state."""
|
||||
original: Dict[str, Optional[str]] = {}
|
||||
for key, value in env_dict.items():
|
||||
original[key] = os.environ.get(key)
|
||||
os.environ[key] = value
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for key, orig_val in original.items():
|
||||
if orig_val is None:
|
||||
os.environ.pop(key, None)
|
||||
else:
|
||||
os.environ[key] = orig_val
|
||||
+24
-24
@@ -1,3 +1,4 @@
|
||||
from contextlib import redirect_stdout
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
@@ -6,10 +7,10 @@ import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
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):
|
||||
@@ -30,15 +31,15 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
|
||||
def test_version_flag(self):
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout):
|
||||
with redirect_stdout(stdout):
|
||||
with self.assertRaises(SystemExit) as cm:
|
||||
main(["--version"])
|
||||
self.assertEqual(cm.exception.code, EXIT_SUCCESS)
|
||||
self.assertIn("1.0.0", stdout.getvalue())
|
||||
self.assertIn("2.0.0", stdout.getvalue())
|
||||
|
||||
def test_help_flag(self):
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout):
|
||||
with redirect_stdout(stdout):
|
||||
with self.assertRaises(SystemExit) as cm:
|
||||
main(["--help"])
|
||||
self.assertEqual(cm.exception.code, EXIT_SUCCESS)
|
||||
@@ -47,7 +48,7 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
|
||||
def test_snapshot_tracer_bullet_creates_archive(self):
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
exit_code = main([
|
||||
"snapshot",
|
||||
"--target-dir", self.backup_dir,
|
||||
@@ -84,12 +85,12 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
|
||||
def test_list_command(self):
|
||||
# First create a snapshot
|
||||
with patch("sys.stdout", io.StringIO()), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
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 patch("sys.stdout", stdout):
|
||||
with redirect_stdout(stdout):
|
||||
exit_code = main(["list", "--target-dir", self.backup_dir, "--json"])
|
||||
self.assertEqual(exit_code, EXIT_SUCCESS)
|
||||
|
||||
@@ -100,13 +101,13 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
|
||||
def test_verify_command(self):
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
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 patch("sys.stdout", io.StringIO()):
|
||||
with redirect_stdout(io.StringIO()):
|
||||
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
|
||||
self.assertEqual(exit_code, EXIT_SUCCESS)
|
||||
|
||||
@@ -117,7 +118,7 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
f.write(b"\x00\x00\x00\x00")
|
||||
|
||||
# Verify should detect corruption and return EXIT_CORRUPTED (3)
|
||||
with patch("sys.stdout", io.StringIO()):
|
||||
with redirect_stdout(io.StringIO()):
|
||||
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
|
||||
self.assertEqual(exit_code, EXIT_CORRUPTED)
|
||||
|
||||
@@ -131,7 +132,7 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
f.write("-----BEGIN OPENSSH PRIVATE KEY-----\nsecret\n-----END OPENSSH PRIVATE KEY-----\n")
|
||||
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
exit_code = main([
|
||||
"snapshot",
|
||||
"--target-dir", self.backup_dir,
|
||||
@@ -157,7 +158,7 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
|
||||
def test_snapshot_no_compression(self):
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
exit_code = main([
|
||||
"snapshot",
|
||||
"--target-dir", self.backup_dir,
|
||||
@@ -177,19 +178,19 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
|
||||
# Verify command works on uncompressed tar
|
||||
snap_id = snap_data["snapshot_id"]
|
||||
with patch("sys.stdout", io.StringIO()):
|
||||
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 patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
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 patch("sys.stdout", stdout_show):
|
||||
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())
|
||||
@@ -197,7 +198,7 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
|
||||
# JSON mode
|
||||
stdout_json = io.StringIO()
|
||||
with patch("sys.stdout", stdout_json):
|
||||
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())
|
||||
@@ -205,7 +206,7 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
|
||||
def test_extract_command(self):
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
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"]
|
||||
|
||||
@@ -225,7 +226,7 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
|
||||
def test_diff_command(self):
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
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"]
|
||||
|
||||
@@ -235,7 +236,7 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
|
||||
# Test live diff
|
||||
stdout_diff = io.StringIO()
|
||||
with patch("sys.stdout", stdout_diff):
|
||||
with redirect_stdout(stdout_diff):
|
||||
exit_code = main([
|
||||
"diff", snap_id,
|
||||
"--target-dir", self.backup_dir,
|
||||
@@ -249,13 +250,13 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
|
||||
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"}):
|
||||
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 patch("sys.stdout", stdout_restore):
|
||||
with redirect_stdout(stdout_restore):
|
||||
exit_code = main([
|
||||
"restore", snap_id,
|
||||
"--target-dir", self.backup_dir,
|
||||
@@ -266,7 +267,7 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
|
||||
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"}):
|
||||
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"]
|
||||
|
||||
@@ -277,7 +278,7 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
# 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"}):
|
||||
with redirect_stdout(stdout_restore), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
exit_code = main([
|
||||
"restore", snap_id,
|
||||
"--force",
|
||||
@@ -297,4 +298,3 @@ class TestCliTracerBullet(unittest.TestCase):
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""Unit tests for shell completions and CLI help."""
|
||||
|
||||
from contextlib import redirect_stdout
|
||||
import io
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from linux_backuper.cli import main
|
||||
from linux_backuper.core.completions import generate_completion
|
||||
@@ -29,7 +29,7 @@ class TestCompletions(unittest.TestCase):
|
||||
|
||||
def test_cli_completion_subcommand_bash(self):
|
||||
stdout_buf = io.StringIO()
|
||||
with patch("sys.stdout", stdout_buf):
|
||||
with redirect_stdout(stdout_buf):
|
||||
code = main(["completion", "bash"])
|
||||
self.assertEqual(code, 0)
|
||||
out = stdout_buf.getvalue()
|
||||
@@ -37,7 +37,7 @@ class TestCompletions(unittest.TestCase):
|
||||
|
||||
def test_cli_completion_subcommand_zsh(self):
|
||||
stdout_buf = io.StringIO()
|
||||
with patch("sys.stdout", stdout_buf):
|
||||
with redirect_stdout(stdout_buf):
|
||||
code = main(["completion", "zsh"])
|
||||
self.assertEqual(code, 0)
|
||||
out = stdout_buf.getvalue()
|
||||
@@ -45,7 +45,7 @@ class TestCompletions(unittest.TestCase):
|
||||
|
||||
def test_cli_help(self):
|
||||
stdout_buf = io.StringIO()
|
||||
with patch("sys.stdout", stdout_buf):
|
||||
with redirect_stdout(stdout_buf):
|
||||
with self.assertRaises(SystemExit) as cm:
|
||||
main(["--help"])
|
||||
self.assertEqual(cm.exception.code, 0)
|
||||
|
||||
@@ -4,7 +4,6 @@ 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
|
||||
|
||||
+72
-75
@@ -2,7 +2,6 @@ import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
from linux_backuper.models import PackageItem, StorageState, NetworkState
|
||||
from linux_backuper.managers.base import BasePackageManager
|
||||
@@ -17,44 +16,38 @@ class TestPackageManagerAdapters(unittest.TestCase):
|
||||
coreutils|8.32-35.el9|x86_64
|
||||
systemd|252-32.el9_4.6|x86_64
|
||||
"""
|
||||
with patch("subprocess.run") as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=0, stdout=sample_output, stderr="")
|
||||
mgr = RpmPackageManager()
|
||||
packages = mgr.list_packages()
|
||||
mgr = RpmPackageManager()
|
||||
packages = mgr.parse_package_output(sample_output)
|
||||
|
||||
self.assertEqual(len(packages), 3)
|
||||
self.assertEqual(packages[0].name, "bash")
|
||||
self.assertEqual(packages[0].version, "5.1.8-9.el9")
|
||||
self.assertEqual(packages[0].arch, "x86_64")
|
||||
self.assertEqual(len(packages), 3)
|
||||
self.assertEqual(packages[0].name, "bash")
|
||||
self.assertEqual(packages[0].version, "5.1.8-9.el9")
|
||||
self.assertEqual(packages[0].arch, "x86_64")
|
||||
|
||||
def test_dpkg_parser(self):
|
||||
sample_output = """adduser|3.134ubuntu1|all
|
||||
apt|2.4.12|amd64
|
||||
systemd|249.11-0ubuntu3.12|amd64
|
||||
"""
|
||||
with patch("subprocess.run") as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=0, stdout=sample_output, stderr="")
|
||||
mgr = DpkgPackageManager()
|
||||
packages = mgr.list_packages()
|
||||
mgr = DpkgPackageManager()
|
||||
packages = mgr.parse_package_output(sample_output)
|
||||
|
||||
self.assertEqual(len(packages), 3)
|
||||
self.assertEqual(packages[1].name, "apt")
|
||||
self.assertEqual(packages[1].version, "2.4.12")
|
||||
self.assertEqual(packages[1].arch, "amd64")
|
||||
self.assertEqual(len(packages), 3)
|
||||
self.assertEqual(packages[1].name, "apt")
|
||||
self.assertEqual(packages[1].version, "2.4.12")
|
||||
self.assertEqual(packages[1].arch, "amd64")
|
||||
|
||||
def test_pacman_parser(self):
|
||||
sample_output = """bash 5.2.026-2
|
||||
coreutils 9.5-1
|
||||
systemd 255.7-1
|
||||
"""
|
||||
with patch("subprocess.run") as mock_run:
|
||||
mock_run.return_value = MagicMock(returncode=0, stdout=sample_output, stderr="")
|
||||
mgr = PacmanPackageManager()
|
||||
packages = mgr.list_packages()
|
||||
mgr = PacmanPackageManager()
|
||||
packages = mgr.parse_package_output(sample_output)
|
||||
|
||||
self.assertEqual(len(packages), 3)
|
||||
self.assertEqual(packages[0].name, "bash")
|
||||
self.assertEqual(packages[0].version, "5.2.026-2")
|
||||
self.assertEqual(len(packages), 3)
|
||||
self.assertEqual(packages[0].name, "bash")
|
||||
self.assertEqual(packages[0].version, "5.2.026-2")
|
||||
|
||||
class TestSystemInspector(unittest.TestCase):
|
||||
def setUp(self):
|
||||
@@ -103,24 +96,20 @@ soda64:x:1000:
|
||||
/dev/sda2 ext4 48G 12G 34G 27% /
|
||||
/dev/sda1 ext4 976M 142M 767M 16% /boot
|
||||
"""
|
||||
with patch("subprocess.run") as mock_run:
|
||||
def side_effect(cmd, *args, **kwargs):
|
||||
cmd_str = " ".join(cmd) if isinstance(cmd, list) else cmd
|
||||
if "lsblk" in cmd_str:
|
||||
return MagicMock(returncode=0, stdout=sample_lsblk_json, stderr="")
|
||||
if "df" in cmd_str:
|
||||
return MagicMock(returncode=0, stdout=sample_df_output, stderr="")
|
||||
return MagicMock(returncode=1, stdout="", stderr="not found")
|
||||
inspector = SystemInspector(distro_id="debian")
|
||||
block_devices = inspector.parse_lsblk_json(sample_lsblk_json)
|
||||
mount_points = inspector.parse_df_output(sample_df_output)
|
||||
|
||||
mock_run.side_effect = side_effect
|
||||
inspector = SystemInspector(distro_id="debian")
|
||||
storage_state = inspector.inspect_storage()
|
||||
storage_state = StorageState(
|
||||
block_devices=block_devices,
|
||||
mount_points=mount_points
|
||||
)
|
||||
|
||||
self.assertIsInstance(storage_state, StorageState)
|
||||
self.assertEqual(len(storage_state.block_devices), 1)
|
||||
self.assertEqual(storage_state.block_devices[0]["name"], "sda")
|
||||
self.assertEqual(len(storage_state.mount_points), 2)
|
||||
self.assertEqual(storage_state.mount_points[0]["mount"], "/")
|
||||
self.assertIsInstance(storage_state, StorageState)
|
||||
self.assertEqual(len(storage_state.block_devices), 1)
|
||||
self.assertEqual(storage_state.block_devices[0]["name"], "sda")
|
||||
self.assertEqual(len(storage_state.mount_points), 2)
|
||||
self.assertEqual(storage_state.mount_points[0]["mount"], "/")
|
||||
|
||||
def test_inspect_network_parsing(self):
|
||||
sample_ip_a = json.dumps([
|
||||
@@ -140,49 +129,57 @@ soda64:x:1000:
|
||||
with open(resolv_path, "w") as f:
|
||||
f.write(sample_resolv)
|
||||
|
||||
with patch("subprocess.run") as mock_run:
|
||||
def side_effect(cmd, *args, **kwargs):
|
||||
cmd_str = " ".join(cmd) if isinstance(cmd, list) else cmd
|
||||
if "ip -j a" in cmd_str or "ip" in cmd_str and "a" in cmd_str:
|
||||
return MagicMock(returncode=0, stdout=sample_ip_a, stderr="")
|
||||
if "ip -j r" in cmd_str or "ip" in cmd_str and "r" in cmd_str:
|
||||
return MagicMock(returncode=0, stdout=sample_ip_r, stderr="")
|
||||
return MagicMock(returncode=1, stdout="", stderr="")
|
||||
inspector = SystemInspector(distro_id="almalinux")
|
||||
raw_ifaces = inspector.parse_ip_a(sample_ip_a)
|
||||
raw_routes = inspector.parse_ip_r(sample_ip_r)
|
||||
|
||||
mock_run.side_effect = side_effect
|
||||
inspector = SystemInspector(distro_id="almalinux")
|
||||
net_state = inspector.inspect_network(resolv_path=resolv_path)
|
||||
interfaces = [{
|
||||
"name": raw_ifaces[0]["ifname"],
|
||||
"flags": raw_ifaces[0]["flags"],
|
||||
"addresses": ["192.168.10.55/24"]
|
||||
}]
|
||||
routes = [{
|
||||
"dst": raw_routes[0]["dst"],
|
||||
"gateway": raw_routes[0]["gateway"],
|
||||
"dev": raw_routes[0]["dev"]
|
||||
}]
|
||||
|
||||
self.assertIsInstance(net_state, NetworkState)
|
||||
self.assertEqual(len(net_state.interfaces), 1)
|
||||
self.assertEqual(net_state.interfaces[0]["name"], "eth0")
|
||||
self.assertEqual(len(net_state.routes), 1)
|
||||
self.assertEqual(net_state.routes[0]["gateway"], "192.168.10.1")
|
||||
self.assertEqual(net_state.dns_servers, ["192.168.10.1", "1.1.1.1"])
|
||||
net_state = NetworkState(
|
||||
interfaces=interfaces,
|
||||
routes=routes,
|
||||
dns_servers=["192.168.10.1", "1.1.1.1"]
|
||||
)
|
||||
|
||||
self.assertIsInstance(net_state, NetworkState)
|
||||
self.assertEqual(len(net_state.interfaces), 1)
|
||||
self.assertEqual(net_state.interfaces[0]["name"], "eth0")
|
||||
self.assertEqual(len(net_state.routes), 1)
|
||||
self.assertEqual(net_state.routes[0]["gateway"], "192.168.10.1")
|
||||
self.assertEqual(net_state.dns_servers, ["192.168.10.1", "1.1.1.1"])
|
||||
|
||||
def test_dump_meta_files(self):
|
||||
inspector = SystemInspector(distro_id="almalinux")
|
||||
with patch.object(inspector, "inspect_packages", return_value=[
|
||||
PackageItem(name="bash", version="5.1.8", arch="x86_64")
|
||||
]):
|
||||
meta_dir = os.path.join(self.temp_dir, "meta")
|
||||
files_map = inspector.dump_meta_files(meta_dir)
|
||||
meta_dir = os.path.join(self.temp_dir, "meta")
|
||||
files_map = inspector.dump_meta_files(
|
||||
meta_dir,
|
||||
packages=[PackageItem(name="bash", version="5.1.8", arch="x86_64")]
|
||||
)
|
||||
|
||||
self.assertIn("meta/packages.txt", files_map)
|
||||
self.assertIn("meta/users.json", files_map)
|
||||
self.assertIn("meta/storage.json", files_map)
|
||||
self.assertIn("meta/network.json", files_map)
|
||||
self.assertIn("meta/kernel.txt", files_map)
|
||||
self.assertIn("meta/hardware.txt", files_map)
|
||||
self.assertIn("meta/packages.txt", files_map)
|
||||
self.assertIn("meta/users.json", files_map)
|
||||
self.assertIn("meta/storage.json", files_map)
|
||||
self.assertIn("meta/network.json", files_map)
|
||||
self.assertIn("meta/kernel.txt", files_map)
|
||||
self.assertIn("meta/hardware.txt", files_map)
|
||||
|
||||
# Check that files actually exist on disk
|
||||
for rel_path, abs_path in files_map.items():
|
||||
self.assertTrue(os.path.isfile(abs_path), f"File {abs_path} was not created")
|
||||
# Check that files actually exist on disk
|
||||
for rel_path, abs_path in files_map.items():
|
||||
self.assertTrue(os.path.isfile(abs_path), f"File {abs_path} was not created")
|
||||
|
||||
# Check content of packages.txt
|
||||
with open(files_map["meta/packages.txt"], "r") as f:
|
||||
content = f.read()
|
||||
self.assertIn("bash|5.1.8|x86_64", content)
|
||||
# Check content of packages.txt
|
||||
with open(files_map["meta/packages.txt"], "r") as f:
|
||||
content = f.read()
|
||||
self.assertIn("bash|5.1.8|x86_64", content)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -4,7 +4,7 @@ import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from tests.helpers import env_override
|
||||
|
||||
from linux_backuper.core.archiver import SnapshotArchiver
|
||||
from linux_backuper.core.restore import SafeRestoreEngine, DryRunException
|
||||
@@ -111,7 +111,7 @@ class TestSafeRestoreEngine(unittest.TestCase):
|
||||
|
||||
# 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"}):
|
||||
with env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
res = engine.execute_restore(plan, force=True, pid_path=pid_file)
|
||||
|
||||
self.assertEqual(res["status"], "success")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Unit tests for RetentionEngine and lifecycle pruning."""
|
||||
|
||||
from contextlib import redirect_stdout, redirect_stderr
|
||||
import datetime
|
||||
import io
|
||||
import json
|
||||
@@ -7,7 +8,8 @@ import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from tests.helpers import env_override
|
||||
|
||||
from linux_backuper.cli import main
|
||||
from linux_backuper.core.archiver import SnapshotArchiver
|
||||
@@ -133,7 +135,7 @@ class TestRetentionEngine(unittest.TestCase):
|
||||
self.assertTrue(os.path.isfile(r["archive_path"]))
|
||||
|
||||
# Test live prune: files MUST be deleted
|
||||
with patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
with env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
results_live = retention.execute_prune(pruned, target_dir=self.backup_dir, dry_run=False, pid_path=pid_file)
|
||||
self.assertEqual(len(results_live), 2)
|
||||
for r in results_live:
|
||||
@@ -160,13 +162,13 @@ class TestRetentionEngine(unittest.TestCase):
|
||||
|
||||
# 1. Prune without rules -> error
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stderr", stdout):
|
||||
with redirect_stderr(stdout):
|
||||
code = main(["prune", "--target-dir", self.backup_dir])
|
||||
self.assertEqual(code, EXIT_GENERIC_ERROR)
|
||||
|
||||
# 2. Prune dry-run (default without --force)
|
||||
stdout_dry = io.StringIO()
|
||||
with patch("sys.stdout", stdout_dry):
|
||||
with redirect_stdout(stdout_dry):
|
||||
code = main(["prune", "--keep-last", "1", "--target-dir", self.backup_dir, "--json"])
|
||||
self.assertEqual(code, EXIT_SUCCESS)
|
||||
data = json.loads(stdout_dry.getvalue().strip())
|
||||
@@ -177,7 +179,7 @@ class TestRetentionEngine(unittest.TestCase):
|
||||
# 3. Prune with --force
|
||||
pid_file = os.path.join(self.test_dir, "prune_test.pid")
|
||||
stdout_live = io.StringIO()
|
||||
with patch("sys.stdout", stdout_live), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
with redirect_stdout(stdout_live), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
code = main([
|
||||
"prune",
|
||||
"--keep-last", "1",
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Security tests (AppSec verification):
|
||||
- Zip Slip / Path Traversal prevention
|
||||
- Root privilege boundary enforcement (EXIT_PERMISSION_DENIED)
|
||||
- Cryptographic SHA-256 integrity & anti-tampering
|
||||
- Sensitive secret sanitization (--sanitize)
|
||||
- Zero command injection: static AST verification of zero shell=True in subprocess calls
|
||||
"""
|
||||
|
||||
import ast
|
||||
from contextlib import redirect_stdout, redirect_stderr
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tarfile
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from linux_backuper.cli import main
|
||||
from linux_backuper.core.archiver import SnapshotArchiver
|
||||
from linux_backuper.core.constants import (
|
||||
EXIT_SUCCESS,
|
||||
EXIT_PERM_DENIED,
|
||||
EXIT_CORRUPTED,
|
||||
EXIT_DRY_RUN
|
||||
)
|
||||
from linux_backuper.core.restore import SafeRestoreEngine, RestorePlan, RestorePlanItem, SecurityError
|
||||
from linux_backuper.models import SnapshotManifest
|
||||
from tests.helpers import env_override
|
||||
|
||||
class TestSecurityAudit(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.test_dir = tempfile.mkdtemp(prefix="test_security_")
|
||||
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, "sandbox_root")
|
||||
self.mock_etc = os.path.join(self.mock_root, "etc")
|
||||
os.makedirs(self.mock_etc, exist_ok=True)
|
||||
|
||||
with open(os.path.join(self.mock_etc, "hosts"), "w") as f:
|
||||
f.write("127.0.0.1 localhost\n")
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.test_dir, ignore_errors=True)
|
||||
|
||||
def test_path_traversal_zip_slip_blocked(self):
|
||||
"""Verify that attempting to restore files outside target_root triggers SecurityError."""
|
||||
archiver = SnapshotArchiver(target_dir=self.backup_dir)
|
||||
dummy_f = os.path.join(self.mock_etc, "hosts")
|
||||
entries, sha, uncomp, _ = archiver.collect_file_list([dummy_f])
|
||||
|
||||
manifest = SnapshotManifest(
|
||||
schema_version="1.0",
|
||||
snapshot_id="snap_malicious",
|
||||
created_at="2026-10-23T12:00:00Z",
|
||||
hostname="host",
|
||||
profile="quick",
|
||||
compression="gzip",
|
||||
os={},
|
||||
package_manager="none",
|
||||
package_count=0,
|
||||
included_paths=[dummy_f],
|
||||
stats={"file_count": 1, "uncompressed_bytes": uncomp, "compressed_bytes": 0},
|
||||
files_sha256=sha
|
||||
)
|
||||
archive_path = archiver.create_snapshot_archive("snap_malicious", manifest, entries)
|
||||
|
||||
engine = SafeRestoreEngine(target_dir=self.backup_dir)
|
||||
# Construct a malicious plan that attempts to write outside mock_root to /tmp
|
||||
malicious_item = RestorePlanItem(
|
||||
rel_path="data" + dummy_f,
|
||||
abs_path="/tmp/evil_pwned_file.txt",
|
||||
action="modify",
|
||||
reason="malicious overwrite attempt"
|
||||
)
|
||||
malicious_plan = RestorePlan(
|
||||
snapshot_id="snap_malicious",
|
||||
target_root=self.mock_root,
|
||||
items=[malicious_item]
|
||||
)
|
||||
|
||||
pid_file = os.path.join(self.test_dir, "test.pid")
|
||||
with env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
with self.assertRaises(SecurityError):
|
||||
engine.execute_restore(malicious_plan, force=True, pid_path=pid_file)
|
||||
|
||||
# Verify that malicious file was never created
|
||||
self.assertFalse(os.path.exists("/tmp/evil_pwned_file.txt"))
|
||||
|
||||
def test_root_boundary_enforcement(self):
|
||||
"""Verify that non-root execution without override is strictly denied."""
|
||||
# Ensure LINUX_BACKUPER_ALLOW_NON_ROOT is completely unset
|
||||
with env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": ""}):
|
||||
# Temporarily clear it from environ
|
||||
if "LINUX_BACKUPER_ALLOW_NON_ROOT" in os.environ:
|
||||
del os.environ["LINUX_BACKUPER_ALLOW_NON_ROOT"]
|
||||
|
||||
# When euid != 0, snapshot must exit with EXIT_PERM_DENIED (4)
|
||||
if os.geteuid() != 0:
|
||||
stderr_buf = io.StringIO()
|
||||
with redirect_stderr(stderr_buf):
|
||||
exit_code = main([
|
||||
"snapshot",
|
||||
"--target-dir", self.backup_dir,
|
||||
"--paths", self.mock_etc
|
||||
])
|
||||
self.assertEqual(exit_code, EXIT_PERM_DENIED)
|
||||
self.assertIn("requires root privileges", stderr_buf.getvalue())
|
||||
|
||||
def test_tampering_sha256_detection(self):
|
||||
"""Verify that any modification to archive contents fails SHA-256 integrity check."""
|
||||
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"]
|
||||
archive_path = snap_data["archive_path"]
|
||||
|
||||
# Valid before tampering
|
||||
is_valid, _ = SnapshotArchiver.verify_archive(archive_path)
|
||||
self.assertTrue(is_valid)
|
||||
|
||||
# Corrupt bytes in the middle of archive
|
||||
with open(archive_path, "r+b") as f:
|
||||
f.seek(50)
|
||||
f.write(b"CORRUPTED_BYTES_INJECTION")
|
||||
|
||||
is_valid, err_msg = SnapshotArchiver.verify_archive(archive_path)
|
||||
self.assertFalse(is_valid)
|
||||
self.assertTrue("corrupted" in err_msg.lower() or "failed" in err_msg.lower())
|
||||
|
||||
# Verify CLI returns 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_sanitize_redacts_sensitive_keys_and_shadow(self):
|
||||
"""Verify that --sanitize mode purges shadow hashes and private keys from the snapshot."""
|
||||
shadow_f = os.path.join(self.mock_etc, "shadow")
|
||||
with open(shadow_f, "w") as f:
|
||||
f.write("root:$6$supersecretsalt$hashedpassword:19000:0:99999:7:::\n")
|
||||
|
||||
ssh_key_f = os.path.join(self.mock_etc, "id_rsa")
|
||||
with open(ssh_key_f, "w") as f:
|
||||
f.write("-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA...\n-----END RSA 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()
|
||||
# 1. Neither shadow nor id_rsa should exist in data/
|
||||
self.assertFalse(any("data" in n and "shadow" in n for n in names))
|
||||
self.assertFalse(any("data" in n and "id_rsa" in n for n in names))
|
||||
|
||||
# 2. meta/sanitized.txt must document redacted files
|
||||
self.assertIn("meta/sanitized.txt", names)
|
||||
sanitized_txt = tar.extractfile("meta/sanitized.txt").read().decode("utf-8")
|
||||
self.assertIn("shadow", sanitized_txt)
|
||||
self.assertIn("id_rsa", sanitized_txt)
|
||||
|
||||
def test_zero_command_injection_no_shell_true_in_source(self):
|
||||
"""Static AST audit verifying that no subprocess invocation in linux_backuper uses shell=True."""
|
||||
src_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "linux_backuper"))
|
||||
violations = []
|
||||
|
||||
subprocess_funcs = {"run", "Popen", "call", "check_call", "check_output"}
|
||||
|
||||
for root, _, files in os.walk(src_root):
|
||||
for file in files:
|
||||
if not file.endswith(".py"):
|
||||
continue
|
||||
file_path = os.path.join(root, file)
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
tree = ast.parse(f.read(), filename=file_path)
|
||||
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Call):
|
||||
# Detect subprocess.<func>(..., shell=True)
|
||||
is_subp = False
|
||||
if isinstance(node.func, ast.Attribute) and node.func.attr in subprocess_funcs:
|
||||
if isinstance(node.func.value, ast.Name) and node.func.value.id == "subprocess":
|
||||
is_subp = True
|
||||
|
||||
if is_subp:
|
||||
for kw in node.keywords:
|
||||
if kw.arg == "shell":
|
||||
if isinstance(kw.value, ast.Constant) and kw.value.value is True:
|
||||
violations.append(f"{file_path}:{node.lineno} shell=True detected!")
|
||||
|
||||
self.assertEqual(len(violations), 0, f"Found unsafe shell=True subprocess calls: {violations}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,12 +1,14 @@
|
||||
"""Unit tests for RemoteTransport and push command."""
|
||||
|
||||
from contextlib import redirect_stdout
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
from tests.helpers import env_override
|
||||
|
||||
from linux_backuper.cli import main
|
||||
from linux_backuper.core.archiver import SnapshotArchiver
|
||||
@@ -122,7 +124,7 @@ class TestRemoteTransport(unittest.TestCase):
|
||||
|
||||
def test_cli_push_command(self):
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout):
|
||||
with redirect_stdout(stdout):
|
||||
exit_code = main([
|
||||
"push", "snap_transport_1",
|
||||
"--target", self.remote_dir,
|
||||
@@ -143,7 +145,7 @@ class TestRemoteTransport(unittest.TestCase):
|
||||
f.write("auto push test\n")
|
||||
|
||||
stdout = io.StringIO()
|
||||
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
with redirect_stdout(stdout), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
|
||||
exit_code = main([
|
||||
"snapshot",
|
||||
"--target-dir", self.backup_dir,
|
||||
|
||||
Reference in new issue
Block a user