Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tests /test_zen_ai_comprehensive.py
| """ | |
| ============================================================================= | |
| Zen-AI-Pentest — Comprehensive pytest/unittest Test Suite | |
| ============================================================================= | |
| Run with: | |
| pytest test_zen_ai_pentest.py -v --tb=short | |
| or: | |
| python -m unittest test_zen_ai_pentest -v | |
| ============================================================================= | |
| """ | |
| import base64 | |
| import hashlib | |
| import hmac as _hmac | |
| import json as _json | |
| import time | |
| import unittest | |
| from dataclasses import dataclass, field | |
| from typing import Any, Dict, List, Optional | |
| # --------------------------------------------------------------------------- | |
| # STUBS — swap these for real imports once inside the project: | |
| # from risk_engine.cvss import CVSSCalculator | |
| # from risk_engine.epss import EPSSClient | |
| # from risk_engine.false_positive_engine import FalsePositiveEngine | |
| # from autonomous.memory import AgentMemory | |
| # from autonomous.exploit_validator import ExploitValidator | |
| # from agents.react_agent import ReActAgent, ReActAgentConfig | |
| # from api.auth import AuthManager | |
| # --------------------------------------------------------------------------- | |
| class CVSSCalculator: | |
| def calculate_base_score(self, vector: str) -> float: | |
| if not vector or not vector.startswith("CVSS:3"): | |
| raise ValueError(f"Invalid CVSS vector: {vector}") | |
| if "AV:N" in vector and "AC:L" in vector and "PR:N" in vector: | |
| return 9.8 | |
| if "AV:L" in vector: | |
| return 5.5 | |
| return 7.0 | |
| def get_severity(self, score: float) -> str: | |
| if score == 0.0: | |
| return "None" | |
| if score <= 3.9: | |
| return "Low" | |
| if score <= 6.9: | |
| return "Medium" | |
| if score <= 8.9: | |
| return "High" | |
| return "Critical" | |
| def calculate_temporal_score(self, base_score: float, exploit_maturity: str = "proof_of_concept") -> float: | |
| m = { | |
| "unproven": 0.91, | |
| "proof_of_concept": 0.94, | |
| "functional": 0.97, | |
| "high": 1.0, | |
| }.get(exploit_maturity, 0.94) | |
| return round(base_score * m, 1) | |
| class EPSSClient: | |
| _SCORES = { | |
| "CVE-2021-44228": {"epss": 0.975, "percentile": 0.999}, | |
| "CVE-2023-00001": {"epss": 0.42, "percentile": 0.85}, | |
| } | |
| def get_score(self, cve_id: str) -> Dict[str, Any]: | |
| if not cve_id.startswith("CVE-"): | |
| raise ValueError(f"Invalid CVE ID: {cve_id}") | |
| return self._SCORES.get(cve_id, {"epss": 0.05, "percentile": 0.60}) | |
| def get_bulk_scores(self, cve_ids: List[str]) -> Dict[str, Dict]: | |
| return {c: self.get_score(c) for c in cve_ids} | |
| def prioritize(self, findings: List[Dict]) -> List[Dict]: | |
| return sorted( | |
| findings, | |
| key=lambda f: self.get_score(f.get("cve_id", "CVE-0000-0000"))["epss"], | |
| reverse=True, | |
| ) | |
| class FalsePositiveEngine: | |
| def __init__(self, confidence_threshold: float = 0.7): | |
| self.confidence_threshold = confidence_threshold | |
| def validate(self, finding: Dict) -> Dict: | |
| score = finding.get("confidence", 0.5) | |
| return { | |
| **finding, | |
| "is_false_positive": score < self.confidence_threshold, | |
| "validated_confidence": score, | |
| } | |
| def filter_findings(self, findings: List[Dict]) -> List[Dict]: | |
| return [f for f in findings if not self.validate(f)["is_false_positive"]] | |
| class AgentMemory: | |
| def __init__(self, max_short_term: int = 10): | |
| self.max_short_term = max_short_term | |
| self._short_term: List[Dict] = [] | |
| self._long_term: List[Dict] = [] | |
| def add_observation(self, obs: Dict) -> None: | |
| self._short_term.append(obs) | |
| if len(self._short_term) > self.max_short_term: | |
| self._long_term.append(self._short_term.pop(0)) | |
| def get_context(self, last_n: int = 5) -> List[Dict]: | |
| return self._short_term[-last_n:] | |
| def clear_short_term(self) -> None: | |
| self._short_term.clear() | |
| def short_term_count(self) -> int: | |
| return len(self._short_term) | |
| def long_term_count(self) -> int: | |
| return len(self._long_term) | |
| class ExploitValidator: | |
| SAFE = {0, 1, 2, 3} | |
| def __init__(self, max_risk_level: int = 2): | |
| if max_risk_level not in self.SAFE: | |
| raise ValueError(f"max_risk_level must be 0-3, got {max_risk_level}") | |
| self.max_risk_level = max_risk_level | |
| def validate_exploit(self, exploit: Dict) -> Dict: | |
| allowed = exploit.get("risk_level", 0) <= self.max_risk_level | |
| return { | |
| **exploit, | |
| "allowed": allowed, | |
| "reason": "within" if allowed else "exceeds", | |
| } | |
| def execute_in_sandbox(self, exploit: Dict) -> Dict: | |
| r = self.validate_exploit(exploit) | |
| if not r["allowed"]: | |
| return {"success": False, "error": r["reason"], "output": None} | |
| return {"success": True, "error": None, "output": "sandbox_output"} | |
| class ReActAgentConfig: | |
| max_iterations: int = 10 | |
| use_vm: bool = False | |
| vm_name: str = "" | |
| safety_level: int = 2 | |
| timeout_seconds: int = 300 | |
| class ReActAgent: | |
| def __init__(self, config: ReActAgentConfig): | |
| self.config = config | |
| self.state = "IDLE" | |
| self._iteration = 0 | |
| self.memory = AgentMemory() | |
| def run(self, target: str, objective: str) -> Dict: | |
| if not target: | |
| raise ValueError("target cannot be empty") | |
| self.state = "PLANNING" | |
| self.state = "COMPLETED" | |
| return { | |
| "target": target, | |
| "objective": objective, | |
| "findings": [], | |
| "state": self.state, | |
| } | |
| def generate_report(self, result: Dict) -> str: | |
| return f"# Report\nTarget: {result['target']}\nFindings: {result['findings']}" | |
| def reset(self) -> None: | |
| self.state = "IDLE" | |
| self._iteration = 0 | |
| self.memory.clear_short_term() | |
| class AuthManager: | |
| def __init__(self, secret_key: str, expiration_seconds: int = 3600): | |
| if not secret_key: | |
| raise ValueError("secret_key must not be empty") | |
| self.secret_key = secret_key | |
| self.expiration_seconds = expiration_seconds | |
| self._users: Dict[str, str] = {} | |
| def _hash(self, pw: str) -> str: | |
| return hashlib.sha256(pw.encode()).hexdigest() | |
| def register_user(self, username: str, password: str) -> bool: | |
| if username in self._users: | |
| return False | |
| self._users[username] = self._hash(password) | |
| return True | |
| def authenticate(self, username: str, password: str) -> Optional[str]: | |
| if self._users.get(username) != self._hash(password): | |
| return None | |
| payload = { | |
| "sub": username, | |
| "exp": time.time() + self.expiration_seconds, | |
| } | |
| td = base64.urlsafe_b64encode(_json.dumps(payload).encode()).decode() | |
| sig = _hmac.new(self.secret_key.encode(), td.encode(), hashlib.sha256).hexdigest() | |
| return f"{td}.{sig}" | |
| def verify_token(self, token: str) -> Optional[Dict]: | |
| try: | |
| td, sig = token.rsplit(".", 1) | |
| exp = _hmac.new(self.secret_key.encode(), td.encode(), hashlib.sha256).hexdigest() | |
| if not _hmac.compare_digest(sig, exp): | |
| return None | |
| payload = _json.loads(base64.urlsafe_b64decode(td)) | |
| if payload.get("exp", 0) < time.time(): | |
| return None | |
| return payload | |
| except Exception: | |
| return None | |
| # ============================================================================= | |
| # TESTS | |
| # ============================================================================= | |
| class TestCVSSCalculator(unittest.TestCase): | |
| """risk_engine/cvss.py""" | |
| def setUp(self): | |
| self.calc = CVSSCalculator() | |
| def test_critical_network_vector(self): | |
| s = self.calc.calculate_base_score("CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H") | |
| self.assertGreaterEqual(s, 9.0) | |
| self.assertLessEqual(s, 10.0) | |
| def test_local_vector_medium_range(self): | |
| s = self.calc.calculate_base_score("CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N") | |
| self.assertGreaterEqual(s, 4.0) | |
| self.assertLessEqual(s, 8.9) | |
| def test_severity_none(self): | |
| self.assertEqual(self.calc.get_severity(0.0), "None") | |
| def test_severity_low(self): | |
| self.assertEqual(self.calc.get_severity(2.5), "Low") | |
| def test_severity_medium(self): | |
| self.assertEqual(self.calc.get_severity(5.0), "Medium") | |
| def test_severity_high(self): | |
| self.assertEqual(self.calc.get_severity(8.0), "High") | |
| def test_severity_critical(self): | |
| self.assertEqual(self.calc.get_severity(9.5), "Critical") | |
| def test_temporal_lte_base(self): | |
| self.assertLessEqual(self.calc.calculate_temporal_score(9.8, "proof_of_concept"), 9.8) | |
| def test_temporal_high_maturity_equals_base(self): | |
| self.assertEqual(self.calc.calculate_temporal_score(7.0, "high"), 7.0) | |
| def test_boundary_4_is_medium(self): | |
| self.assertEqual(self.calc.get_severity(4.0), "Medium") | |
| def test_boundary_7_is_high(self): | |
| self.assertEqual(self.calc.get_severity(7.0), "High") | |
| def test_boundary_9_is_critical(self): | |
| self.assertEqual(self.calc.get_severity(9.0), "Critical") | |
| def test_invalid_vector_raises(self): | |
| with self.assertRaises(ValueError): | |
| self.calc.calculate_base_score("BAD") | |
| def test_empty_vector_raises(self): | |
| with self.assertRaises(ValueError): | |
| self.calc.calculate_base_score("") | |
| def test_cvss2_raises(self): | |
| with self.assertRaises(ValueError): | |
| self.calc.calculate_base_score("AV:N/AC:L/Au:N/C:C/I:C/A:C") | |
| class TestEPSSClient(unittest.TestCase): | |
| """risk_engine/epss.py""" | |
| def setUp(self): | |
| self.client = EPSSClient() | |
| def test_log4shell_high_score(self): | |
| self.assertGreater(self.client.get_score("CVE-2021-44228")["epss"], 0.9) | |
| def test_unknown_cve_default_range(self): | |
| r = self.client.get_score("CVE-9999-99999") | |
| self.assertGreaterEqual(r["epss"], 0.0) | |
| self.assertLessEqual(r["epss"], 1.0) | |
| def test_bulk_returns_all_keys(self): | |
| cves = ["CVE-2021-44228", "CVE-2023-00001"] | |
| self.assertEqual(set(self.client.get_bulk_scores(cves).keys()), set(cves)) | |
| def test_prioritize_high_epss_first(self): | |
| findings = [{"cve_id": "CVE-9999-99999"}, {"cve_id": "CVE-2021-44228"}] | |
| self.assertEqual(self.client.prioritize(findings)[0]["cve_id"], "CVE-2021-44228") | |
| def test_score_range_valid(self): | |
| r = self.client.get_score("CVE-2023-00001") | |
| self.assertGreaterEqual(r["epss"], 0.0) | |
| self.assertLessEqual(r["epss"], 1.0) | |
| def test_invalid_format_raises(self): | |
| with self.assertRaises(ValueError): | |
| self.client.get_score("NOTACVE") | |
| def test_empty_bulk_returns_empty(self): | |
| self.assertEqual(self.client.get_bulk_scores([]), {}) | |
| def test_prioritize_empty_returns_empty(self): | |
| self.assertEqual(self.client.prioritize([]), []) | |
| class TestFalsePositiveEngine(unittest.TestCase): | |
| """risk_engine/false_positive_engine.py""" | |
| def setUp(self): | |
| self.engine = FalsePositiveEngine(confidence_threshold=0.7) | |
| def test_high_confidence_not_fp(self): | |
| self.assertFalse(self.engine.validate({"confidence": 0.95})["is_false_positive"]) | |
| def test_low_confidence_is_fp(self): | |
| self.assertTrue(self.engine.validate({"confidence": 0.3})["is_false_positive"]) | |
| def test_filter_removes_fp(self): | |
| findings = [ | |
| {"id": "f1", "confidence": 0.9}, | |
| {"id": "f2", "confidence": 0.2}, | |
| {"id": "f3", "confidence": 0.8}, | |
| ] | |
| ids = [f["id"] for f in self.engine.filter_findings(findings)] | |
| self.assertNotIn("f2", ids) | |
| self.assertIn("f1", ids) | |
| def test_validate_preserves_fields(self): | |
| r = self.engine.validate({"id": "x", "cve_id": "CVE-X", "confidence": 0.9}) | |
| self.assertEqual(r["cve_id"], "CVE-X") | |
| def test_at_threshold_not_fp(self): | |
| self.assertFalse(self.engine.validate({"confidence": 0.7})["is_false_positive"]) | |
| def test_all_high_confidence_kept(self): | |
| findings = [{"id": str(i), "confidence": 0.9} for i in range(5)] | |
| self.assertEqual(len(self.engine.filter_findings(findings)), 5) | |
| def test_all_low_confidence_removed(self): | |
| findings = [{"id": str(i), "confidence": 0.1} for i in range(5)] | |
| self.assertEqual(self.engine.filter_findings(findings), []) | |
| def test_custom_threshold(self): | |
| engine = FalsePositiveEngine(confidence_threshold=0.5) | |
| self.assertFalse(engine.validate({"confidence": 0.6})["is_false_positive"]) | |
| class TestAgentMemory(unittest.TestCase): | |
| """autonomous/memory.py""" | |
| def setUp(self): | |
| self.memory = AgentMemory(max_short_term=3) | |
| def test_add_increases_count(self): | |
| self.memory.add_observation({"data": "x"}) | |
| self.assertEqual(self.memory.short_term_count, 1) | |
| def test_get_context_respects_n(self): | |
| for i in range(3): | |
| self.memory.add_observation({"seq": i}) | |
| self.assertLessEqual(len(self.memory.get_context(last_n=2)), 2) | |
| def test_clear_empties_short_term(self): | |
| self.memory.add_observation({"x": 1}) | |
| self.memory.clear_short_term() | |
| self.assertEqual(self.memory.short_term_count, 0) | |
| def test_overflow_evicts_to_long_term(self): | |
| for i in range(5): | |
| self.memory.add_observation({"seq": i}) | |
| self.assertLessEqual(self.memory.short_term_count, 3) | |
| self.assertGreaterEqual(self.memory.long_term_count, 1) | |
| def test_total_preserved_across_eviction(self): | |
| for i in range(6): | |
| self.memory.add_observation({"seq": i}) | |
| self.assertEqual(self.memory.short_term_count + self.memory.long_term_count, 6) | |
| def test_get_context_n_larger_than_stored(self): | |
| self.memory.add_observation({"x": 1}) | |
| self.assertEqual(len(self.memory.get_context(last_n=100)), 1) | |
| def test_empty_context_returns_empty(self): | |
| self.assertEqual(self.memory.get_context(), []) | |
| class TestExploitValidator(unittest.TestCase): | |
| """autonomous/exploit_validator.py""" | |
| def setUp(self): | |
| self.v = ExploitValidator(max_risk_level=2) | |
| def test_allowed_within_threshold(self): | |
| self.assertTrue(self.v.validate_exploit({"risk_level": 1})["allowed"]) | |
| def test_blocked_exceeds_threshold(self): | |
| self.assertFalse(self.v.validate_exploit({"risk_level": 3})["allowed"]) | |
| def test_sandbox_succeeds_for_allowed(self): | |
| r = self.v.execute_in_sandbox({"risk_level": 0}) | |
| self.assertTrue(r["success"]) | |
| self.assertIsNotNone(r["output"]) | |
| def test_sandbox_fails_for_blocked(self): | |
| r = self.v.execute_in_sandbox({"risk_level": 3}) | |
| self.assertFalse(r["success"]) | |
| self.assertIsNone(r["output"]) | |
| def test_preserves_exploit_name(self): | |
| self.assertEqual( | |
| self.v.validate_exploit({"name": "probe", "risk_level": 1})["name"], | |
| "probe", | |
| ) | |
| def test_at_threshold_is_allowed(self): | |
| self.assertTrue(self.v.validate_exploit({"risk_level": 2})["allowed"]) | |
| def test_zero_risk_allowed(self): | |
| self.assertTrue(self.v.validate_exploit({"risk_level": 0})["allowed"]) | |
| def test_invalid_max_level_raises(self): | |
| with self.assertRaises(ValueError): | |
| ExploitValidator(max_risk_level=99) | |
| def test_negative_level_raises(self): | |
| with self.assertRaises(ValueError): | |
| ExploitValidator(max_risk_level=-1) | |
| class TestReActAgent(unittest.TestCase): | |
| """agents/react_agent.py""" | |
| def setUp(self): | |
| self.agent = ReActAgent(ReActAgentConfig(max_iterations=5, safety_level=2)) | |
| def test_initial_state_idle(self): | |
| self.assertEqual(self.agent.state, "IDLE") | |
| def test_run_returns_dict(self): | |
| self.assertIsInstance(self.agent.run("t.com", "recon"), dict) | |
| def test_run_sets_target(self): | |
| self.assertEqual(self.agent.run("192.168.1.1", "scan")["target"], "192.168.1.1") | |
| def test_run_completes(self): | |
| self.agent.run("t.com", "audit") | |
| self.assertEqual(self.agent.state, "COMPLETED") | |
| def test_result_has_findings(self): | |
| self.assertIn("findings", self.agent.run("t.com", "test")) | |
| def test_report_contains_target(self): | |
| r = self.agent.run("x.com", "r") | |
| self.assertIn("x.com", self.agent.generate_report(r)) | |
| def test_reset_to_idle(self): | |
| self.agent.run("t.com", "t") | |
| self.agent.reset() | |
| self.assertEqual(self.agent.state, "IDLE") | |
| def test_reset_clears_memory(self): | |
| self.agent.memory.add_observation({"x": 1}) | |
| self.agent.reset() | |
| self.assertEqual(self.agent.memory.short_term_count, 0) | |
| def test_empty_target_raises(self): | |
| with self.assertRaises(ValueError): | |
| self.agent.run("", "obj") | |
| def test_successive_runs(self): | |
| self.agent.run("t1.com", "r1") | |
| self.agent.reset() | |
| self.assertEqual(self.agent.run("t2.com", "r2")["target"], "t2.com") | |
| def test_config_stored(self): | |
| self.assertEqual(self.agent.config.max_iterations, 5) | |
| self.assertEqual(self.agent.config.safety_level, 2) | |
| class TestAuthManager(unittest.TestCase): | |
| """api/auth.py""" | |
| def setUp(self): | |
| self.auth = AuthManager(secret_key="test-secret-2026") | |
| def test_register_succeeds(self): | |
| self.assertTrue(self.auth.register_user("alice", "p")) | |
| def test_register_duplicate_false(self): | |
| self.auth.register_user("b", "p") | |
| self.assertFalse(self.auth.register_user("b", "p2")) | |
| def test_valid_creds_return_token(self): | |
| self.auth.register_user("c", "p") | |
| self.assertIsNotNone(self.auth.authenticate("c", "p")) | |
| def test_wrong_password_none(self): | |
| self.auth.register_user("d", "right") | |
| self.assertIsNone(self.auth.authenticate("d", "wrong")) | |
| def test_unknown_user_none(self): | |
| self.assertIsNone(self.auth.authenticate("nobody", "p")) | |
| def test_valid_token_verifies(self): | |
| self.auth.register_user("e", "p") | |
| token = self.auth.authenticate("e", "p") | |
| payload = self.auth.verify_token(token) | |
| self.assertIsNotNone(payload) | |
| self.assertEqual(payload["sub"], "e") | |
| def test_tampered_token_rejected(self): | |
| self.auth.register_user("f", "p") | |
| token = self.auth.authenticate("f", "p") | |
| self.assertIsNone(self.auth.verify_token(token[:-5] + "XXXXX")) | |
| def test_expired_token_rejected(self): | |
| a = AuthManager("k", expiration_seconds=-1) | |
| a.register_user("g", "p") | |
| t = a.authenticate("g", "p") | |
| self.assertIsNone(a.verify_token(t)) | |
| def test_garbage_token_none(self): | |
| self.assertIsNone(self.auth.verify_token("not.real.token")) | |
| def test_empty_token_none(self): | |
| self.assertIsNone(self.auth.verify_token("")) | |
| def test_empty_secret_raises(self): | |
| with self.assertRaises(ValueError): | |
| AuthManager(secret_key="") | |
| def test_different_users_different_tokens(self): | |
| self.auth.register_user("u1", "p") | |
| self.auth.register_user("u2", "p") | |
| self.assertNotEqual( | |
| self.auth.authenticate("u1", "p"), | |
| self.auth.authenticate("u2", "p"), | |
| ) | |
| class TestRiskEnginePipeline(unittest.TestCase): | |
| """Integration: CVSS + EPSS + FalsePositive chain.""" | |
| def setUp(self): | |
| self.cvss = CVSSCalculator() | |
| self.epss = EPSSClient() | |
| self.fp = FalsePositiveEngine(confidence_threshold=0.6) | |
| def _finding(self, cve, vector, conf): | |
| s = self.cvss.calculate_base_score(vector) | |
| e = self.epss.get_score(cve) | |
| return { | |
| "cve_id": cve, | |
| "cvss_score": s, | |
| "severity": self.cvss.get_severity(s), | |
| "epss_score": e["epss"], | |
| "confidence": conf, | |
| } | |
| CRIT_VEC = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H" | |
| LOCAL_VEC = "CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N" | |
| def test_critical_passes_all_stages(self): | |
| f = self._finding("CVE-2021-44228", self.CRIT_VEC, 0.95) | |
| v = self.fp.validate(f) | |
| self.assertEqual(v["severity"], "Critical") | |
| self.assertFalse(v["is_false_positive"]) | |
| self.assertGreater(f["epss_score"], 0.9) | |
| def test_low_confidence_filtered(self): | |
| f = self._finding("CVE-9999-99999", self.LOCAL_VEC, 0.1) | |
| self.assertTrue(self.fp.validate(f)["is_false_positive"]) | |
| def test_epss_prioritization(self): | |
| findings = [ | |
| self._finding("CVE-9999-99999", self.CRIT_VEC, 0.9), | |
| self._finding("CVE-2021-44228", self.CRIT_VEC, 0.9), | |
| ] | |
| self.assertEqual(self.epss.prioritize(findings)[0]["cve_id"], "CVE-2021-44228") | |
| def test_mixed_batch_filtering(self): | |
| findings = [ | |
| self._finding("CVE-2021-44228", self.CRIT_VEC, 0.9), | |
| self._finding("CVE-9999-99999", self.LOCAL_VEC, 0.1), | |
| ] | |
| filtered = self.fp.filter_findings(findings) | |
| self.assertEqual(len(filtered), 1) | |
| self.assertEqual(filtered[0]["cve_id"], "CVE-2021-44228") | |
| if __name__ == "__main__": | |
| unittest.main(verbosity=2) | |
Xet Storage Details
- Size:
- 21.5 kB
- Xet hash:
- 7d282189f13984dad866a78fe52a9f16cf6594ca324ce8bbefe06824b2ac8ba7
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.