Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tests /unit /test_tool_wrapper.py
| """ | |
| Unit tests for zen_ai_pentest/tool_wrapper.py | |
| Fast, isolated tests using monkeypatch and unittest.mock. | |
| No real Docker or subprocess calls are executed. | |
| """ | |
| import json | |
| import os | |
| import stat | |
| import subprocess | |
| import sys | |
| import threading | |
| import time | |
| import types | |
| from unittest.mock import MagicMock, patch | |
| import pytest | |
| sys.path.insert( | |
| 0, | |
| os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), | |
| ) | |
| # Stub the zen_ai_pentest package so these tests can import tool_wrapper and | |
| # plugin_manager directly without executing the top-level __init__.py. This | |
| # keeps the test suite fast, avoids pulling in heavy transitive dependencies | |
| # such as numpy, and allows coverage measurement to run reliably. | |
| if "zen_ai_pentest" not in sys.modules or not hasattr(sys.modules.get("zen_ai_pentest"), "__path__"): | |
| _zen_pkg = types.ModuleType("zen_ai_pentest") | |
| _zen_pkg.__path__ = ["zen_ai_pentest"] | |
| sys.modules["zen_ai_pentest"] = _zen_pkg | |
| from docker.errors import APIError, ContainerError, DockerException | |
| from zen_ai_pentest import tool_wrapper | |
| from zen_ai_pentest.plugin_manager import ( | |
| BaseTool, | |
| ToolCategory, | |
| ToolMetadata, | |
| ToolRiskLevel, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Helpers | |
| # --------------------------------------------------------------------------- | |
| class FakeTool(BaseTool): | |
| """Concrete tool implementation for unit tests.""" | |
| def __init__(self, **metadata_overrides): | |
| metadata = ToolMetadata( | |
| name="fake_tool", | |
| version="1.0.0", | |
| category=ToolCategory.NETWORK_SCANNING, | |
| description="Fake tool for testing", | |
| author="test", | |
| risk_level=ToolRiskLevel.LOW, | |
| docker_image=metadata_overrides.pop("docker_image", None), | |
| binary_path="/bin/fake", | |
| max_cpu_percent=25.0, | |
| max_memory_mb=512, | |
| max_execution_time=120, | |
| requires_network=False, | |
| ) | |
| for key, value in metadata_overrides.items(): | |
| setattr(metadata, key, value) | |
| super().__init__(metadata) | |
| def validate_input(self, target, options): | |
| return True | |
| def build_command(self, target, options): | |
| return [self.metadata.binary_path, target] | |
| def parse_output(self, stdout, stderr): | |
| return {"raw": stdout, "findings": [{"id": 1}]} | |
| def fake_tool(): | |
| return FakeTool() | |
| def execution_options(): | |
| return tool_wrapper.ExecutionOptions(target="example.com", timeout=10) | |
| def mock_docker_module(monkeypatch): | |
| """Replace the docker module used by tool_wrapper with a MagicMock.""" | |
| mock_docker = MagicMock() | |
| mock_docker.DockerClient = MagicMock() | |
| mock_docker.from_env = MagicMock() | |
| mock_docker.errors.DockerException = DockerException | |
| mock_docker.errors.APIError = APIError | |
| mock_docker.errors.ContainerError = ContainerError | |
| mock_docker.types.Mount = MagicMock(side_effect=lambda **kwargs: kwargs) | |
| monkeypatch.setattr(tool_wrapper, "docker", mock_docker) | |
| return mock_docker | |
| def mock_psutil(monkeypatch): | |
| """Mock psutil so ResourceMonitor does not need the real package.""" | |
| mock_mod = MagicMock() | |
| process_mock = MagicMock() | |
| process_mock.memory_info.return_value = MagicMock(rss=100 * 1024 * 1024) | |
| process_mock.cpu_percent.return_value = 12.5 | |
| mock_mod.Process.return_value = process_mock | |
| monkeypatch.setitem(sys.modules, "psutil", mock_mod) | |
| monkeypatch.setattr(tool_wrapper.time, "sleep", lambda _x: None) | |
| return mock_mod, process_mock | |
| # --------------------------------------------------------------------------- | |
| # Dataclasses | |
| # --------------------------------------------------------------------------- | |
| class TestSandboxConfig: | |
| def test_defaults(self): | |
| cfg = tool_wrapper.SandboxConfig() | |
| assert cfg.max_cpu_percent == 50.0 | |
| assert cfg.max_memory_mb == 1024 | |
| assert cfg.max_execution_time == 300 | |
| assert cfg.max_disk_mb == 512 | |
| assert cfg.network_mode == "none" | |
| assert cfg.allowed_ports == [] | |
| assert cfg.blocked_hosts == ["169.254.169.254"] | |
| assert cfg.read_only_mounts == [] | |
| assert cfg.writable_mounts == {} | |
| assert cfg.tmpfs_size_mb == 100 | |
| assert cfg.drop_capabilities == ["ALL"] | |
| assert cfg.add_capabilities == [] | |
| assert cfg.seccomp_profile is None | |
| assert cfg.apparmor_profile is None | |
| assert cfg.no_new_privileges is True | |
| assert cfg.run_as_user == "nobody" | |
| assert cfg.run_as_group == "nogroup" | |
| assert cfg.credential_env_vars == {} | |
| assert cfg.credential_files == {} | |
| def test_to_docker_resources(self): | |
| cfg = tool_wrapper.SandboxConfig( | |
| max_cpu_percent=75.0, | |
| max_memory_mb=2048, | |
| ) | |
| resources = cfg.to_docker_resources() | |
| assert resources["cpu_quota"] == 75000 | |
| assert resources["cpu_period"] == 100000 | |
| assert resources["mem_limit"] == "2048m" | |
| assert resources["memswap_limit"] == "2048m" | |
| class TestExecutionOptions: | |
| def test_defaults(self): | |
| opts = tool_wrapper.ExecutionOptions(target="example.com") | |
| assert opts.target == "example.com" | |
| assert opts.timeout == 300 | |
| assert opts.output_format == "json" | |
| assert opts.verbose is False | |
| assert opts.save_output is True | |
| assert opts.custom_args == {} | |
| assert opts.environment_vars == {} | |
| # --------------------------------------------------------------------------- | |
| # ResourceMonitor | |
| # --------------------------------------------------------------------------- | |
| class TestResourceMonitor: | |
| def test_start_stop_no_monitoring(self): | |
| monitor = tool_wrapper.ResourceMonitor() | |
| assert monitor._monitoring is False | |
| monitor.start() | |
| assert monitor._monitoring is True | |
| assert monitor._monitor_thread is not None | |
| stats = monitor.stop() | |
| assert monitor._monitoring is False | |
| assert "peak_memory_mb" in stats | |
| assert "peak_cpu_percent" in stats | |
| assert "execution_time" in stats | |
| def test_stop_without_start(self): | |
| monitor = tool_wrapper.ResourceMonitor() | |
| stats = monitor.stop() | |
| assert stats["execution_time"] == 0 | |
| def test_monitor_loop_updates_peaks(self, mock_psutil): | |
| mock_mod, process_mock = mock_psutil | |
| monitor = tool_wrapper.ResourceMonitor() | |
| loop_ran = threading.Event() | |
| original_memory_info = process_mock.memory_info | |
| def memory_info_and_signal(): | |
| loop_ran.set() | |
| return MagicMock(rss=200 * 1024 * 1024) | |
| process_mock.memory_info.side_effect = memory_info_and_signal | |
| process_mock.cpu_percent.return_value = 42.0 | |
| monitor.start() | |
| loop_ran.wait(timeout=2) | |
| monitor.stop() | |
| assert monitor.peak_memory_mb >= 200.0 | |
| assert monitor.peak_cpu_percent == 42.0 | |
| def test_monitor_loop_memory_warning(self, mock_psutil, caplog): | |
| mock_mod, process_mock = mock_psutil | |
| monitor = tool_wrapper.ResourceMonitor(max_memory_mb=50) | |
| loop_ran = threading.Event() | |
| def memory_info_and_signal(): | |
| loop_ran.set() | |
| return MagicMock(rss=100 * 1024 * 1024) | |
| process_mock.memory_info.side_effect = memory_info_and_signal | |
| with caplog.at_level("WARNING", logger="zen_ai_pentest.tool_wrapper"): | |
| monitor.start() | |
| loop_ran.wait(timeout=2) | |
| monitor.stop() | |
| assert any("Memory limit exceeded" in rec.message for rec in caplog.records) | |
| def test_monitor_loop_exception(self, mock_psutil, caplog): | |
| mock_mod, process_mock = mock_psutil | |
| monitor = tool_wrapper.ResourceMonitor() | |
| process_mock.memory_info.side_effect = RuntimeError("psutil failure") | |
| with caplog.at_level("ERROR", logger="zen_ai_pentest.tool_wrapper"): | |
| monitor.start() | |
| monitor._monitor_thread.join(timeout=2) | |
| monitor.stop() | |
| assert any("Monitor error" in rec.message for rec in caplog.records) | |
| # --------------------------------------------------------------------------- | |
| # SecureToolWrapper initialization & docker_client | |
| # --------------------------------------------------------------------------- | |
| class TestSecureToolWrapperInit: | |
| def test_default_init(self): | |
| wrapper = tool_wrapper.SecureToolWrapper() | |
| assert wrapper.use_docker is True | |
| assert wrapper.docker_socket == "unix://var/run/docker.sock" | |
| assert wrapper._docker_client is None | |
| assert wrapper._temp_dirs == [] | |
| def test_docker_client_lazy_success(self, mock_docker_module): | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=True) | |
| client = wrapper.docker_client | |
| assert client is not None | |
| mock_docker_module.DockerClient.assert_called_once_with(base_url="unix://var/run/docker.sock") | |
| # second access should reuse cached client | |
| wrapper.docker_client | |
| assert mock_docker_module.DockerClient.call_count == 1 | |
| def test_docker_client_lazy_failure(self, mock_docker_module, caplog): | |
| mock_docker_module.DockerClient.side_effect = DockerException("not reachable") | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=True) | |
| client = wrapper.docker_client | |
| assert client is None | |
| assert wrapper.use_docker is False | |
| assert any("Failed to connect to Docker" in rec.message for rec in caplog.records) | |
| def test_docker_client_when_disabled(self): | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=False) | |
| assert wrapper.docker_client is None | |
| # --------------------------------------------------------------------------- | |
| # SecureToolWrapper.execute | |
| # --------------------------------------------------------------------------- | |
| class TestSecureToolWrapperExecute: | |
| def test_execute_validation_failure(self, fake_tool, execution_options): | |
| fake_tool.validate_input = MagicMock(return_value=False) | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=False) | |
| result = wrapper.execute(fake_tool, execution_options) | |
| assert result.success is False | |
| assert result.return_code == -1 | |
| assert result.stderr == "Input validation failed" | |
| assert result.error_message == "Input validation failed" | |
| def test_execute_docker_success(self, mock_docker_module, fake_tool, execution_options, monkeypatch): | |
| fake_tool.metadata.docker_image = "fake:image" | |
| monkeypatch.setattr( | |
| tool_wrapper.os, | |
| "walk", | |
| lambda _path: [("/output", [], ["result.json"])], | |
| ) | |
| mock_client = MagicMock() | |
| mock_container = MagicMock() | |
| mock_container.wait.return_value = {"StatusCode": 0} | |
| mock_container.logs.side_effect = lambda stdout=False, stderr=False: b"stdout" if stdout else b"stderr" | |
| mock_client.containers.run.return_value = mock_container | |
| mock_docker_module.DockerClient.return_value = mock_client | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=True) | |
| result = wrapper.execute(fake_tool, execution_options) | |
| assert result.success is True | |
| assert result.return_code == 0 | |
| assert result.stdout == "stdout" | |
| assert result.stderr == "stderr" | |
| assert "/output/result.json" in result.output_files | |
| assert result.findings == [{"id": 1}] | |
| assert fake_tool._performance_metrics["total_executions"] == 1 | |
| mock_container.remove.assert_called_once_with(force=True) | |
| def test_execute_subprocess_success(self, fake_tool, execution_options, monkeypatch): | |
| monkeypatch.setattr( | |
| tool_wrapper.os, | |
| "walk", | |
| lambda _path: [("/output", [], ["sub.json"])], | |
| ) | |
| mock_proc = MagicMock() | |
| mock_proc.communicate.return_value = (b"stdout", b"stderr") | |
| mock_proc.returncode = 0 | |
| monkeypatch.setattr(tool_wrapper.subprocess, "Popen", MagicMock(return_value=mock_proc)) | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=False) | |
| result = wrapper.execute(fake_tool, execution_options) | |
| assert result.success is True | |
| assert result.return_code == 0 | |
| assert result.stdout == "stdout" | |
| assert result.stderr == "stderr" | |
| assert any("sub.json" in f for f in result.output_files) | |
| assert fake_tool._performance_metrics["successful_executions"] == 1 | |
| def test_execute_exception_handling(self, fake_tool, execution_options): | |
| fake_tool.pre_execute = MagicMock(side_effect=RuntimeError("boom")) | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=False) | |
| result = wrapper.execute(fake_tool, execution_options) | |
| assert result.success is False | |
| assert result.return_code == -1 | |
| assert "boom" in result.error_message | |
| # --------------------------------------------------------------------------- | |
| # _execute_docker branches | |
| # --------------------------------------------------------------------------- | |
| class TestExecuteDockerBranches: | |
| def _build_wrapper_and_container(self, mock_docker_module, monkeypatch): | |
| monkeypatch.setattr( | |
| tool_wrapper.os, | |
| "walk", | |
| lambda _path: [("/output", [], ["out.json"])], | |
| ) | |
| mock_client = MagicMock() | |
| mock_container = MagicMock() | |
| mock_container.wait.return_value = {"StatusCode": 0} | |
| mock_container.logs.side_effect = lambda stdout=False, stderr=False: b"stdout" if stdout else b"stderr" | |
| mock_client.containers.run.return_value = mock_container | |
| mock_docker_module.DockerClient.return_value = mock_client | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=True) | |
| return wrapper, mock_container, mock_client | |
| def test_execute_docker_wait_timeout(self, mock_docker_module, fake_tool, execution_options, monkeypatch): | |
| wrapper, mock_container, _mock_client = self._build_wrapper_and_container(mock_docker_module, monkeypatch) | |
| mock_container.wait.side_effect = Exception("timeout") | |
| fake_tool.metadata.docker_image = "fake:image" | |
| result = wrapper.execute(fake_tool, execution_options) | |
| assert result.success is False | |
| assert result.return_code == -1 | |
| mock_container.kill.assert_called_once() | |
| mock_container.remove.assert_called_once_with(force=True) | |
| def test_execute_docker_container_error(self, mock_docker_module, fake_tool, execution_options): | |
| mock_docker_module.DockerClient.return_value.containers.run.side_effect = ContainerError( | |
| None, 1, [], "image", "stderr" | |
| ) | |
| fake_tool.metadata.docker_image = "fake:image" | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=True) | |
| result = wrapper.execute(fake_tool, execution_options) | |
| assert result.success is False | |
| assert "Container error" in result.error_message | |
| def test_execute_docker_api_error(self, mock_docker_module, fake_tool, execution_options): | |
| mock_docker_module.DockerClient.return_value.containers.run.side_effect = APIError("docker api failure") | |
| fake_tool.metadata.docker_image = "fake:image" | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=True) | |
| result = wrapper.execute(fake_tool, execution_options) | |
| assert result.success is False | |
| assert "Docker API error" in result.error_message | |
| def test_execute_docker_with_full_config(self, mock_docker_module, fake_tool, execution_options, monkeypatch): | |
| wrapper, _mock_container, mock_client = self._build_wrapper_and_container(mock_docker_module, monkeypatch) | |
| fake_tool.metadata.docker_image = "fake:image" | |
| sandbox_config = tool_wrapper.SandboxConfig( | |
| read_only_mounts=["/tools"], | |
| credential_env_vars={"TOKEN": "secret"}, | |
| seccomp_profile="default", | |
| apparmor_profile="docker-default", | |
| ) | |
| result = wrapper.execute(fake_tool, execution_options, sandbox_config) | |
| assert result.success is True | |
| call_kwargs = mock_client.containers.run.call_args.kwargs | |
| mounts = call_kwargs["mounts"] | |
| assert any(m.get("Target") == "/tools" and m.get("ReadOnly") for m in mounts) | |
| assert call_kwargs["environment"]["TOKEN"] == "secret" | |
| assert any("seccomp=default" in opt for opt in call_kwargs["security_opt"]) | |
| assert any("apparmor=docker-default" in opt for opt in call_kwargs["security_opt"]) | |
| assert call_kwargs["environment"]["TOKEN"] == "secret" | |
| assert any("seccomp=default" in opt for opt in call_kwargs["security_opt"]) | |
| assert any("apparmor=docker-default" in opt for opt in call_kwargs["security_opt"]) | |
| # --------------------------------------------------------------------------- | |
| # _execute_subprocess branches | |
| # --------------------------------------------------------------------------- | |
| class TestExecuteSubprocessBranches: | |
| def _patch_popen(self, monkeypatch, process_mock): | |
| monkeypatch.setattr(tool_wrapper.subprocess, "Popen", MagicMock(return_value=process_mock)) | |
| monkeypatch.setattr( | |
| tool_wrapper.os, | |
| "walk", | |
| lambda _path: [("/output", [], ["proc.json"])], | |
| ) | |
| def test_subprocess_success(self, fake_tool, execution_options, monkeypatch): | |
| mock_proc = MagicMock() | |
| mock_proc.communicate.return_value = (b"out", b"err") | |
| mock_proc.returncode = 0 | |
| self._patch_popen(monkeypatch, mock_proc) | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=False) | |
| result = wrapper._execute_subprocess(fake_tool, execution_options, tool_wrapper.SandboxConfig()) | |
| assert result.success is True | |
| assert result.return_code == 0 | |
| assert result.stdout == "out" | |
| assert result.stderr == "err" | |
| def test_subprocess_timeout(self, fake_tool, execution_options, monkeypatch): | |
| mock_proc = MagicMock() | |
| mock_proc.communicate.side_effect = [ | |
| subprocess.TimeoutExpired(cmd="fake", timeout=1), | |
| (b"partial", b"err"), | |
| ] | |
| mock_proc.returncode = -1 | |
| self._patch_popen(monkeypatch, mock_proc) | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=False) | |
| result = wrapper._execute_subprocess(fake_tool, execution_options, tool_wrapper.SandboxConfig()) | |
| assert result.success is False | |
| assert result.return_code == -1 | |
| mock_proc.kill.assert_called_once() | |
| def test_subprocess_exception(self, fake_tool, execution_options, monkeypatch): | |
| monkeypatch.setattr(tool_wrapper.subprocess, "Popen", MagicMock(side_effect=OSError("exec fail"))) | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=False) | |
| result = wrapper._execute_subprocess(fake_tool, execution_options, tool_wrapper.SandboxConfig()) | |
| assert result.success is False | |
| assert result.return_code == -1 | |
| assert "exec fail" in result.error_message | |
| def test_subprocess_with_credentials(self, fake_tool, execution_options, monkeypatch): | |
| mock_proc = MagicMock() | |
| mock_proc.communicate.return_value = (b"out", b"err") | |
| mock_proc.returncode = 0 | |
| captured = {} | |
| def fake_popen(*_args, **kwargs): | |
| captured["kwargs"] = kwargs | |
| return mock_proc | |
| monkeypatch.setattr(tool_wrapper.subprocess, "Popen", fake_popen) | |
| config = tool_wrapper.SandboxConfig(credential_env_vars={"TOKEN": "secret"}) | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=False) | |
| wrapper._execute_subprocess(fake_tool, execution_options, config) | |
| assert captured["kwargs"]["env"]["TOKEN"] == "secret" | |
| def test_preexec_fn_sets_resource_limits(self, fake_tool, execution_options, monkeypatch): | |
| mock_proc = MagicMock() | |
| mock_proc.communicate.return_value = (b"out", b"err") | |
| mock_proc.returncode = 0 | |
| captured = {} | |
| def fake_popen(*_args, **kwargs): | |
| captured["preexec_fn"] = kwargs.get("preexec_fn") | |
| return mock_proc | |
| monkeypatch.setattr(tool_wrapper.subprocess, "Popen", fake_popen) | |
| monkeypatch.setattr(tool_wrapper.resource, "setrlimit", MagicMock()) | |
| config = tool_wrapper.SandboxConfig(max_memory_mb=256, max_disk_mb=128) | |
| wrapper = tool_wrapper.SecureToolWrapper(use_docker=False) | |
| wrapper._execute_subprocess(fake_tool, execution_options, config) | |
| assert "preexec_fn" in captured | |
| captured["preexec_fn"]() | |
| setrlimit = tool_wrapper.resource.setrlimit | |
| assert setrlimit.call_count == 4 | |
| calls = setrlimit.call_args_list | |
| assert calls[0][0][0] == tool_wrapper.resource.RLIMIT_AS | |
| assert calls[1][0][0] == tool_wrapper.resource.RLIMIT_CPU | |
| assert calls[2][0][0] == tool_wrapper.resource.RLIMIT_FSIZE | |
| assert calls[3][0][0] == tool_wrapper.resource.RLIMIT_NPROC | |
| # Verify memory limit in bytes | |
| assert calls[0][0][1] == (256 * 1024 * 1024, 256 * 1024 * 1024) | |
| # Verify disk limit in bytes | |
| assert calls[2][0][1] == (128 * 1024 * 1024, 128 * 1024 * 1024) | |
| # --------------------------------------------------------------------------- | |
| # Helper methods | |
| # --------------------------------------------------------------------------- | |
| class TestHelperMethods: | |
| def test_create_default_sandbox_config(self, fake_tool): | |
| wrapper = tool_wrapper.SecureToolWrapper() | |
| cfg = wrapper._create_default_sandbox_config(fake_tool) | |
| assert cfg.max_cpu_percent == fake_tool.metadata.max_cpu_percent | |
| assert cfg.max_memory_mb == fake_tool.metadata.max_memory_mb | |
| assert cfg.max_execution_time == fake_tool.metadata.max_execution_time | |
| assert cfg.network_mode == "none" | |
| def test_create_default_sandbox_config_network(self, fake_tool): | |
| fake_tool.metadata.requires_network = True | |
| wrapper = tool_wrapper.SecureToolWrapper() | |
| cfg = wrapper._create_default_sandbox_config(fake_tool) | |
| assert cfg.network_mode == "bridge" | |
| def test_create_and_cleanup_temp_dirs(self): | |
| wrapper = tool_wrapper.SecureToolWrapper() | |
| path = wrapper._create_temp_dir("work") | |
| assert os.path.isdir(path) | |
| assert path in wrapper._temp_dirs | |
| wrapper._cleanup_temp_dirs() | |
| assert wrapper._temp_dirs == [] | |
| assert not os.path.exists(path) | |
| def test_cleanup_temp_dirs_exception(self, monkeypatch, caplog): | |
| wrapper = tool_wrapper.SecureToolWrapper() | |
| path = wrapper._create_temp_dir("work") | |
| assert path in wrapper._temp_dirs | |
| def failing_rmtree(*_args, **_kwargs): | |
| raise PermissionError("cannot remove") | |
| monkeypatch.setattr(tool_wrapper.shutil, "rmtree", failing_rmtree) | |
| with caplog.at_level("WARNING", logger="SecureToolWrapper"): | |
| wrapper._cleanup_temp_dirs() | |
| assert wrapper._temp_dirs == [] | |
| assert any("Failed to cleanup" in rec.message for rec in caplog.records) | |
| # --------------------------------------------------------------------------- | |
| # inject_credentials | |
| # --------------------------------------------------------------------------- | |
| class TestInjectCredentials: | |
| def test_env_method(self): | |
| wrapper = tool_wrapper.SecureToolWrapper() | |
| cfg = tool_wrapper.SandboxConfig() | |
| credentials = {"API_KEY": "secret123"} | |
| result = wrapper.inject_credentials(cfg, credentials, method="env") | |
| assert result is cfg | |
| assert len(cfg.credential_env_vars) == 1 | |
| key = list(cfg.credential_env_vars.keys())[0] | |
| assert cfg.credential_env_vars[key] == "secret123" | |
| def test_file_method(self): | |
| wrapper = tool_wrapper.SecureToolWrapper() | |
| cfg = tool_wrapper.SandboxConfig() | |
| credentials = {"API_KEY": "secret123"} | |
| result = wrapper.inject_credentials(cfg, credentials, method="file") | |
| assert result is cfg | |
| assert len(cfg.credential_files) == 1 | |
| local_path = list(cfg.credential_files.keys())[0] | |
| assert cfg.credential_files[local_path] == "/run/secrets/credentials" | |
| assert os.path.isfile(local_path) | |
| with open(local_path, "r") as f: | |
| stored = json.load(f) | |
| assert stored == credentials | |
| mode = stat.S_IMODE(os.stat(local_path).st_mode) | |
| assert mode == 0o600 | |
| # cleanup temp dir created by inject_credentials | |
| wrapper._cleanup_temp_dirs() | |
| def test_tmpfs_method(self): | |
| wrapper = tool_wrapper.SecureToolWrapper() | |
| cfg = tool_wrapper.SandboxConfig(tmpfs_size_mb=5) | |
| credentials = {"API_KEY": "secret123"} | |
| result = wrapper.inject_credentials(cfg, credentials, method="tmpfs") | |
| assert result is cfg | |
| assert cfg.tmpfs_size_mb == 10 | |
| # --------------------------------------------------------------------------- | |
| # NetworkIsolator | |
| # --------------------------------------------------------------------------- | |
| class TestNetworkIsolator: | |
| def test_init(self): | |
| isolator = tool_wrapper.NetworkIsolator() | |
| assert isolator._iptables_rules == [] | |
| def test_create_isolated_network_success(self, mock_docker_module): | |
| mock_network = MagicMock() | |
| mock_network.name = "zen_isolated" | |
| mock_docker_module.from_env.return_value.networks.create.return_value = mock_network | |
| isolator = tool_wrapper.NetworkIsolator() | |
| name = isolator.create_isolated_network("zen_isolated") | |
| assert name == "zen_isolated" | |
| mock_docker_module.from_env.return_value.networks.create.assert_called_once() | |
| call_kwargs = mock_docker_module.from_env.return_value.networks.create.call_args.kwargs | |
| assert call_kwargs["internal"] is True | |
| def test_create_isolated_network_docker_exception(self, mock_docker_module, caplog): | |
| mock_docker_module.from_env.side_effect = DockerException("no daemon") | |
| isolator = tool_wrapper.NetworkIsolator() | |
| result = isolator.create_isolated_network("zen_isolated") | |
| assert result is None | |
| assert any("Failed to create network" in rec.message for rec in caplog.records) | |
| def test_apply_egress_filtering_blocked_hosts(self, mock_docker_module): | |
| mock_container = MagicMock() | |
| mock_container.attrs = {"State": {"Pid": 1234}} | |
| mock_client = MagicMock() | |
| mock_client.containers.get.return_value = mock_container | |
| mock_docker_module.from_env.return_value = mock_client | |
| isolator = tool_wrapper.NetworkIsolator() | |
| ok = isolator.apply_egress_filtering( | |
| container_id="abc123", | |
| blocked_hosts=["169.254.169.254"], | |
| ) | |
| assert ok is True | |
| mock_client.containers.get.assert_called_once_with("abc123") | |
| assert ("abc123", "OUTPUT -d 169.254.169.254 -j DROP") in isolator._iptables_rules | |
| def test_apply_egress_filtering_no_blocked_hosts(self, mock_docker_module): | |
| mock_container = MagicMock() | |
| mock_container.attrs = {"State": {"Pid": 5678}} | |
| mock_client = MagicMock() | |
| mock_client.containers.get.return_value = mock_container | |
| mock_docker_module.from_env.return_value = mock_client | |
| isolator = tool_wrapper.NetworkIsolator() | |
| ok = isolator.apply_egress_filtering(container_id="def456") | |
| assert ok is True | |
| assert isolator._iptables_rules == [] | |
| def test_apply_egress_filtering_exception(self, mock_docker_module): | |
| mock_docker_module.from_env.return_value.containers.get.side_effect = RuntimeError("boom") | |
| isolator = tool_wrapper.NetworkIsolator() | |
| ok = isolator.apply_egress_filtering(container_id="bad") | |
| assert ok is False | |
Xet Storage Details
- Size:
- 27.9 kB
- Xet hash:
- a5849997fe87ec5dc44362ea32b92eab0745474e7d08936a83b086c472a030d2
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.