Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tests /unit /test_scout_integration.py
"""Comprehensive unit tests for tools/scout_integration.py
These tests exercise the ScoutSuite integration module with all external
calls (subprocess, cloud CLIs, filesystem operations) mocked.
"""
import asyncio
import json
import logging
import os
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, Mock, mock_open, patch
import pytest
from tools.scout_integration import (
CloudProvider,
ScoutFinding,
ScoutResult,
ScoutSuiteScanner,
register_scout_tools,
scout_osint,
scoutsuite_quick_scan,
scoutsuite_scan_aws,
scoutsuite_scan_azure,
scoutsuite_scan_gcp,
)
# -----------------------------------------------------------------------------
# Sample data
# -----------------------------------------------------------------------------
SAMPLE_SCOUTSUITE_REPORT = {
"provider_code": "aws",
"provider_name": "Amazon Web Services",
"account_id": "123456789012",
"last_run": {
"time": "2023-01-01T00:00:00Z",
"services": ["iam", "s3", "ec2"],
},
"services": {
"iam": {
"findings": {
"password-policy-not-set": {
"description": "No password policy set for IAM users",
"level": "danger",
"id_suffix": "password-policy-not-set",
"path": "iam.password_policy.password-policy-not-set",
"display_path": "iam.password_policy",
"resource_type": "password-policy",
"service": "iam",
"checked_items": 1,
"flagged_items": 1,
"compliance": ["cis", "pci-dss"],
"references": ["https://docs.aws.amazon.com/IAM"],
"remediation": "Set a strong password policy",
},
"root-account-mfa-not-enabled": {
"description": "Root account MFA is not enabled",
"level": "danger",
"id_suffix": "root-account-mfa-not-enabled",
"resource_type": "root-account",
"service": "iam",
"checked_items": 1,
"flagged_items": 1,
"compliance": ["cis"],
"references": [],
"remediation": "Enable MFA for root account",
},
},
},
"s3": {
"findings": {
"bucket-public-access": {
"description": "S3 bucket has public access enabled",
"level": "warning",
"id_suffix": "bucket-public-access",
"resource_type": "s3-bucket",
"service": "s3",
"checked_items": 5,
"flagged_items": 2,
"compliance": [],
"references": [],
"remediation": "Remove public access from S3 bucket",
},
},
},
},
"metadata": {"version": "5.0.0"},
}
# -----------------------------------------------------------------------------
# Autouse fixtures
# -----------------------------------------------------------------------------
@pytest.fixture(autouse=True)
def _stub_shutil_which(monkeypatch):
"""Make ScoutSuite appear installed for every test by default."""
monkeypatch.setattr("tools.scout_integration.shutil.which", lambda _path: "/usr/bin/scout")
@pytest.fixture
def aws_scanner():
return ScoutSuiteScanner(provider=CloudProvider.AWS)
# -----------------------------------------------------------------------------
# Dataclasses / Enums
# -----------------------------------------------------------------------------
class TestCloudProviderEnum:
def test_all_values(self):
assert CloudProvider.AWS.value == "aws"
assert CloudProvider.AZURE.value == "azure"
assert CloudProvider.GCP.value == "gcp"
assert CloudProvider.ALIBABA.value == "aliyun"
assert CloudProvider.ORACLE.value == "oracle"
class TestScoutFinding:
def test_creation_with_all_fields(self):
finding = ScoutFinding(
rule_id="r1",
description="desc",
severity="critical",
provider="aws",
service="iam",
resource_type="policy",
resource_path="iam.policies",
remediation="fix",
compliance=["cis"],
references=["https://x"],
enabled=False,
flagged_items=3,
checked_items=5,
)
assert finding.rule_id == "r1"
assert finding.severity == "critical"
assert finding.enabled is False
assert finding.flagged_items == 3
def test_default_values(self):
finding = ScoutFinding(
rule_id="r2",
description="d",
severity="high",
provider="aws",
service="ec2",
resource_type="instance",
resource_path="ec2",
remediation="fix",
)
assert finding.compliance == []
assert finding.references == []
assert finding.enabled is True
assert finding.flagged_items == 0
assert finding.checked_items == 0
class TestScoutResult:
def test_success_result(self):
result = ScoutResult(
success=True,
provider="aws",
findings=[ScoutFinding("r", "d", "high", "aws", "s3", "b", "s3", "fix")],
scan_time=12.5,
report_path="/tmp/report.json",
summary={"total_findings": 1},
compliance_summary={"cis": "ok"},
)
assert result.success is True
assert result.provider == "aws"
assert len(result.findings) == 1
assert result.scan_time == 12.5
def test_failure_result_defaults(self):
result = ScoutResult(success=False, provider="azure", error="boom")
assert result.success is False
assert result.error == "boom"
assert result.findings == []
assert result.scan_time == 0.0
assert result.report_path is None
assert result.summary == {}
assert result.compliance_summary == {}
# -----------------------------------------------------------------------------
# Initialization & validation
# -----------------------------------------------------------------------------
class TestScoutSuiteScannerInit:
def test_provider_enum(self):
scanner = ScoutSuiteScanner(provider=CloudProvider.AWS)
assert scanner.provider == "aws"
def test_provider_string(self):
scanner = ScoutSuiteScanner(provider="azure")
assert scanner.provider == "azure"
def test_options_preserved(self, tmp_path):
out = str(tmp_path / "reports")
scanner = ScoutSuiteScanner(
provider=CloudProvider.GCP,
scout_path="scout",
profile="prod",
regions=["us-east1"],
services=["iam"],
compliance=["cis"],
output_dir=out,
skip_prompt=False,
thread_config=10,
)
assert scanner.provider == "gcp"
assert scanner.profile == "prod"
assert scanner.regions == ["us-east1"]
assert scanner.services == ["iam"]
assert scanner.compliance == ["cis"]
assert scanner.output_dir == out
assert scanner.skip_prompt is False
assert scanner.thread_config == 10
assert Path(out).exists()
def test_not_found_raises(self, monkeypatch):
monkeypatch.setattr("tools.scout_integration.shutil.which", lambda _path: None)
with pytest.raises(RuntimeError, match="ScoutSuite not found"):
ScoutSuiteScanner(provider=CloudProvider.AWS)
def test_falls_back_to_alternative_name(self, monkeypatch):
calls = []
def fake_which(name):
calls.append(name)
if calls == ["myscout"]:
return None
if name == "scout":
return "/opt/scout"
return None
monkeypatch.setattr("tools.scout_integration.shutil.which", fake_which)
scanner = ScoutSuiteScanner(provider=CloudProvider.AWS, scout_path="myscout")
assert scanner.scout_path == "/opt/scout"
assert calls == ["myscout", "scout"]
class TestGetVersion:
def test_version_from_subprocess(self, aws_scanner):
proc = Mock(returncode=0, stdout="ScoutSuite 5.12.0\n", stderr="")
with patch("tools.scout_integration.subprocess.run", return_value=proc):
assert aws_scanner.get_version() == "ScoutSuite 5.12.0"
def test_version_unknown_on_nonzero(self, aws_scanner):
proc = Mock(returncode=1, stdout="", stderr="err")
with patch("tools.scout_integration.subprocess.run", return_value=proc):
assert aws_scanner.get_version() == "unknown"
def test_version_unknown_on_exception(self, aws_scanner):
with patch("tools.scout_integration.subprocess.run", side_effect=OSError("nope")):
assert aws_scanner.get_version() == "unknown"
# -----------------------------------------------------------------------------
# Command building
# -----------------------------------------------------------------------------
class TestBuildCommand:
def test_basic_aws(self, aws_scanner):
cmd = aws_scanner._build_command()
assert cmd[0] == "/usr/bin/scout"
assert "aws" in cmd
assert "--report-dir" in cmd
assert "--thread-config" in cmd
assert "--no-browser" in cmd
def test_skip_prompt_false(self):
scanner = ScoutSuiteScanner(provider=CloudProvider.AWS, skip_prompt=False)
assert "--no-browser" not in scanner._build_command()
def test_aws_profile_included(self):
scanner = ScoutSuiteScanner(provider=CloudProvider.AWS, profile="prod")
cmd = scanner._build_command()
assert "--profile" in cmd
assert "prod" in cmd
def test_profile_ignored_for_non_aws(self):
scanner = ScoutSuiteScanner(provider=CloudProvider.AZURE, profile="prod")
assert "--profile" not in scanner._build_command()
def test_regions_services_compliance(self):
scanner = ScoutSuiteScanner(
provider=CloudProvider.AWS,
regions=["us-east-1", "eu-west-1"],
services=["iam", "s3"],
compliance=["cis", "pci-dss"],
thread_config=12,
)
cmd = scanner._build_command()
assert "us-east-1,eu-west-1" in cmd
assert "iam,s3" in cmd
assert "cis,pci-dss" in cmd
assert "12" in cmd
# -----------------------------------------------------------------------------
# Report discovery / parsing
# -----------------------------------------------------------------------------
class TestFindLatestReport:
def test_missing_dir_returns_none(self, aws_scanner):
aws_scanner.output_dir = "/nonexistent/path/12345"
assert aws_scanner._find_latest_report() is None
def test_empty_dir_returns_none(self, tmp_path, aws_scanner):
aws_scanner.output_dir = str(tmp_path)
assert aws_scanner._find_latest_report() is None
def test_returns_newest_json(self, tmp_path, aws_scanner):
aws_scanner.output_dir = str(tmp_path)
older = tmp_path / "aws-111111111111-2023-01-01.json"
newer = tmp_path / "aws-222222222222-2023-02-01.json"
older.write_text("{}")
newer.write_text("{}")
# Ensure mtime order regardless of filesystem precision
import time
now = time.time()
os.utime(str(older), (now - 100, now - 100))
os.utime(str(newer), (now, now))
assert aws_scanner._find_latest_report() == str(newer)
class TestParseReport:
def test_valid_json(self, aws_scanner):
data = {"services": {}}
with patch("builtins.open", mock_open(read_data=json.dumps(data))) as m:
assert aws_scanner._parse_report("/tmp/r.json") == data
m.assert_called_once_with("/tmp/r.json", "r", encoding="utf-8")
def test_invalid_json_logs_error(self, aws_scanner, caplog):
with patch("builtins.open", mock_open(read_data="not json")):
with caplog.at_level(logging.ERROR):
assert aws_scanner._parse_report("/tmp/r.json") == {}
assert "Failed to parse report" in caplog.text
def test_io_error_logs_error(self, aws_scanner, caplog):
with patch("builtins.open", side_effect=PermissionError("denied")):
with caplog.at_level(logging.ERROR):
assert aws_scanner._parse_report("/tmp/r.json") == {}
assert "Failed to parse report" in caplog.text
class TestExtractFindings:
def test_empty_services(self, aws_scanner):
assert aws_scanner._extract_findings({}) == []
assert aws_scanner._extract_findings({"services": {}}) == []
def test_sample_report(self, aws_scanner):
findings = aws_scanner._extract_findings(SAMPLE_SCOUTSUITE_REPORT)
assert len(findings) == 3
rule_ids = {f.rule_id for f in findings}
assert rule_ids == {
"password-policy-not-set",
"root-account-mfa-not-enabled",
"bucket-public-access",
}
danger = next(f for f in findings if f.rule_id == "password-policy-not-set")
assert danger.severity == "critical"
assert danger.compliance == ["cis", "pci-dss"]
def test_skips_non_dict_service(self, aws_scanner):
data = {"services": {"iam": "bad"}}
assert aws_scanner._extract_findings(data) == []
def test_skips_non_dict_rule(self, aws_scanner):
data = {"services": {"iam": {"findings": {"rule1": "bad"}}}}
assert aws_scanner._extract_findings(data) == []
def test_skips_disabled_rules(self, aws_scanner):
data = {
"services": {
"iam": {
"findings": {
"enabled-rule": {"level": "high", "enabled": True},
"disabled-rule": {"level": "high", "enabled": False},
}
}
}
}
findings = aws_scanner._extract_findings(data)
assert [f.rule_id for f in findings] == ["enabled-rule"]
def test_unknown_severity_defaults_to_medium(self, aws_scanner):
data = {
"services": {
"iam": {
"findings": {
"weird": {"level": "strange"},
}
}
}
}
findings = aws_scanner._extract_findings(data)
assert findings[0].severity == "medium"
def test_compliance_dict_converted_to_keys(self, aws_scanner):
data = {
"services": {
"iam": {
"findings": {
"rule1": {
"level": "low",
"compliance": {"cis": "1.1", "pci": "2.2"},
}
}
}
}
}
findings = aws_scanner._extract_findings(data)
assert sorted(findings[0].compliance) == ["cis", "pci"]
def test_defaults_for_missing_fields(self, aws_scanner):
data = {"services": {"ec2": {"findings": {"bare": {}}}}}
f = aws_scanner._extract_findings(data)[0]
assert f.rule_id == "bare"
assert f.description == ""
assert f.severity == "medium"
assert f.resource_type == "Unknown"
assert f.remediation == ""
assert f.compliance == []
assert f.references == []
assert f.enabled is True
assert f.flagged_items == 0
assert f.checked_items == 0
class TestGenerateSummary:
def test_counts(self, aws_scanner):
findings = [
ScoutFinding(
rule_id="c1",
description="",
severity="critical",
provider="aws",
service="iam",
resource_type="",
resource_path="",
remediation="",
flagged_items=1,
checked_items=1,
),
ScoutFinding(
rule_id="h1",
description="",
severity="high",
provider="aws",
service="s3",
resource_type="",
resource_path="",
remediation="",
flagged_items=2,
checked_items=5,
),
ScoutFinding(
rule_id="u1",
description="",
severity="weird",
provider="aws",
service="ec2",
resource_type="",
resource_path="",
remediation="",
),
]
summary = aws_scanner._generate_summary(findings)
assert summary["total_findings"] == 3
assert summary["severity_counts"]["critical"] == 1
assert summary["severity_counts"]["high"] == 1
assert summary["severity_counts"]["medium"] == 0
assert summary["service_counts"] == {"iam": 1, "s3": 1, "ec2": 1}
assert summary["total_flagged_items"] == 3
assert summary["total_checked_items"] == 6
# -----------------------------------------------------------------------------
# Credential checks
# -----------------------------------------------------------------------------
class TestCredentialChecks:
# AWS
def test_aws_env_keys(self, monkeypatch, aws_scanner):
monkeypatch.setenv("AWS_ACCESS_KEY_ID", "ak")
monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "sk")
assert aws_scanner._check_aws_credentials() is True
def test_aws_profile_env(self, monkeypatch, aws_scanner):
monkeypatch.setenv("AWS_PROFILE", "prod")
assert aws_scanner._check_aws_credentials() is True
def test_aws_credentials_file(self, tmp_path, monkeypatch, aws_scanner):
monkeypatch.delenv("AWS_ACCESS_KEY_ID", raising=False)
monkeypatch.delenv("AWS_PROFILE", raising=False)
creds = tmp_path / ".aws" / "credentials"
creds.parent.mkdir()
creds.write_text("[default]")
monkeypatch.setattr("tools.scout_integration.Path.home", lambda: tmp_path)
assert aws_scanner._check_aws_credentials() is True
def test_aws_sts_success(self, monkeypatch, aws_scanner):
monkeypatch.delenv("AWS_ACCESS_KEY_ID", raising=False)
monkeypatch.delenv("AWS_PROFILE", raising=False)
monkeypatch.setattr("tools.scout_integration.Path.home", lambda: Path("/no-home"))
proc = Mock(returncode=0)
with patch("subprocess.run", return_value=proc):
assert aws_scanner._check_aws_credentials() is True
def test_aws_no_creds(self, monkeypatch, aws_scanner):
monkeypatch.delenv("AWS_ACCESS_KEY_ID", raising=False)
monkeypatch.delenv("AWS_SECRET_ACCESS_KEY", raising=False)
monkeypatch.delenv("AWS_PROFILE", raising=False)
monkeypatch.setattr("tools.scout_integration.Path.home", lambda: Path("/no-home"))
proc = Mock(returncode=1)
with patch("subprocess.run", return_value=proc):
assert aws_scanner._check_aws_credentials() is False
# Azure
def test_azure_client_secret(self, monkeypatch):
scanner = ScoutSuiteScanner(provider=CloudProvider.AZURE)
monkeypatch.setenv("AZURE_CLIENT_ID", "cid")
monkeypatch.setenv("AZURE_CLIENT_SECRET", "secret")
assert scanner._check_azure_credentials() is True
def test_azure_tenant_env(self, monkeypatch):
scanner = ScoutSuiteScanner(provider=CloudProvider.AZURE)
monkeypatch.setenv("AZURE_TENANT_ID", "tid")
assert scanner._check_azure_credentials() is True
def test_azure_cli_success(self, monkeypatch):
scanner = ScoutSuiteScanner(provider=CloudProvider.AZURE)
monkeypatch.delenv("AZURE_CLIENT_ID", raising=False)
monkeypatch.delenv("AZURE_TENANT_ID", raising=False)
proc = Mock(returncode=0)
with patch("subprocess.run", return_value=proc):
assert scanner._check_azure_credentials() is True
def test_azure_no_creds(self, monkeypatch):
scanner = ScoutSuiteScanner(provider=CloudProvider.AZURE)
monkeypatch.delenv("AZURE_CLIENT_ID", raising=False)
monkeypatch.delenv("AZURE_CLIENT_SECRET", raising=False)
monkeypatch.delenv("AZURE_TENANT_ID", raising=False)
proc = Mock(returncode=1)
with patch("subprocess.run", return_value=proc):
assert scanner._check_azure_credentials() is False
# GCP
def test_gcp_env_creds(self, monkeypatch):
scanner = ScoutSuiteScanner(provider=CloudProvider.GCP)
monkeypatch.setenv("GOOGLE_APPLICATION_CREDENTIALS", "/path/to/creds.json")
assert scanner._check_gcp_credentials() is True
def test_gcp_gcloud_db(self, tmp_path, monkeypatch):
scanner = ScoutSuiteScanner(provider=CloudProvider.GCP)
monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False)
db = tmp_path / ".config" / "gcloud" / "credentials.db"
db.parent.mkdir(parents=True)
db.write_text("x")
monkeypatch.setattr("tools.scout_integration.Path.home", lambda: tmp_path)
assert scanner._check_gcp_credentials() is True
def test_gcp_adc_file(self, tmp_path, monkeypatch):
scanner = ScoutSuiteScanner(provider=CloudProvider.GCP)
monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False)
adc = tmp_path / ".config" / "gcloud" / "application_default_credentials.json"
adc.parent.mkdir(parents=True)
adc.write_text("{}")
monkeypatch.setattr("tools.scout_integration.Path.home", lambda: tmp_path)
assert scanner._check_gcp_credentials() is True
def test_gcp_no_creds(self, monkeypatch):
scanner = ScoutSuiteScanner(provider=CloudProvider.GCP)
monkeypatch.delenv("GOOGLE_APPLICATION_CREDENTIALS", raising=False)
monkeypatch.setattr("tools.scout_integration.Path.home", lambda: Path("/no-home"))
assert scanner._check_gcp_credentials() is False
def test_check_credentials_delegates_aws(self, monkeypatch):
scanner = ScoutSuiteScanner(provider=CloudProvider.AWS)
monkeypatch.setenv("AWS_ACCESS_KEY_ID", "ak")
monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "sk")
assert scanner._check_credentials() is True
def test_check_credentials_delegates_azure(self, monkeypatch):
scanner = ScoutSuiteScanner(provider=CloudProvider.AZURE)
monkeypatch.setenv("AZURE_CLIENT_ID", "x")
monkeypatch.setenv("AZURE_CLIENT_SECRET", "y")
assert scanner._check_credentials() is True
def test_check_credentials_delegates_gcp(self, monkeypatch):
scanner = ScoutSuiteScanner(provider=CloudProvider.GCP)
monkeypatch.setenv("GOOGLE_APPLICATION_CREDENTIALS", "/path/creds.json")
assert scanner._check_credentials() is True
def test_aws_sts_exception_returns_false(self, monkeypatch, aws_scanner):
monkeypatch.delenv("AWS_ACCESS_KEY_ID", raising=False)
monkeypatch.delenv("AWS_SECRET_ACCESS_KEY", raising=False)
monkeypatch.delenv("AWS_PROFILE", raising=False)
monkeypatch.setattr("tools.scout_integration.Path.home", lambda: Path("/no-home"))
with patch("subprocess.run", side_effect=FileNotFoundError):
assert aws_scanner._check_aws_credentials() is False
def test_azure_cli_exception_returns_false(self, monkeypatch):
scanner = ScoutSuiteScanner(provider=CloudProvider.AZURE)
monkeypatch.delenv("AZURE_CLIENT_ID", raising=False)
monkeypatch.delenv("AZURE_CLIENT_SECRET", raising=False)
monkeypatch.delenv("AZURE_TENANT_ID", raising=False)
with patch("subprocess.run", side_effect=FileNotFoundError):
assert scanner._check_azure_credentials() is False
def test_unknown_provider_returns_true(self):
scanner = ScoutSuiteScanner(provider="aliyun")
assert scanner._check_credentials() is True
# -----------------------------------------------------------------------------
# Subprocess wrapper
# -----------------------------------------------------------------------------
class TestRunSubprocess:
def test_delegates_to_subprocess_run(self, aws_scanner):
proc = Mock(returncode=0, stdout="", stderr="")
with patch("subprocess.run", return_value=proc) as m:
result = aws_scanner._run_subprocess(["scout", "aws"])
assert result is proc
m.assert_called_once_with(["scout", "aws"], capture_output=True, text=True)
# -----------------------------------------------------------------------------
# Async scan
# -----------------------------------------------------------------------------
class TestScanAsync:
@pytest.mark.asyncio
async def test_aws_scan_success(self, aws_scanner):
proc = Mock(returncode=0, stdout="", stderr="")
with patch.object(aws_scanner, "_check_credentials", return_value=True):
with patch.object(aws_scanner, "_run_subprocess", return_value=proc):
with patch.object(aws_scanner, "_find_latest_report", return_value="/tmp/report.json"):
with patch.object(aws_scanner, "_parse_report", return_value=SAMPLE_SCOUTSUITE_REPORT):
result = await aws_scanner.scan()
assert result.success is True
assert result.provider == "aws"
assert len(result.findings) == 3
assert result.report_path == "/tmp/report.json"
assert result.summary["total_findings"] == 3
assert result.scan_time >= 0
@pytest.mark.asyncio
async def test_azure_scan_success(self):
scanner = ScoutSuiteScanner(provider=CloudProvider.AZURE)
proc = Mock(returncode=0, stdout="", stderr="")
with patch.object(scanner, "_check_credentials", return_value=True):
with patch.object(scanner, "_run_subprocess", return_value=proc):
with patch.object(scanner, "_find_latest_report", return_value="/tmp/azure.json"):
with patch.object(scanner, "_parse_report", return_value={"services": {}}):
result = await scanner.scan()
assert result.success is True
assert result.provider == "azure"
@pytest.mark.asyncio
async def test_gcp_scan_success(self):
scanner = ScoutSuiteScanner(provider=CloudProvider.GCP)
proc = Mock(returncode=0, stdout="", stderr="")
with patch.object(scanner, "_check_credentials", return_value=True):
with patch.object(scanner, "_run_subprocess", return_value=proc):
with patch.object(scanner, "_find_latest_report", return_value="/tmp/gcp.json"):
with patch.object(scanner, "_parse_report", return_value={"services": {}}):
result = await scanner.scan()
assert result.success is True
assert result.provider == "gcp"
@pytest.mark.asyncio
async def test_no_credentials(self, aws_scanner):
with patch.object(aws_scanner, "_check_credentials", return_value=False):
result = await aws_scanner.scan()
assert result.success is False
assert "credentials" in result.error.lower()
assert result.scan_time == 0.0
@pytest.mark.asyncio
async def test_scoutsuite_failure_with_error_in_stderr(self, aws_scanner):
proc = Mock(returncode=1, stdout="", stderr="An error occurred")
with patch.object(aws_scanner, "_check_credentials", return_value=True):
with patch.object(aws_scanner, "_run_subprocess", return_value=proc):
result = await aws_scanner.scan()
assert result.success is False
assert "ScoutSuite failed" in result.error
@pytest.mark.asyncio
async def test_nonzero_but_no_error_keyword_continues(self, aws_scanner):
proc = Mock(returncode=1, stdout="", stderr="warning only")
with patch.object(aws_scanner, "_check_credentials", return_value=True):
with patch.object(aws_scanner, "_run_subprocess", return_value=proc):
with patch.object(aws_scanner, "_find_latest_report", return_value="/tmp/report.json"):
with patch.object(aws_scanner, "_parse_report", return_value={"services": {}}):
result = await aws_scanner.scan()
assert result.success is True
@pytest.mark.asyncio
async def test_no_report_generated(self, aws_scanner):
proc = Mock(returncode=0, stdout="", stderr="")
with patch.object(aws_scanner, "_check_credentials", return_value=True):
with patch.object(aws_scanner, "_run_subprocess", return_value=proc):
with patch.object(aws_scanner, "_find_latest_report", return_value=None):
result = await aws_scanner.scan()
assert result.success is False
assert "No report generated" in result.error
@pytest.mark.asyncio
async def test_timeout(self, aws_scanner):
with patch.object(aws_scanner, "_check_credentials", return_value=True):
with patch.object(aws_scanner, "_run_subprocess", side_effect=asyncio.TimeoutError):
result = await aws_scanner.scan(timeout=1)
assert result.success is False
assert "timed out" in result.error.lower()
assert result.scan_time >= 0
@pytest.mark.asyncio
async def test_generic_exception(self, aws_scanner):
with patch.object(aws_scanner, "_check_credentials", return_value=True):
with patch.object(aws_scanner, "_run_subprocess", side_effect=ValueError("boom")):
result = await aws_scanner.scan()
assert result.success is False
assert result.error == "boom"
assert result.scan_time >= 0
@pytest.mark.asyncio
async def test_accepts_progress_callback(self, aws_scanner):
proc = Mock(returncode=0, stdout="", stderr="")
cb = Mock()
with patch.object(aws_scanner, "_check_credentials", return_value=True):
with patch.object(aws_scanner, "_run_subprocess", return_value=proc):
with patch.object(aws_scanner, "_find_latest_report", return_value="/tmp/report.json"):
with patch.object(aws_scanner, "_parse_report", return_value={"services": {}}):
result = await aws_scanner.scan(progress_callback=cb)
assert result.success is True
# -----------------------------------------------------------------------------
# Output parsing / normalization
# -----------------------------------------------------------------------------
class TestParseOutput:
def test_parse_output_structure(self, aws_scanner):
finding = ScoutFinding(
rule_id="r1",
description="d",
severity="high",
provider="aws",
service="s3",
resource_type="bucket",
resource_path="s3",
remediation="fix",
compliance=["cis"],
references=["https://x"],
flagged_items=2,
checked_items=5,
)
result = ScoutResult(success=True, provider="aws", findings=[finding])
parsed = aws_scanner.parse_output(result)
assert len(parsed) == 1
assert parsed[0]["tool"] == "scoutsuite"
assert parsed[0]["rule_id"] == "r1"
assert parsed[0]["severity"] == "high"
assert parsed[0]["flagged_items"] == 2
class TestNormalizeFindings:
def test_normalization(self, aws_scanner):
findings = [
{
"tool": "scoutsuite",
"rule_id": "my-rule",
"description": "desc",
"severity": "HIGH",
"provider": "aws",
"service": "s3",
"resource_type": "bucket",
"remediation": "fix",
"compliance": ["cis"],
"references": ["https://x"],
"flagged_items": 2,
"checked_items": 5,
}
]
norm = aws_scanner.normalize_findings(findings)
assert len(norm) == 1
n = norm[0]
assert n["tool"] == "scoutsuite"
assert n["target"] == "aws:s3"
assert n["severity"] == "high"
assert n["title"] == "My Rule"
assert n["evidence"]["flagged_items"] == 2
assert n["compliance"] == ["cis"]
def test_empty_list(self, aws_scanner):
assert aws_scanner.normalize_findings([]) == []
def test_defaults_for_missing_fields(self, aws_scanner):
norm = aws_scanner.normalize_findings([{}])
n = norm[0]
assert n["target"] == "cloud:unknown"
assert n["severity"] == "medium"
assert n["title"] == "Unknown Issue"
assert n["evidence"]["flagged_items"] == 0
assert n["compliance"] == []
# -----------------------------------------------------------------------------
# Risk scoring integration
# -----------------------------------------------------------------------------
class TestRiskScoringIntegration:
def test_normalized_finding_has_risk_relevant_fields(self, aws_scanner):
findings = [
{
"rule_id": "r1",
"description": "d",
"severity": "critical",
"provider": "aws",
"service": "iam",
"resource_type": "policy",
"remediation": "fix",
"compliance": ["cis"],
"references": [],
"flagged_items": 1,
"checked_items": 1,
}
]
norm = aws_scanner.normalize_findings(findings)[0]
assert "severity" in norm
assert "evidence" in norm
assert "remediation" in norm
assert "references" in norm
assert "compliance" in norm
assert norm["severity"] == "critical"
# -----------------------------------------------------------------------------
# LangChain tool wrappers
# -----------------------------------------------------------------------------
class TestLangChainTools:
def test_scoutsuite_scan_aws_success(self):
mock_result = Mock()
mock_result.success = True
mock_result.scan_time = 42.0
mock_result.report_path = "/tmp/aws.json"
mock_result.summary = {
"severity_counts": {"critical": 1, "high": 2, "medium": 0, "low": 0},
"total_findings": 3,
}
with patch.object(ScoutSuiteScanner, "scan", new_callable=AsyncMock, return_value=mock_result):
text = scoutsuite_scan_aws(profile="default", regions="us-east-1", services="iam")
assert "ScoutSuite AWS Scan Complete" in text
assert "42.00s" in text
assert "Critical: 1" in text
def test_scoutsuite_scan_aws_failure(self):
mock_result = Mock()
mock_result.success = False
mock_result.error = "no creds"
with patch.object(ScoutSuiteScanner, "scan", new_callable=AsyncMock, return_value=mock_result):
text = scoutsuite_scan_aws()
assert "failed" in text.lower()
assert "no creds" in text
def test_scoutsuite_scan_azure_success(self):
mock_result = Mock()
mock_result.success = True
mock_result.findings = []
mock_result.report_path = "/tmp/azure.json"
with patch.object(ScoutSuiteScanner, "scan", new_callable=AsyncMock, return_value=mock_result):
text = scoutsuite_scan_azure()
assert "Azure Scan Complete" in text
def test_scoutsuite_scan_azure_failure(self):
mock_result = Mock()
mock_result.success = False
mock_result.error = "azure down"
with patch.object(ScoutSuiteScanner, "scan", new_callable=AsyncMock, return_value=mock_result):
text = scoutsuite_scan_azure()
assert "failed" in text.lower()
assert "azure down" in text
def test_scoutsuite_scan_gcp_sets_project_env(self, monkeypatch):
monkeypatch.delenv("GOOGLE_CLOUD_PROJECT", raising=False)
mock_result = Mock()
mock_result.success = True
mock_result.findings = []
mock_result.report_path = "/tmp/gcp.json"
with patch.object(ScoutSuiteScanner, "scan", new_callable=AsyncMock, return_value=mock_result):
text = scoutsuite_scan_gcp(project_id="my-project")
assert os.environ.get("GOOGLE_CLOUD_PROJECT") == "my-project"
assert "my-project" in text
def test_scoutsuite_scan_gcp_failure(self):
mock_result = Mock()
mock_result.success = False
mock_result.error = "gcp fail"
with patch.object(ScoutSuiteScanner, "scan", new_callable=AsyncMock, return_value=mock_result):
text = scoutsuite_scan_gcp()
assert "failed" in text.lower()
def test_quick_scan_unknown_provider(self):
assert "Unknown provider" in scoutsuite_quick_scan("unknown")
def test_quick_scan_success(self):
f = ScoutFinding(
rule_id="r1",
description="",
severity="critical",
provider="aws",
service="iam",
resource_type="",
resource_path="",
remediation="",
)
mock_result = Mock()
mock_result.success = True
mock_result.findings = [f, ScoutFinding("r2", "", "high", "aws", "s3", "", "", "")]
mock_result.report_path = "/tmp/q.json"
with patch.object(ScoutSuiteScanner, "scan", new_callable=AsyncMock, return_value=mock_result):
text = scoutsuite_quick_scan("aws")
assert "High/Critical Issues: 2" in text
assert "Total Findings: 2" in text
def test_quick_scan_failure(self):
mock_result = Mock()
mock_result.success = False
mock_result.error = "oops"
with patch.object(ScoutSuiteScanner, "scan", new_callable=AsyncMock, return_value=mock_result):
text = scoutsuite_quick_scan("gcp")
assert "Scan failed" in text
assert "oops" in text
def test_scout_osint_alias(self):
assert scout_osint is scoutsuite_scan_aws
# -----------------------------------------------------------------------------
# Tool registry integration
# -----------------------------------------------------------------------------
class TestRegisterScoutTools:
def test_register_does_not_raise(self):
# The registry is already imported; this should be idempotent.
register_scout_tools()
def test_register_logs_warning_on_exception(self, caplog):
import tools.scout_integration as _scout
with patch.object(_scout, "LANGCHAIN_AVAILABLE", True):
with patch.object(_scout.registry, "register", side_effect=RuntimeError("bad")) as mock_reg:
with caplog.at_level(logging.WARNING):
register_scout_tools()
assert "Could not register ScoutSuite tools" in caplog.text
assert mock_reg.call_count >= 1
def test_register_calls_registry_when_available(self):
import tools.scout_integration as _scout
with patch.object(_scout, "LANGCHAIN_AVAILABLE", True):
with patch.object(_scout.registry, "register") as mock_reg:
register_scout_tools()
assert mock_reg.call_count == 4
def test_register_no_op_when_langchain_unavailable(self):
import tools.scout_integration as _scout
with patch.object(_scout, "LANGCHAIN_AVAILABLE", False):
with patch.object(_scout.registry, "register") as mock_reg:
register_scout_tools()
assert mock_reg.call_count == 0
def test_register_no_op_when_registry_unavailable(self):
import tools.scout_integration as _scout
with patch.object(_scout, "TOOL_REGISTRY_AVAILABLE", False):
with patch.object(_scout.registry, "register") as mock_reg:
register_scout_tools()
assert mock_reg.call_count == 0
# -----------------------------------------------------------------------------
# Module exports
# -----------------------------------------------------------------------------
class TestModuleExports:
def test_all_exports_present(self):
import tools.scout_integration as m
for name in m.__all__:
assert hasattr(m, name)
"""Comprehensive unit tests for tools/scout_integration.py
These tests exercise the ScoutSuite integration module with all external
calls (subprocess, cloud CLIs, filesystem operations) mocked.
"""
import asyncio
import json
import logging
import os
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, Mock, mock_open, patch
import pytest
from tools.scout_integration import (
CloudProvider,
ScoutFinding,
ScoutResult,
ScoutSuiteScanner,
register_scout_tools,
scout_osint,
scoutsuite_quick_scan,
scoutsuite_scan_aws,
scoutsuite_scan_azure,
scoutsuite_scan_gcp,
)
# -----------------------------------------------------------------------------
# Sample data
# -----------------------------------------------------------------------------
SAMPLE_SCOUTSUITE_REPORT = {
"provider_code": "aws",
"provider_name": "Amazon Web Services",
"account_id": "123456789012",
"last_run": {
"time": "2023-01-01T00:00:00Z",
"services": ["iam", "s3", "ec2"],
},
"services": {
"iam": {
"findings": {
"password-policy-not-set": {
"description": "No password policy set for IAM users",
"level": "danger",
"id_suffix": "password-policy-not-set",
"path": "iam.password_policy.password-policy-not-set",
"display_path": "iam.password_policy",
"resource_type": "password-policy",
"service": "iam",
"checked_items": 1,
"flagged_items": 1,
"compliance": ["cis", "pci-dss"],
"references": ["https://docs.aws.amazon.com/IAM"],
"remediation": "Set a strong password policy",
},
"root-account-mfa-not-enabled": {
"description": "Root account MFA is not enabled",
"level": "danger",
"id_suffix": "root-account-mfa-not-enabled",
"resource_type": "root-account",
"service": "iam",
"checked_items": 1,
"flagged_items": 1,
"compliance": ["cis"],
"references": [],
"remediation": "Enable MFA for root account",
},
},
},
"s3": {
"findings": {
"bucket-public-access": {
"description": "S3 bucket has public access enabled",
"level": "warning",
"id_suffix": "bucket-public-access",
"resource_type": "s3-bucket",
"service": "s3",
"checked_items": 5,
"flagged_items": 2,
"compliance": [],
"references": [],
"remediation": "Remove public access from S3 bucket",
},
},
},
},
"metadata": {"version": "5.0.0"},
}
# -----------------------------------------------------------------------------
# Autouse fixtures
# -----------------------------------------------------------------------------
def _stub_shutil_which(monkeypatch):
"""Make ScoutSuite appear installed for every test by default."""
Xet Storage Details
- Size:
- 40.7 kB
- Xet hash:
- 0e0ef77ec90cb3f95fd88ef83df22fb87a125229de8a30b062a8f7f3ec683c22
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.