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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
HexStrike AI MCP Test Suite
|
| 4 |
+
Testes de validação para o sistema HexStrike AI MCP
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import sys
|
| 8 |
+
import subprocess
|
| 9 |
+
import time
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
# Cores para output
|
| 13 |
+
GREEN = '\033[92m'
|
| 14 |
+
RED = '\033[91m'
|
| 15 |
+
YELLOW = '\033[93m'
|
| 16 |
+
RESET = '\033[0m'
|
| 17 |
+
BOLD = '\033[1m'
|
| 18 |
+
|
| 19 |
+
def print_header(text):
|
| 20 |
+
"""Imprime cabeçalho de seção"""
|
| 21 |
+
print(f"\n{BOLD}{'='*60}{RESET}")
|
| 22 |
+
print(f"{BOLD}{text}{RESET}")
|
| 23 |
+
print(f"{BOLD}{'='*60}{RESET}\n")
|
| 24 |
+
|
| 25 |
+
def print_success(text):
|
| 26 |
+
"""Imprime mensagem de sucesso"""
|
| 27 |
+
print(f"{GREEN}✅ {text}{RESET}")
|
| 28 |
+
|
| 29 |
+
def print_error(text):
|
| 30 |
+
"""Imprime mensagem de erro"""
|
| 31 |
+
print(f"{RED}❌ {text}{RESET}")
|
| 32 |
+
|
| 33 |
+
def print_warning(text):
|
| 34 |
+
"""Imprime mensagem de aviso"""
|
| 35 |
+
print(f"{YELLOW}⚠️ {text}{RESET}")
|
| 36 |
+
|
| 37 |
+
def check_file_exists(filepath, description):
|
| 38 |
+
"""Verifica se arquivo existe"""
|
| 39 |
+
path = Path(filepath)
|
| 40 |
+
if path.exists():
|
| 41 |
+
print_success(f"{description}: {filepath}")
|
| 42 |
+
return True
|
| 43 |
+
else:
|
| 44 |
+
print_error(f"{description}: {filepath} não encontrado")
|
| 45 |
+
return False
|
| 46 |
+
|
| 47 |
+
def check_python_syntax(filepath):
|
| 48 |
+
"""Verifica sintaxe Python"""
|
| 49 |
+
try:
|
| 50 |
+
result = subprocess.run(
|
| 51 |
+
['python3', '-m', 'py_compile', filepath],
|
| 52 |
+
capture_output=True,
|
| 53 |
+
text=True
|
| 54 |
+
)
|
| 55 |
+
if result.returncode == 0:
|
| 56 |
+
print_success(f"Sintaxe válida: {filepath}")
|
| 57 |
+
return True
|
| 58 |
+
else:
|
| 59 |
+
print_error(f"Erro de sintaxe: {filepath}")
|
| 60 |
+
print(f" {result.stderr}")
|
| 61 |
+
return False
|
| 62 |
+
except Exception as e:
|
| 63 |
+
print_error(f"Erro ao verificar sintaxe: {e}")
|
| 64 |
+
return False
|
| 65 |
+
|
| 66 |
+
def check_command_exists(command):
|
| 67 |
+
"""Verifica se comando existe"""
|
| 68 |
+
result = subprocess.run(
|
| 69 |
+
['which', command],
|
| 70 |
+
capture_output=True,
|
| 71 |
+
text=True
|
| 72 |
+
)
|
| 73 |
+
if result.returncode == 0:
|
| 74 |
+
path = result.stdout.strip()
|
| 75 |
+
print_success(f"{command}: {path}")
|
| 76 |
+
return True
|
| 77 |
+
else:
|
| 78 |
+
print_warning(f"{command}: não instalado")
|
| 79 |
+
return False
|
| 80 |
+
|
| 81 |
+
def check_dependencies():
|
| 82 |
+
"""Verifica dependências Python"""
|
| 83 |
+
print_header("Verificando Dependências Python")
|
| 84 |
+
|
| 85 |
+
# Dependências essenciais (requeridas)
|
| 86 |
+
essential_deps = [
|
| 87 |
+
('flask', 'Flask'),
|
| 88 |
+
('requests', 'Requests'),
|
| 89 |
+
('psutil', 'Psutil'),
|
| 90 |
+
]
|
| 91 |
+
|
| 92 |
+
# Dependências opcionais
|
| 93 |
+
optional_deps = [
|
| 94 |
+
('fastmcp', 'FastMCP'),
|
| 95 |
+
('beautifulsoup4', 'BeautifulSoup4'),
|
| 96 |
+
('selenium', 'Selenium'),
|
| 97 |
+
('aiohttp', 'AioHTTP'),
|
| 98 |
+
('mitmproxy', 'Mitmproxy'),
|
| 99 |
+
('angr', 'Angr'),
|
| 100 |
+
('pwntools', 'Pwntools'),
|
| 101 |
+
]
|
| 102 |
+
|
| 103 |
+
all_essential_installed = True
|
| 104 |
+
for package, import_name in essential_deps:
|
| 105 |
+
try:
|
| 106 |
+
__import__(import_name.lower() if import_name.lower() != 'psutil' else 'psutil')
|
| 107 |
+
version = sys.modules[import_name.lower() if import_name.lower() != 'psutil' else 'psutil'].__version__
|
| 108 |
+
print_success(f"{package}: instalado (versão {version})")
|
| 109 |
+
except ImportError:
|
| 110 |
+
print_warning(f"{package}: não instalado")
|
| 111 |
+
all_essential_installed = False
|
| 112 |
+
|
| 113 |
+
# Dependências opcionais
|
| 114 |
+
for package, import_name in optional_deps:
|
| 115 |
+
try:
|
| 116 |
+
__import__(import_name.lower() if import_name.lower() != 'psutil' else 'psutil')
|
| 117 |
+
version = sys.modules[import_name.lower() if import_name.lower() != 'psutil' else 'psutil'].__version__
|
| 118 |
+
print_success(f"{package}: instalado (versão {version})")
|
| 119 |
+
except ImportError:
|
| 120 |
+
print_warning(f"{package}: não instalado (opcional)")
|
| 121 |
+
|
| 122 |
+
return all_essential_installed
|
| 123 |
+
|
| 124 |
+
def check_security_tools():
|
| 125 |
+
"""Verifica ferramentas de segurança"""
|
| 126 |
+
print_header("Verificando Ferramentas de Segurança")
|
| 127 |
+
|
| 128 |
+
# Ferramentas essenciais
|
| 129 |
+
essential_tools = ['nmap', 'gobuster']
|
| 130 |
+
|
| 131 |
+
# Ferramentas opcionais
|
| 132 |
+
optional_tools = ['nuclei', 'trivy']
|
| 133 |
+
|
| 134 |
+
all_essential_found = True
|
| 135 |
+
found = []
|
| 136 |
+
missing_essential = []
|
| 137 |
+
|
| 138 |
+
for tool in essential_tools:
|
| 139 |
+
if check_command_exists(tool):
|
| 140 |
+
found.append(tool)
|
| 141 |
+
else:
|
| 142 |
+
print_warning(f"{tool}: não instalado (essencial)")
|
| 143 |
+
missing_essential.append(tool)
|
| 144 |
+
all_essential_found = False
|
| 145 |
+
|
| 146 |
+
# Ferramentas opcionais
|
| 147 |
+
for tool in optional_tools:
|
| 148 |
+
if check_command_exists(tool):
|
| 149 |
+
found.append(tool)
|
| 150 |
+
else:
|
| 151 |
+
print_warning(f"{tool}: não instalado (opcional)")
|
| 152 |
+
|
| 153 |
+
return all_essential_found, found, missing_essential
|
| 154 |
+
|
| 155 |
+
def check_venv():
|
| 156 |
+
"""Verifica ambiente virtual"""
|
| 157 |
+
print_header("Verificando Ambiente Virtual")
|
| 158 |
+
|
| 159 |
+
venv_path = Path("hexstrike-env")
|
| 160 |
+
if check_file_exists(str(venv_path), "Ambiente virtual"):
|
| 161 |
+
# Verificar binário Python
|
| 162 |
+
python_path = venv_path / "bin" / "python"
|
| 163 |
+
if check_file_exists(str(python_path), "Python virtual"):
|
| 164 |
+
return True
|
| 165 |
+
|
| 166 |
+
return False
|
| 167 |
+
|
| 168 |
+
def test_server_startup():
|
| 169 |
+
"""Testa inicialização do servidor"""
|
| 170 |
+
print_header("Testando Inicialização do Servidor")
|
| 171 |
+
|
| 172 |
+
# Verificar se servidor está rodando
|
| 173 |
+
try:
|
| 174 |
+
import requests
|
| 175 |
+
response = requests.get('http://127.0.0.1:8888/health', timeout=5)
|
| 176 |
+
if response.status_code == 200:
|
| 177 |
+
data = response.json()
|
| 178 |
+
status = data.get('status', 'unknown')
|
| 179 |
+
print_success(f"Servidor respondendo: status={status}")
|
| 180 |
+
return True
|
| 181 |
+
else:
|
| 182 |
+
print_warning(f"Servidor retornou código: {response.status_code}")
|
| 183 |
+
return False
|
| 184 |
+
except requests.exceptions.ConnectionError:
|
| 185 |
+
print_warning("Servidor não está rodando. Tentando iniciar...")
|
| 186 |
+
# Tentar iniciar servidor
|
| 187 |
+
try:
|
| 188 |
+
result = subprocess.run(
|
| 189 |
+
['python3', 'hexstrike_server.py', '--help'],
|
| 190 |
+
capture_output=True,
|
| 191 |
+
text=True,
|
| 192 |
+
timeout=5
|
| 193 |
+
)
|
| 194 |
+
if result.returncode == 0:
|
| 195 |
+
print_success("Servidor aceita argumentos --help")
|
| 196 |
+
return True
|
| 197 |
+
else:
|
| 198 |
+
print_warning("Servidor retornou código não-zero")
|
| 199 |
+
return False
|
| 200 |
+
except Exception as e:
|
| 201 |
+
print_error(f"Erro ao iniciar servidor: {e}")
|
| 202 |
+
return False
|
| 203 |
+
except Exception as e:
|
| 204 |
+
print_error(f"Erro ao conectar ao servidor: {e}")
|
| 205 |
+
return False
|
| 206 |
+
|
| 207 |
+
def check_mcp_config():
|
| 208 |
+
"""Verifica configuração MCP"""
|
| 209 |
+
print_header("Verificando Configuração MCP")
|
| 210 |
+
|
| 211 |
+
config_file = "hexstrike-ai-mcp.json"
|
| 212 |
+
return check_file_exists(config_file, "Configuração MCP")
|
| 213 |
+
|
| 214 |
+
def run_all_tests():
|
| 215 |
+
"""Executa todos os testes"""
|
| 216 |
+
print(f"{BOLD}{'🧪 HEXSTRIKE AI - SUITE DE TESTES'}{RESET}")
|
| 217 |
+
print(f"{BOLD}{'='*60}{RESET}")
|
| 218 |
+
|
| 219 |
+
results = {
|
| 220 |
+
"Arquivos principais": [],
|
| 221 |
+
"Sintaxe Python": [],
|
| 222 |
+
"Dependências": [],
|
| 223 |
+
"Ferramentas de segurança": [],
|
| 224 |
+
"Ambiente virtual": [],
|
| 225 |
+
"Configuração MCP": [],
|
| 226 |
+
"Servidor": []
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
# Verificar arquivos principais
|
| 230 |
+
print_header("Verificando Arquivos Principais")
|
| 231 |
+
main_files = [
|
| 232 |
+
("hexstrike_server.py", "Servidor HexStrike"),
|
| 233 |
+
("hexstrike_mcp.py", "Cliente MCP"),
|
| 234 |
+
("requirements.txt", "Dependências"),
|
| 235 |
+
("README.md", "Documentação"),
|
| 236 |
+
]
|
| 237 |
+
|
| 238 |
+
for filepath, desc in main_files:
|
| 239 |
+
results["Arquivos principais"].append(check_file_exists(filepath, desc))
|
| 240 |
+
|
| 241 |
+
# Verificar sintaxe Python
|
| 242 |
+
print_header("Verificando Sintaxe Python")
|
| 243 |
+
for filepath, _ in main_files[:2]:
|
| 244 |
+
if Path(filepath).exists():
|
| 245 |
+
results["Sintaxe Python"].append(check_python_syntax(filepath))
|
| 246 |
+
|
| 247 |
+
# Verificar dependências
|
| 248 |
+
results["Dependências"].append(check_dependencies())
|
| 249 |
+
|
| 250 |
+
# Verificar ferramentas de segurança
|
| 251 |
+
all_tools, found, missing = check_security_tools()
|
| 252 |
+
results["Ferramentas de segurança"].append(all_tools)
|
| 253 |
+
if missing:
|
| 254 |
+
print_warning(f"Ferramentas ausentes: {', '.join(missing)}")
|
| 255 |
+
|
| 256 |
+
# Verificar ambiente virtual
|
| 257 |
+
results["Ambiente virtual"].append(check_venv())
|
| 258 |
+
|
| 259 |
+
# Verificar configuração MCP
|
| 260 |
+
results["Configuração MCP"].append(check_mcp_config())
|
| 261 |
+
|
| 262 |
+
# Testar servidor
|
| 263 |
+
results["Servidor"].append(test_server_startup())
|
| 264 |
+
|
| 265 |
+
# Resumo final
|
| 266 |
+
print_header("📊 RESUMO DOS TESTES")
|
| 267 |
+
|
| 268 |
+
all_passed = True
|
| 269 |
+
for category, passed_list in results.items():
|
| 270 |
+
if passed_list and all(passed_list):
|
| 271 |
+
print_success(f"{category}: OK")
|
| 272 |
+
else:
|
| 273 |
+
print_error(f"{category}: FALHA")
|
| 274 |
+
all_passed = False
|
| 275 |
+
|
| 276 |
+
print(f"\n{BOLD}{'='*60}{RESET}")
|
| 277 |
+
if all_passed:
|
| 278 |
+
print(f"{GREEN}{BOLD}🎉 TODOS OS TESTES PASSARAM!{RESET}")
|
| 279 |
+
print(f"{GREEN}O HexStrike AI está pronto para uso.{RESET}")
|
| 280 |
+
else:
|
| 281 |
+
print(f"{YELLOW}{BOLD}⚠️ ALGUNS TESTES FALHARAM{RESET}")
|
| 282 |
+
print(f"{YELLOW}Revise as dependências e ferramentas acima.{RESET}")
|
| 283 |
+
print(f"{BOLD}{'='*60}{RESET}\n")
|
| 284 |
+
|
| 285 |
+
return all_passed
|
| 286 |
+
|
| 287 |
+
if __name__ == "__main__":
|
| 288 |
+
import os
|
| 289 |
+
os.chdir(Path(__file__).parent)
|
| 290 |
+
success = run_all_tests()
|
| 291 |
+
sys.exit(0 if success else 1)
|