Spaces:
Runtime error
Runtime error
File size: 76,165 Bytes
8c486a8 9a22987 ca6fc4d 8c486a8 f549fda 8c486a8 f549fda ca6fc4d f549fda 80ef9e0 5b3b677 8c486a8 5b99233 8c486a8 307d729 595e190 6f0f018 72e9079 6f0f018 72e9079 6f0f018 72e9079 595e190 8c486a8 49d1c75 5848160 49d1c75 595e190 5848160 595e190 5848160 bcfb80b 5848160 bcfb80b 5848160 bcfb80b 5848160 bcfb80b 5848160 bcfb80b 5848160 bcfb80b 5848160 bcfb80b 595e190 49d1c75 7fedc25 49d1c75 7fedc25 49d1c75 8c486a8 72e9079 595e190 72e9079 595e190 72e9079 595e190 72e9079 9a22987 8c486a8 49d1c75 b439619 595e190 b439619 595e190 b439619 595e190 b439619 595e190 b439619 d2809e9 595e190 d2809e9 595e190 d2809e9 8c486a8 49d1c75 9a22987 49d1c75 9a22987 8c486a8 ca6fc4d 8c486a8 307d729 8c486a8 307d729 8c486a8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 | """Tests for validator checks β all run without Docker via mock_containers."""
import json
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from open_range.protocols import (
CheckResult,
EvidenceItem,
ExecResult,
ExploitStep,
FlagSpec,
GoldenPathStep,
MutationOp,
MutationPlan,
NPCPersona,
SnapshotSpec,
TaskSpec,
TruthGraph,
Vulnerability,
)
from open_range.validator.validator import ValidatorGate, ValidationResult
@pytest.mark.asyncio
async def test_manifest_compliance_rejects_illegal_mutation_plan(
tier1_manifest,
sample_snapshot_spec,
mock_containers,
):
from open_range.validator.manifest_compliance import ManifestComplianceCheck
spec = sample_snapshot_spec.model_copy(deep=True)
spec.mutation_plan = MutationPlan(
parent_snapshot_id="root_snap",
ops=[
MutationOp(
mutation_id="illegal1",
op_type="seed_vuln",
target_selector={"host": "web"},
params={"vuln_type": "totally_fake_bug"},
)
],
)
spec.lineage.parent_snapshot_id = "root_snap"
spec.lineage.generation_depth = 1
result = await ManifestComplianceCheck(tier1_manifest).check(spec, mock_containers)
assert result.passed is False
assert "illegal family" in result.error
@pytest.mark.asyncio
async def test_manifest_compliance_rejects_incompatible_seed_vuln_host(
tier1_manifest,
sample_snapshot_spec,
mock_containers,
):
from open_range.validator.manifest_compliance import ManifestComplianceCheck
spec = sample_snapshot_spec.model_copy(deep=True)
spec.mutation_plan = MutationPlan(
parent_snapshot_id="root_snap",
ops=[
MutationOp(
mutation_id="illegal_host",
op_type="seed_vuln",
target_selector={"host": "firewall"},
params={
"vuln_type": "path_traversal",
"template_id": "vuln_path_traversal",
"required_services": ["nginx", "php-fpm"],
},
)
],
)
spec.lineage.parent_snapshot_id = "root_snap"
spec.lineage.generation_depth = 1
result = await ManifestComplianceCheck(tier1_manifest).check(spec, mock_containers)
assert result.passed is False
assert "incompatible with required services" in result.error
@pytest.mark.asyncio
async def test_graph_consistency_rejects_missing_parent_lineage(sample_snapshot_spec, mock_containers):
from open_range.validator.graph_consistency import GraphConsistencyCheck
spec = sample_snapshot_spec.model_copy(deep=True)
spec.mutation_plan = MutationPlan(
parent_snapshot_id="root_snap",
ops=[
MutationOp(
mutation_id="mut1",
op_type="add_benign_noise",
target_selector={"location": "siem:noise.log"},
params={"location": "siem:noise.log"},
)
],
)
spec.lineage.generation_depth = 1
spec.lineage.parent_snapshot_id = None
result = await GraphConsistencyCheck().check(spec, mock_containers)
assert result.passed is False
assert "missing parent_snapshot_id" in result.error
@pytest.mark.asyncio
async def test_path_solvability_passes_for_reachable_flag_host(mock_containers):
from open_range.protocols import EvidenceItem, TruthGraph, Vulnerability
from open_range.validator.path_solvability import PathSolvabilityCheck
spec = SnapshotSpec(
topology={
"hosts": ["attacker", "web", "db"],
"zones": {"external": ["attacker"], "dmz": ["web"], "internal": ["db"]},
"dependency_edges": [
{"source": "attacker", "target": "web"},
{"source": "web", "target": "db"},
],
"host_details": {
"attacker": {"services": ["nmap"]},
"web": {"services": ["nginx"]},
"db": {"services": ["mysql"]},
},
},
truth_graph=TruthGraph(
vulns=[Vulnerability(id="v1", type="sqli", host="web", service="nginx")],
),
flags=[FlagSpec(id="f1", value="FLAG{ok}", path="/var/flags/flag1.txt", host="db")],
evidence_spec=[EvidenceItem(type="log_entry", location="siem:/var/log/siem/all.log")],
golden_path=[GoldenPathStep(step=1, command="nmap web", expect_in_stdout="80/tcp")],
task=TaskSpec(red_briefing="go", blue_briefing="watch"),
)
result = await PathSolvabilityCheck().check(spec, mock_containers)
assert result.passed is True
@pytest.mark.asyncio
async def test_graph_evidence_sufficiency_fails_without_supporting_hosts(mock_containers):
from open_range.protocols import TruthGraph, Vulnerability
from open_range.validator.graph_evidence import GraphEvidenceSufficiencyCheck
spec = SnapshotSpec(
topology={
"hosts": ["attacker", "web", "db"],
"zones": {"external": ["attacker"], "dmz": ["web"], "internal": ["db"]},
"dependency_edges": [{"source": "attacker", "target": "web"}],
"host_details": {
"attacker": {"services": ["nmap"]},
"web": {"services": ["nginx"]},
"db": {"services": ["mysql"]},
},
},
truth_graph=TruthGraph(
vulns=[Vulnerability(id="v1", type="sqli", host="db", service="mysql")],
),
flags=[FlagSpec(id="f1", value="FLAG{db}", path="/var/flags/flag1.txt", host="db")],
evidence_spec=[EvidenceItem(type="log_entry", location="web:/var/log/access.log")],
golden_path=[GoldenPathStep(step=1, command="scan", expect_in_stdout="ok")],
task=TaskSpec(red_briefing="go", blue_briefing="watch"),
)
result = await GraphEvidenceSufficiencyCheck().check(spec, mock_containers)
assert result.passed is False
assert "no supporting evidence host" in result.error
@pytest.mark.asyncio
async def test_graph_reward_grounding_fails_when_flag_host_unreachable(mock_containers):
from open_range.protocols import TruthGraph, Vulnerability
from open_range.validator.graph_reward_grounding import GraphRewardGroundingCheck
spec = SnapshotSpec(
topology={
"hosts": ["attacker", "web", "db"],
"zones": {"external": ["attacker"], "dmz": ["web"], "internal": ["db"]},
"dependency_edges": [{"source": "attacker", "target": "web"}],
"host_details": {
"attacker": {"services": ["nmap"]},
"web": {"services": ["nginx"]},
"db": {"services": ["mysql"]},
},
},
truth_graph=TruthGraph(
vulns=[Vulnerability(id="v1", type="sqli", host="web", service="nginx")],
),
flags=[FlagSpec(id="f1", value="FLAG{db}", path="/var/flags/flag1.txt", host="db")],
evidence_spec=[EvidenceItem(type="log_entry", location="siem:/var/log/siem/all.log")],
golden_path=[GoldenPathStep(step=1, command="scan", expect_in_stdout="ok")],
task=TaskSpec(red_briefing="go", blue_briefing="watch"),
)
result = await GraphRewardGroundingCheck().check(spec, mock_containers)
assert result.passed is False
assert "not reachable from any vuln host" in result.error
@pytest.mark.asyncio
async def test_graph_checks_allow_trust_based_host_pivots(mock_containers):
from open_range.validator.graph_reward_grounding import GraphRewardGroundingCheck
from open_range.validator.path_solvability import PathSolvabilityCheck
spec = SnapshotSpec(
topology={
"hosts": ["attacker", "web", "db"],
"zones": {"external": ["attacker"], "dmz": ["web"], "internal": ["db"]},
"dependency_edges": [{"source": "attacker", "target": "web"}],
"trust_edges": [{"source": "websvc", "target": "dbsvc", "type": "credential_reuse"}],
"host_details": {
"attacker": {"services": ["nmap"]},
"web": {"services": ["nginx"]},
"db": {"services": ["mysql"]},
},
"principal_catalog": {
"websvc": {"username": "websvc", "hosts": ["web"], "is_login_account": False},
"dbsvc": {"username": "dbsvc", "hosts": ["db"], "is_login_account": False},
},
},
truth_graph=TruthGraph(
vulns=[Vulnerability(id="v1", type="credential_reuse", host="web", service="nginx")],
),
flags=[FlagSpec(id="f1", value="FLAG{db}", path="/var/flags/flag1.txt", host="db")],
evidence_spec=[EvidenceItem(type="log_entry", location="db:/var/log/mysql.log")],
golden_path=[GoldenPathStep(step=1, command="scan", expect_in_stdout="ok")],
task=TaskSpec(red_briefing="go", blue_briefing="watch"),
)
path_result = await PathSolvabilityCheck().check(spec, mock_containers)
reward_result = await GraphRewardGroundingCheck().check(spec, mock_containers)
assert path_result.passed is True
assert reward_result.passed is True
# ---------------------------------------------------------------------------
# Check 1: BuildBoot
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_build_boot_passes_when_all_healthy(sample_snapshot_spec, mock_containers):
from open_range.validator.build_boot import BuildBootCheck
for h in sample_snapshot_spec.topology["hosts"]:
mock_containers.healthy.add(h)
result = await BuildBootCheck().check(sample_snapshot_spec, mock_containers)
assert result.passed is True
assert result.name == "build_boot"
@pytest.mark.asyncio
async def test_build_boot_fails_when_host_unhealthy(sample_snapshot_spec, mock_containers):
from open_range.validator.build_boot import BuildBootCheck
# Mark all except 'web' as healthy
for h in sample_snapshot_spec.topology["hosts"]:
if h != "web":
mock_containers.healthy.add(h)
result = await BuildBootCheck().check(sample_snapshot_spec, mock_containers)
assert result.passed is False
assert "web" in result.error
# ---------------------------------------------------------------------------
# Check 2: Exploitability
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_exploitability_passes_when_golden_path_succeeds(mock_containers):
from open_range.validator.exploitability import ExploitabilityCheck
# Use a minimal spec with distinct commands to avoid substring collisions.
spec = SnapshotSpec(
golden_path=[
GoldenPathStep(step=1, command="nmap -sV 10.0.1.0/24", expect_in_stdout="80/tcp"),
GoldenPathStep(step=2, command="curl http://target/page", expect_in_stdout="OK"),
],
)
for step in spec.golden_path:
mock_containers.exec_results[("attacker", step.command)] = step.expect_in_stdout
result = await ExploitabilityCheck().check(spec, mock_containers)
assert result.passed is True
@pytest.mark.asyncio
async def test_exploitability_normalizes_whitespace_for_tool_output(mock_containers):
from open_range.validator.exploitability import ExploitabilityCheck
spec = SnapshotSpec(
golden_path=[
GoldenPathStep(
step=1,
command="nmap -sV 10.0.1.0/24",
expect_in_stdout="80/tcp open http",
),
],
)
mock_containers.exec_results[("attacker", "nmap -sV 10.0.1.0/24")] = (
"80/tcp open http nginx"
)
result = await ExploitabilityCheck().check(spec, mock_containers)
assert result.passed is True
@pytest.mark.asyncio
async def test_exploitability_fails_when_step_output_missing(
sample_snapshot_spec, mock_containers
):
from open_range.validator.exploitability import ExploitabilityCheck
# Register all steps but make one return wrong output
for step in sample_snapshot_spec.golden_path:
host = getattr(step, "host", None) or "attacker"
mock_containers.exec_results[(host, step.command)] = step.expect_in_stdout
# Override one step to return wrong output
first_step = sample_snapshot_spec.golden_path[0]
host = getattr(first_step, "host", None) or "attacker"
mock_containers.exec_results[(host, first_step.command)] = "totally wrong output"
result = await ExploitabilityCheck().check(sample_snapshot_spec, mock_containers)
assert result.passed is False
assert "failed" in result.error
@pytest.mark.asyncio
async def test_exploitability_fails_on_empty_golden_path(mock_containers):
from open_range.validator.exploitability import ExploitabilityCheck
spec = SnapshotSpec(golden_path=[])
result = await ExploitabilityCheck().check(spec, mock_containers)
assert result.passed is False
assert "empty" in result.error
@pytest.mark.asyncio
async def test_exploitability_skips_meta_commands(mock_containers):
from open_range.validator.exploitability import ExploitabilityCheck
spec = SnapshotSpec(
golden_path=[
GoldenPathStep(step=1, command="curl http://web/", expect_in_stdout="Welcome"),
GoldenPathStep(step=2, command="submit_flag FLAG{abc}", expect_in_stdout="correct"),
],
)
mock_containers.exec_results[("attacker", "curl http://web/")] = "Welcome"
result = await ExploitabilityCheck().check(spec, mock_containers)
assert result.passed is True
assert result.details["skipped_steps"] == [2]
@pytest.mark.asyncio
async def test_exploitability_fails_when_expectation_missing_in_strict_mode(mock_containers):
from open_range.validator.exploitability import ExploitabilityCheck
spec = SnapshotSpec(
golden_path=[
GoldenPathStep(step=1, command="curl http://web/", expect_in_stdout=""),
],
)
mock_containers.exec_results[("attacker", "curl http://web/")] = "Welcome"
result = await ExploitabilityCheck().check(spec, mock_containers)
assert result.passed is False
assert result.details["require_expectation"] is True
assert result.details["failed_steps"][0]["error"] == (
"golden path step 1 has no expect_in_stdout"
)
@pytest.mark.asyncio
async def test_exploitability_allows_missing_expectation_in_lenient_mode(mock_containers):
from open_range.validator.exploitability import ExploitabilityCheck
spec = SnapshotSpec(
golden_path=[
GoldenPathStep(step=1, command="curl http://web/", expect_in_stdout=""),
],
)
mock_containers.exec_results[("attacker", "curl http://web/")] = "Welcome"
result = await ExploitabilityCheck(require_expectation=False).check(spec, mock_containers)
assert result.passed is True
assert result.details["require_expectation"] is False
assert result.details["unvalidated_steps"] == [1]
@pytest.mark.asyncio
async def test_exploitability_fails_on_nonzero_exit_even_with_expected_output(mock_containers):
from open_range.validator.exploitability import ExploitabilityCheck
spec = SnapshotSpec(
golden_path=[
GoldenPathStep(step=1, command="curl http://web/", expect_in_stdout="Welcome"),
],
)
mock_containers.exec_results[("attacker", "curl http://web/")] = "Welcome"
mock_containers.exec_status[("attacker", "curl http://web/")] = 7
result = await ExploitabilityCheck().check(spec, mock_containers)
assert result.passed is False
assert result.details["failed_steps"][0]["error"] == "command failed with exit_code=7"
# ---------------------------------------------------------------------------
# Check 3: Patchability
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_patchability_fails_when_no_vulns(mock_containers):
from open_range.validator.patchability import PatchabilityCheck
spec = SnapshotSpec(truth_graph=TruthGraph(vulns=[]))
result = await PatchabilityCheck().check(spec, mock_containers)
assert result.passed is False
@pytest.mark.asyncio
async def test_patchability_passes_when_patch_breaks_exploit(mock_containers):
"""Patch applied -> golden path step no longer produces expected output -> PASS."""
from open_range.protocols import ExploitStep
from open_range.validator.patchability import PatchabilityCheck
spec = SnapshotSpec(
truth_graph=TruthGraph(
vulns=[
Vulnerability(
id="v1",
type="sqli",
host="web",
remediation="sed -i 's/unsafe/safe/' /var/www/app.php",
),
],
exploit_chain=[
ExploitStep(vuln_id="v1", command="curl http://web/search?q=exploit"),
],
),
golden_path=[
GoldenPathStep(
step=1,
command="curl http://web/search?q=exploit",
expect_in_stdout="SECRET_DATA",
),
],
)
# Remediation exec succeeds (exit 0 by default)
mock_containers.exec_results[("web", "sed")] = ""
# After patch, golden path step returns DIFFERENT output (no SECRET_DATA)
mock_containers.exec_results[("attacker", "curl http://web/search?q=exploit")] = "no results"
result = await PatchabilityCheck().check(spec, mock_containers)
assert result.passed is True
assert result.name == "patchability"
@pytest.mark.asyncio
async def test_patchability_fails_when_exploit_still_works(mock_containers):
"""Patch applied but golden path step still succeeds -> FAIL."""
from open_range.protocols import ExploitStep
from open_range.validator.patchability import PatchabilityCheck
spec = SnapshotSpec(
truth_graph=TruthGraph(
vulns=[
Vulnerability(
id="v1",
type="sqli",
host="web",
remediation="sed -i 's/unsafe/safe/' /var/www/app.php",
),
],
exploit_chain=[
ExploitStep(vuln_id="v1", command="curl http://web/search?q=exploit"),
],
),
golden_path=[
GoldenPathStep(
step=1,
command="curl http://web/search?q=exploit",
expect_in_stdout="SECRET_DATA",
),
],
)
# Remediation exec succeeds
mock_containers.exec_results[("web", "sed")] = ""
# After patch, golden path step STILL returns the expected output (patch didn't work)
mock_containers.exec_results[("attacker", "curl http://web/search?q=exploit")] = "SECRET_DATA"
result = await PatchabilityCheck().check(spec, mock_containers)
assert result.passed is False
assert "exploitable after remediation" in result.error
@pytest.mark.asyncio
async def test_patchability_fails_when_remediation_command_exits_nonzero(mock_containers):
from open_range.protocols import ExploitStep
from open_range.validator.patchability import PatchabilityCheck
spec = SnapshotSpec(
truth_graph=TruthGraph(
vulns=[
Vulnerability(
id="v1",
type="sqli",
host="web",
remediation="sed -i 's/unsafe/safe/' /var/www/app.php",
),
],
exploit_chain=[
ExploitStep(vuln_id="v1", command="curl http://web/search?q=exploit"),
],
),
golden_path=[
GoldenPathStep(
step=1,
command="curl http://web/search?q=exploit",
expect_in_stdout="SECRET_DATA",
),
],
)
mock_containers.exec_results[("web", "sed")] = "sed: cannot read /var/www/app.php"
mock_containers.exec_status[("web", "sed")] = 2
result = await PatchabilityCheck().check(spec, mock_containers)
assert result.passed is False
first = result.details["vuln_results"][0]
assert first["passed"] is False
assert "remediation command failed" in first["reason"]
assert mock_containers.restarted == ["web"]
@pytest.mark.asyncio
async def test_patchability_fails_when_retest_command_is_inconclusive(mock_containers):
from open_range.protocols import ExploitStep
from open_range.validator.patchability import PatchabilityCheck
spec = SnapshotSpec(
truth_graph=TruthGraph(
vulns=[
Vulnerability(
id="v1",
type="sqli",
host="web",
remediation="sed -i 's/unsafe/safe/' /var/www/app.php",
),
],
exploit_chain=[
ExploitStep(vuln_id="v1", command="curl http://web/search?q=exploit"),
],
),
golden_path=[
GoldenPathStep(
step=1,
command="curl http://web/search?q=exploit",
expect_in_stdout="SECRET_DATA",
),
],
)
mock_containers.exec_results[("web", "sed")] = ""
mock_containers.exec_results[("attacker", "curl http://web/search?q=exploit")] = "curl: (7) failed to connect"
mock_containers.exec_status[("attacker", "curl http://web/search?q=exploit")] = 7
result = await PatchabilityCheck().check(spec, mock_containers)
assert result.passed is False
vuln_result = result.details["vuln_results"][0]
assert vuln_result["passed"] is False
assert vuln_result["reason"] == "retest inconclusive after remediation"
assert "retest command failed (exit_code=7)" in vuln_result["details"][0]["reason"]
assert mock_containers.restarted == ["web"]
@pytest.mark.asyncio
async def test_patchability_fails_when_retest_execution_is_inconclusive(mock_containers):
from open_range.protocols import ExecResult, ExploitStep
from open_range.validator.patchability import PatchabilityCheck
spec = SnapshotSpec(
truth_graph=TruthGraph(
vulns=[
Vulnerability(
id="v1",
type="sqli",
host="web",
remediation="sed -i 's/unsafe/safe/' /var/www/app.php",
),
],
exploit_chain=[
ExploitStep(vuln_id="v1", command="curl http://web/search?q=exploit"),
],
),
golden_path=[
GoldenPathStep(
step=1,
command="curl http://web/search?q=exploit",
expect_in_stdout="SECRET_DATA",
),
],
)
async def exec_run_side_effect(container: str, cmd: str, **kwargs):
if container == "web" and "sed -i 's/unsafe/safe/' /var/www/app.php" in cmd:
return ExecResult(stdout="", exit_code=0)
if container == "attacker" and "curl http://web/search?q=exploit" in cmd:
raise RuntimeError("timeout")
return ExecResult(stdout="", exit_code=0)
mock_containers.exec_run = exec_run_side_effect
result = await PatchabilityCheck().check(spec, mock_containers)
assert result.passed is False
vuln_result = result.details["vuln_results"][0]
assert vuln_result["passed"] is False
assert vuln_result["reason"] == "retest inconclusive after remediation"
assert vuln_result["details"][0]["reason"] == "retest execution raised: timeout"
assert mock_containers.restarted == ["web"]
@pytest.mark.asyncio
async def test_patchability_skips_prose_remediation(mock_containers):
"""Non-executable remediation (prose) is skipped with warning, fails if all skipped."""
from open_range.protocols import ExploitStep
from open_range.validator.patchability import PatchabilityCheck
spec = SnapshotSpec(
truth_graph=TruthGraph(
vulns=[
Vulnerability(
id="v1",
type="sqli",
host="web",
remediation="Use parameterized queries instead of string concatenation",
),
],
exploit_chain=[
ExploitStep(vuln_id="v1", command="curl http://web/search?q=exploit"),
],
),
golden_path=[
GoldenPathStep(
step=1,
command="curl http://web/search?q=exploit",
expect_in_stdout="SECRET_DATA",
),
],
)
result = await PatchabilityCheck().check(spec, mock_containers)
assert result.passed is False
# Verify it was recorded as a failure (not silently skipped)
vuln_results = result.details["vuln_results"]
assert len(vuln_results) == 1
assert vuln_results[0]["passed"] is False
assert "not executable" in vuln_results[0]["reason"]
@pytest.mark.asyncio
async def test_patchability_fails_when_all_skipped(mock_containers):
"""If all vulns are skipped (no testable remediation), check FAILS."""
from open_range.protocols import ExploitStep
from open_range.validator.patchability import PatchabilityCheck
spec = SnapshotSpec(
truth_graph=TruthGraph(
vulns=[
Vulnerability(
id="v1",
type="sqli",
host="web",
remediation="", # empty remediation
),
Vulnerability(
id="v2",
type="xss",
host="web",
remediation="Sanitize all user input before rendering", # prose
),
],
exploit_chain=[
ExploitStep(vuln_id="v1", command="cmd1"),
ExploitStep(vuln_id="v2", command="cmd2"),
],
),
golden_path=[
GoldenPathStep(step=1, command="cmd1", expect_in_stdout="found"),
GoldenPathStep(step=2, command="cmd2", expect_in_stdout="xss"),
],
)
result = await PatchabilityCheck().check(spec, mock_containers)
assert result.passed is False
assert "no vulns had testable remediation" in result.error
@pytest.mark.asyncio
async def test_patchability_restarts_container_after_patch(mock_containers):
"""Container is restarted after each vuln's test to restore pre-patched state."""
from open_range.protocols import ExploitStep
from open_range.validator.patchability import PatchabilityCheck
spec = SnapshotSpec(
truth_graph=TruthGraph(
vulns=[
Vulnerability(
id="v1",
type="sqli",
host="web",
remediation="sed -i 's/bad/good/' /app.php",
),
Vulnerability(
id="v2",
type="lfi",
host="web",
remediation="rm /etc/sensitive_file",
),
],
exploit_chain=[
ExploitStep(vuln_id="v1", command="curl http://web/search?q=inject"),
ExploitStep(vuln_id="v2", command="curl http://web/read?file=../../etc/passwd"),
],
),
golden_path=[
GoldenPathStep(
step=1,
command="curl http://web/search?q=inject",
expect_in_stdout="SQLI_RESULT",
),
GoldenPathStep(
step=2,
command="curl http://web/read?file=../../etc/passwd",
expect_in_stdout="root:x:0",
),
],
)
# Remediation succeeds for both
mock_containers.exec_results[("web", "sed")] = ""
mock_containers.exec_results[("web", "rm")] = ""
# After patch, exploits fail (return empty)
mock_containers.exec_results[("attacker", "curl http://web/search")] = "blocked"
mock_containers.exec_results[("attacker", "curl http://web/read")] = "forbidden"
result = await PatchabilityCheck().check(spec, mock_containers)
assert result.passed is True
# Container should have been restarted once per tested vuln
assert mock_containers.restarted == ["web", "web"]
# ---------------------------------------------------------------------------
# Check 4: Evidence
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_evidence_passes_vacuously_when_no_spec(mock_containers):
from open_range.validator.evidence import EvidenceCheck
spec = SnapshotSpec(evidence_spec=[])
result = await EvidenceCheck().check(spec, mock_containers)
assert result.passed is True
@pytest.mark.asyncio
async def test_evidence_fails_when_pattern_missing(mock_containers):
from open_range.validator.evidence import EvidenceCheck
spec = SnapshotSpec(
evidence_spec=[
EvidenceItem(type="log_entry", location="siem:/var/log/test.log", pattern="ATTACK"),
]
)
# Return "0" matches from grep
mock_containers.exec_results[("siem", "grep")] = "0"
result = await EvidenceCheck().check(spec, mock_containers)
assert result.passed is False
@pytest.mark.asyncio
async def test_evidence_fails_when_grep_returns_error_text(mock_containers):
from open_range.validator.evidence import EvidenceCheck
spec = SnapshotSpec(
evidence_spec=[
EvidenceItem(type="log_entry", location="siem:/var/log/missing.log", pattern="ATTACK"),
]
)
mock_containers.exec_results[("siem", "grep")] = "grep: /var/log/missing.log: No such file or directory"
mock_containers.exec_status[("siem", "grep")] = 2
result = await EvidenceCheck().check(spec, mock_containers)
assert result.passed is False
assert "No such file or directory" in result.details["missing"][0]["error"]
@pytest.mark.asyncio
async def test_evidence_fails_on_nonzero_exit_even_when_output_present(mock_containers):
from open_range.validator.evidence import EvidenceCheck
spec = SnapshotSpec(
evidence_spec=[
EvidenceItem(type="artifact", location="siem:/var/log/test.log"),
]
)
mock_containers.exec_status[("siem", "test -f")] = 1
result = await EvidenceCheck().check(spec, mock_containers)
assert result.passed is False
assert result.details["missing"][0]["location"] == "siem:/var/log/test.log"
@pytest.mark.asyncio
async def test_evidence_quotes_pattern_and_location_path():
"""Evidence grep command must quote pattern and path from snapshot content."""
import shlex
from open_range.validator.evidence import EvidenceCheck
class RecordingContainers:
def __init__(self) -> None:
self.calls: list[tuple[str, str]] = []
async def exec_run(self, container: str, cmd: str, **kwargs) -> ExecResult:
self.calls.append((container, cmd))
return ExecResult(stdout="1", exit_code=0)
containers = RecordingContainers()
pattern = "ERR'; touch /tmp/pwn #"
path = "/var/log/app; echo PWNED"
spec = SnapshotSpec(
evidence_spec=[
EvidenceItem(type="log_entry", location=f"siem:{path}", pattern=pattern),
],
)
result = await EvidenceCheck().check(spec, containers) # type: ignore[arg-type]
assert result.passed is True
assert containers.calls
assert containers.calls[0][1] == f"grep -c {shlex.quote(pattern)} {shlex.quote(path)}"
# ---------------------------------------------------------------------------
# Check 5: Reward grounding
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_reward_grounding_passes_when_flag_found(mock_containers):
from open_range.validator.reward_grounding import RewardGroundingCheck
spec = SnapshotSpec(
flags=[FlagSpec(id="f1", value="FLAG{abc}", path="/var/flags/f.txt", host="web")]
)
mock_containers.exec_results[("web", "cat")] = "FLAG{abc}"
result = await RewardGroundingCheck().check(spec, mock_containers)
assert result.passed is True
@pytest.mark.asyncio
async def test_reward_grounding_fails_when_flag_wrong(mock_containers):
from open_range.validator.reward_grounding import RewardGroundingCheck
spec = SnapshotSpec(
flags=[FlagSpec(id="f1", value="FLAG{abc}", path="/var/flags/f.txt", host="web")]
)
mock_containers.exec_results[("web", "cat")] = "FLAG{wrong}"
result = await RewardGroundingCheck().check(spec, mock_containers)
assert result.passed is False
@pytest.mark.asyncio
async def test_reward_grounding_no_flags(mock_containers):
from open_range.validator.reward_grounding import RewardGroundingCheck
spec = SnapshotSpec(flags=[])
result = await RewardGroundingCheck().check(spec, mock_containers)
assert result.passed is False
@pytest.mark.asyncio
async def test_reward_grounding_verifies_db_flag(mock_containers):
"""DB-stored flag verified via MySQL query β value found."""
from open_range.validator.reward_grounding import RewardGroundingCheck
spec = SnapshotSpec(
flags=[FlagSpec(id="f1", value="FLAG{db_flag}", path="db:flags.secrets.flag", host="db")]
)
mock_containers.exec_results[("db", "mysql")] = "FLAG{db_flag}"
result = await RewardGroundingCheck().check(spec, mock_containers)
assert result.passed is True
@pytest.mark.asyncio
async def test_reward_grounding_fails_db_flag_not_found(mock_containers):
"""DB-stored flag verified via MySQL query β wrong value returned."""
from open_range.validator.reward_grounding import RewardGroundingCheck
spec = SnapshotSpec(
flags=[FlagSpec(id="f1", value="FLAG{db_flag}", path="db:flags.secrets.flag", host="db")]
)
mock_containers.exec_results[("db", "mysql")] = "FLAG{wrong_value}"
result = await RewardGroundingCheck().check(spec, mock_containers)
assert result.passed is False
assert "1 flag(s)" in result.error
@pytest.mark.asyncio
async def test_reward_grounding_skips_db_sql_path(mock_containers):
"""db:sql deployment artifacts are skipped, not treated as flag locations."""
from open_range.validator.reward_grounding import RewardGroundingCheck
spec = SnapshotSpec(
flags=[
FlagSpec(id="f1", value="FLAG{abc}", path="/var/flags/f.txt", host="web"),
FlagSpec(id="f2", value="FLAG{deploy}", path="db:sql", host="db"),
]
)
mock_containers.exec_results[("web", "cat")] = "FLAG{abc}"
result = await RewardGroundingCheck().check(spec, mock_containers)
assert result.passed is True
@pytest.mark.asyncio
async def test_reward_grounding_quotes_filesystem_path():
"""Filesystem flag paths with shell metacharacters must be quoted."""
from open_range.validator.reward_grounding import RewardGroundingCheck
class RecordingContainers:
def __init__(self):
self.calls: list[tuple[str, str]] = []
async def exec_run(self, container: str, cmd: str, **kwargs):
from open_range.protocols import ExecResult
self.calls.append((container, cmd))
return ExecResult(stdout="FLAG{abc}", exit_code=0)
async def exec(self, container: str, cmd: str, **kwargs) -> str:
return (await self.exec_run(container, cmd, **kwargs)).combined_output
containers = RecordingContainers()
spec = SnapshotSpec(
flags=[FlagSpec(id="f1", value="FLAG{abc}", path="/tmp/f; echo PWNED", host="web")]
)
result = await RewardGroundingCheck().check(spec, containers) # type: ignore[arg-type]
assert result.passed is True
assert containers.calls
assert containers.calls[0][1] == "cat -- '/tmp/f; echo PWNED'"
@pytest.mark.asyncio
async def test_reward_grounding_rejects_invalid_db_identifier_path():
"""Malformed DB paths must fail rather than altering SQL semantics."""
from open_range.validator.reward_grounding import RewardGroundingCheck
class RecordingContainers:
def __init__(self):
self.calls: list[tuple[str, str]] = []
async def exec_run(self, container: str, cmd: str, **kwargs):
from open_range.protocols import ExecResult
self.calls.append((container, cmd))
return ExecResult(stdout="FLAG{abc}", exit_code=0)
async def exec(self, container: str, cmd: str, **kwargs) -> str:
return (await self.exec_run(container, cmd, **kwargs)).combined_output
containers = RecordingContainers()
spec = SnapshotSpec(
flags=[
FlagSpec(
id="f1",
value="FLAG{abc}",
path="db:flags.secrets.flag FROM secrets; SELECT 'x' --",
host="db",
)
]
)
result = await RewardGroundingCheck().check(spec, containers) # type: ignore[arg-type]
assert result.passed is False
assert "invalid db flag path format" in result.details["results"][0]["error"]
assert containers.calls == []
@pytest.mark.asyncio
async def test_reward_grounding_quotes_mysql_password_from_snapshot():
"""DB checks must not rely on unquoted shell expansion for credentials."""
import shlex
from open_range.validator.reward_grounding import RewardGroundingCheck
class RecordingContainers:
def __init__(self):
self.calls: list[tuple[str, str]] = []
async def exec_run(self, container: str, cmd: str, **kwargs):
from open_range.protocols import ExecResult
self.calls.append((container, cmd))
return ExecResult(stdout="FLAG{abc}", exit_code=0)
async def exec(self, container: str, cmd: str, **kwargs) -> str:
return (await self.exec_run(container, cmd, **kwargs)).combined_output
containers = RecordingContainers()
password = "pa ss;$(id)"
spec = SnapshotSpec(
topology={"mysql_root_password": password},
flags=[FlagSpec(id="f1", value="FLAG{abc}", path="db:flags.secrets.flag", host="db")],
)
result = await RewardGroundingCheck().check(spec, containers) # type: ignore[arg-type]
assert result.passed is True
assert containers.calls
cmd = containers.calls[0][1]
assert cmd.startswith(
f"MYSQL_PWD={shlex.quote(password)} mysql -u root -N -e "
)
assert "-p$MYSQL_ROOT_PASSWORD" not in cmd
# ---------------------------------------------------------------------------
# Check 6: Isolation
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_isolation_passes_clean_briefing(mock_containers):
from open_range.validator.isolation import IsolationCheck
spec = SnapshotSpec(
topology={"hosts": ["web"], "zones": {}},
flags=[FlagSpec(id="f1", value="FLAG{secret}", path="/f.txt", host="web")],
golden_path=[],
task=TaskSpec(
red_briefing="Investigate the network.",
blue_briefing="Monitor for threats.",
),
)
result = await IsolationCheck().check(spec, mock_containers)
assert result.passed is True
@pytest.mark.asyncio
async def test_isolation_fails_when_flag_in_briefing(mock_containers):
from open_range.validator.isolation import IsolationCheck
spec = SnapshotSpec(
topology={"hosts": ["web"], "zones": {}},
flags=[FlagSpec(id="f1", value="FLAG{secret}", path="/f.txt", host="web")],
golden_path=[],
task=TaskSpec(
red_briefing="The flag is FLAG{secret}, go find it.",
blue_briefing="Monitor for threats.",
),
)
result = await IsolationCheck().check(spec, mock_containers)
assert result.passed is False
assert "flag value leaked" in result.error
@pytest.mark.asyncio
async def test_isolation_checks_multiple_ports(mock_containers):
"""Zone isolation probes multiple ports β all CLOSED means pass."""
from open_range.validator.isolation import IsolationCheck
spec = SnapshotSpec(
topology={
"hosts": ["attacker", "db"],
"zones": {"internal": ["db"]},
},
flags=[],
golden_path=[],
task=TaskSpec(red_briefing="Go.", blue_briefing="Watch."),
)
# All probes return CLOSED
mock_containers.exec_results[("attacker", "/dev/tcp/")] = "CLOSED"
result = await IsolationCheck().check(spec, mock_containers)
assert result.passed is True
@pytest.mark.asyncio
async def test_isolation_fails_on_non_ssh_port(mock_containers):
"""Zone isolation detects reachability on a non-SSH port (e.g. 3306)."""
from open_range.validator.isolation import IsolationCheck
spec = SnapshotSpec(
topology={
"hosts": ["attacker", "db"],
"zones": {"internal": ["db"]},
},
flags=[],
golden_path=[],
task=TaskSpec(red_briefing="Go.", blue_briefing="Watch."),
)
# Only port 3306 is OPEN; everything else CLOSED.
async def exec_side_effect(container, cmd, **kwargs):
if container == "attacker" and "/dev/tcp/" in cmd:
if " 3306 " in cmd:
return "OPEN"
return "CLOSED"
return ""
mock_containers.exec = exec_side_effect
result = await IsolationCheck().check(spec, mock_containers)
assert result.passed is False
assert "3306" in result.error
assert "db" in result.error
@pytest.mark.asyncio
async def test_isolation_uses_argument_safe_tcp_probe_for_target_name():
"""Target names are passed as positional args, not interpolated into script."""
from open_range.validator.isolation import IsolationCheck
class RecordingContainers:
def __init__(self) -> None:
self.calls: list[tuple[str, str]] = []
async def exec(self, container: str, cmd: str, **kwargs) -> str:
self.calls.append((container, cmd))
return "CLOSED"
containers = RecordingContainers()
target = "db'; touch /tmp/pwn #"
spec = SnapshotSpec(
topology={"hosts": ["attacker", "db"], "zones": {"internal": [target]}},
flags=[],
golden_path=[],
task=TaskSpec(red_briefing="Go.", blue_briefing="Watch."),
)
result = await IsolationCheck().check(spec, containers) # type: ignore[arg-type]
assert result.passed is True
assert containers.calls
first_cmd = containers.calls[0][1]
script_part, _, arg_part = first_cmd.partition(" _ ")
assert "bash -lc 'echo > /dev/tcp/\"$1\"/\"$2\"'" in script_part
assert "touch /tmp/pwn" not in script_part
assert "touch /tmp/pwn" in arg_part
# ---------------------------------------------------------------------------
# Check 7: Task feasibility
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_task_feasibility_passes_valid_spec(sample_snapshot_spec, mock_containers):
from open_range.validator.task_feasibility import TaskFeasibilityCheck
result = await TaskFeasibilityCheck().check(sample_snapshot_spec, mock_containers)
assert result.passed is True
@pytest.mark.asyncio
async def test_task_feasibility_fails_unknown_flag_host(mock_containers):
from open_range.validator.task_feasibility import TaskFeasibilityCheck
spec = SnapshotSpec(
topology={"hosts": ["web", "attacker"], "zones": {}},
flags=[FlagSpec(id="f1", value="FLAG{x}", path="/f.txt", host="nonexistent")],
golden_path=[],
)
result = await TaskFeasibilityCheck().check(spec, mock_containers)
assert result.passed is False
@pytest.mark.asyncio
async def test_task_feasibility_rejects_seed_vuln_without_task_path(mock_containers):
from open_range.validator.task_feasibility import TaskFeasibilityCheck
spec = SnapshotSpec(
topology={
"hosts": ["attacker", "web", "db"],
"zones": {"external": ["attacker"], "dmz": ["web"], "internal": ["db"]},
"dependency_edges": [{"source": "attacker", "target": "web"}],
"host_details": {
"attacker": {"services": ["nmap"]},
"web": {"services": ["nginx", "php-fpm"]},
"db": {"services": ["mysql"]},
},
},
truth_graph=TruthGraph(
vulns=[Vulnerability(id="path_traversal_1", type="path_traversal", host="web")],
exploit_chain=[
ExploitStep(
vuln_id="path_traversal_1",
command="curl 'http://web/download?file=../../../var/flags/path_traversal_mut1.txt'",
description="download planted flag",
)
],
),
flags=[FlagSpec(id="flag1", value="FLAG{path_mut1}", path="/var/flags/path_traversal_mut1.txt", host="web")],
evidence_spec=[EvidenceItem(type="log_entry", location="web:/var/log/app/access.log")],
golden_path=[
GoldenPathStep(
step=1,
command="curl http://web/",
expect_in_stdout="Welcome",
host="attacker",
)
],
task=TaskSpec(red_briefing="go", blue_briefing="watch"),
mutation_plan=MutationPlan(
parent_snapshot_id="root_snap",
ops=[
MutationOp(
mutation_id="seed_path",
op_type="seed_vuln",
target_selector={"host": "web"},
params={
"vuln_type": "path_traversal",
"instantiated_vuln_id": "path_traversal_1",
"instantiated_flag_id": "flag1",
"instantiated_flag_value": "FLAG{path_mut1}",
"instantiated_flag_host": "web",
"instantiated_exploit_command": "curl 'http://web/download?file=../../../var/flags/path_traversal_mut1.txt'",
},
)
],
),
)
spec.lineage.parent_snapshot_id = "root_snap"
spec.lineage.generation_depth = 1
result = await TaskFeasibilityCheck().check(spec, mock_containers)
assert result.passed is False
assert any(
"missing submit_flag step" in issue for issue in result.details["issues"]
)
# ---------------------------------------------------------------------------
# Check 8: Difficulty
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_difficulty_passes_tier1_with_8_steps(mock_containers):
from open_range.validator.difficulty import DifficultyCheck
steps = [GoldenPathStep(step=i, command=f"cmd_{i}") for i in range(1, 9)]
spec = SnapshotSpec(
topology={"tier": 1},
golden_path=steps,
truth_graph=TruthGraph(vulns=[
Vulnerability(id="v1", type="sqli", host="web"),
]),
)
result = await DifficultyCheck().check(spec, mock_containers)
assert result.passed is True
@pytest.mark.asyncio
async def test_difficulty_fails_tier1_with_3_steps(mock_containers):
from open_range.validator.difficulty import DifficultyCheck
steps = [GoldenPathStep(step=i, command=f"cmd_{i}") for i in range(1, 4)]
spec = SnapshotSpec(
topology={"tier": 1},
golden_path=steps,
truth_graph=TruthGraph(vulns=[
Vulnerability(id="v1", type="sqli", host="web"),
]),
)
result = await DifficultyCheck().check(spec, mock_containers)
assert result.passed is False
assert "steps" in result.error
@pytest.mark.asyncio
async def test_difficulty_fails_single_step(mock_containers):
from open_range.validator.difficulty import DifficultyCheck
spec = SnapshotSpec(
topology={"tier": 1},
golden_path=[GoldenPathStep(step=1, command="cmd1")],
truth_graph=TruthGraph(vulns=[
Vulnerability(id="v1", type="sqli", host="web"),
]),
)
result = await DifficultyCheck().check(spec, mock_containers)
assert result.passed is False
assert "trivial" in result.error or "steps" in result.error
@pytest.mark.asyncio
async def test_difficulty_fails_duplicate_consecutive(mock_containers):
from open_range.validator.difficulty import DifficultyCheck
steps = [GoldenPathStep(step=i, command="same_cmd") for i in range(1, 9)]
spec = SnapshotSpec(
topology={"tier": 1},
golden_path=steps,
truth_graph=TruthGraph(vulns=[
Vulnerability(id="v1", type="sqli", host="web"),
]),
)
result = await DifficultyCheck().check(spec, mock_containers)
assert result.passed is False
assert "duplicate" in result.error
# ---------------------------------------------------------------------------
# Check 9: NPC consistency β mechanical card validation
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_npc_consistency_passes_no_personas(mock_containers):
from open_range.validator.npc_consistency import NPCConsistencyCheck
spec = SnapshotSpec(npc_personas=[])
result = await NPCConsistencyCheck().check(spec, mock_containers)
assert result.passed is True
assert result.advisory is True
@pytest.mark.asyncio
async def test_npc_consistency_fails_high_awareness_high_susceptibility(mock_containers):
from open_range.validator.npc_consistency import NPCConsistencyCheck
spec = SnapshotSpec(
npc_personas=[
NPCPersona(
name="Alice",
security_awareness=0.9,
susceptibility={"phishing_email": 0.8},
)
]
)
result = await NPCConsistencyCheck().check(spec, mock_containers)
assert result.passed is False
assert result.advisory is True
@pytest.mark.asyncio
async def test_npc_consistency_fails_out_of_range_awareness(mock_containers):
from open_range.validator.npc_consistency import NPCConsistencyCheck
spec = SnapshotSpec(
npc_personas=[
NPCPersona(name="BadAwareness", security_awareness=1.5)
]
)
result = await NPCConsistencyCheck().check(spec, mock_containers)
assert result.passed is False
assert "out of [0, 1]" in result.details["issues"][0]
@pytest.mark.asyncio
async def test_npc_consistency_fails_low_awareness_low_susceptibility(mock_containers):
from open_range.validator.npc_consistency import NPCConsistencyCheck
spec = SnapshotSpec(
npc_personas=[
NPCPersona(
name="Bob",
security_awareness=0.2,
susceptibility={"phishing_email": 0.1, "vishing": 0.1},
)
]
)
result = await NPCConsistencyCheck().check(spec, mock_containers)
assert result.passed is False
assert "all susceptibility scores < 0.3" in result.details["issues"][0]
@pytest.mark.asyncio
async def test_npc_consistency_passes_valid_personas(mock_containers):
"""Valid personas with consistent awareness and susceptibility pass.
David (high awareness) passes the LLM test by correctly rejecting phishing.
Janet (mid-range awareness) is not tested by LLM β only mid-range skips.
"""
from open_range.validator.npc_consistency import NPCConsistencyCheck
spec = SnapshotSpec(
npc_personas=[
NPCPersona(
name="David Chen",
role="CISO",
department="Security",
security_awareness=0.95,
susceptibility={
"phishing_email": 0.05,
"credential_sharing": 0.01,
"attachment_opening": 0.1,
"vishing": 0.05,
},
accounts={"ldap": "dchen"},
),
NPCPersona(
name="Janet Smith",
role="Marketing Coordinator",
department="Marketing",
security_awareness=0.5,
susceptibility={
"phishing_email": 0.5,
"credential_sharing": 0.3,
},
),
]
)
# David (high awareness) should report phishing to IT.
mock_acompletion = AsyncMock(
return_value=_make_llm_response(
"report_to_IT",
"This is clearly a phishing attempt.",
["urgency", "suspicious link"],
)
)
with patch("litellm.acompletion", mock_acompletion):
result = await NPCConsistencyCheck().check(spec, mock_containers)
assert result.passed is True
# Only David should be tested (high awareness) β Janet is mid-range.
assert mock_acompletion.call_count == 1
# ---------------------------------------------------------------------------
# Check 9: NPC consistency β LLM behavioral tests
# ---------------------------------------------------------------------------
def _make_llm_response(action: str, reasoning: str = "", suspicious: list | None = None):
"""Helper to create a mock litellm response."""
content = json.dumps({
"action": action,
"reasoning": reasoning,
"suspicious_elements_noticed": suspicious or [],
})
message = MagicMock()
message.content = content
choice = MagicMock()
choice.message = message
response = MagicMock()
response.choices = [choice]
return response
@pytest.mark.asyncio
async def test_npc_consistency_llm_high_awareness_rejects_phishing(mock_containers):
"""High-awareness NPC correctly rejects phishing β check passes."""
from open_range.validator.npc_consistency import NPCConsistencyCheck
spec = SnapshotSpec(
npc_personas=[
NPCPersona(
name="David Chen",
role="CISO",
department="Security",
security_awareness=0.95,
susceptibility={
"phishing_email": 0.05,
"credential_sharing": 0.01,
},
accounts={"ldap": "dchen"},
),
]
)
mock_acompletion = AsyncMock(
return_value=_make_llm_response(
"report_to_IT",
"This looks like a phishing attempt.",
["suspicious link", "urgency"],
)
)
with patch("litellm.acompletion", mock_acompletion):
result = await NPCConsistencyCheck().check(spec, mock_containers)
assert result.passed is True
assert result.advisory is True
@pytest.mark.asyncio
async def test_npc_consistency_llm_high_awareness_falls_for_phishing(mock_containers):
"""High-awareness NPC falls for phishing β check fails."""
from open_range.validator.npc_consistency import NPCConsistencyCheck
spec = SnapshotSpec(
npc_personas=[
NPCPersona(
name="David Chen",
role="CISO",
department="Security",
security_awareness=0.95,
susceptibility={
"phishing_email": 0.05,
},
accounts={"ldap": "dchen"},
),
]
)
mock_acompletion = AsyncMock(
return_value=_make_llm_response(
"click_link",
"I should reset my password as requested.",
)
)
with patch("litellm.acompletion", mock_acompletion):
result = await NPCConsistencyCheck().check(spec, mock_containers)
assert result.passed is False
assert result.advisory is True
assert "fell for test phishing" in result.details["issues"][0]
@pytest.mark.asyncio
async def test_npc_consistency_llm_low_awareness_falls_for_phishing(mock_containers):
"""Low-awareness NPC falls for phishing β check passes (expected behavior)."""
from open_range.validator.npc_consistency import NPCConsistencyCheck
spec = SnapshotSpec(
npc_personas=[
NPCPersona(
name="Janet Smith",
role="Marketing Coordinator",
department="Marketing",
security_awareness=0.2,
susceptibility={
"phishing_email": 0.7,
"attachment_opening": 0.8,
},
accounts={"ldap": "jsmith"},
),
]
)
mock_acompletion = AsyncMock(
return_value=_make_llm_response(
"click_link",
"I need to reset my password right away!",
)
)
with patch("litellm.acompletion", mock_acompletion):
result = await NPCConsistencyCheck().check(spec, mock_containers)
assert result.passed is True
assert result.advisory is True
@pytest.mark.asyncio
async def test_npc_consistency_llm_low_awareness_rejects_phishing(mock_containers):
"""Low-awareness NPC rejects phishing β check fails (miscalibrated persona)."""
from open_range.validator.npc_consistency import NPCConsistencyCheck
spec = SnapshotSpec(
npc_personas=[
NPCPersona(
name="Janet Smith",
role="Marketing Coordinator",
department="Marketing",
security_awareness=0.2,
susceptibility={
"phishing_email": 0.7,
},
accounts={"ldap": "jsmith"},
),
]
)
mock_acompletion = AsyncMock(
return_value=_make_llm_response(
"report_to_IT",
"This seems suspicious, I'll forward it to IT.",
["suspicious URL"],
)
)
with patch("litellm.acompletion", mock_acompletion):
result = await NPCConsistencyCheck().check(spec, mock_containers)
assert result.passed is False
assert result.advisory is True
assert "rejected test phishing" in result.details["issues"][0]
assert "miscalibrated" in result.details["issues"][0]
@pytest.mark.asyncio
async def test_npc_consistency_llm_failure_degrades_gracefully(mock_containers):
"""LLM failure does not cause the check to fail β degrades gracefully."""
from open_range.validator.npc_consistency import NPCConsistencyCheck
spec = SnapshotSpec(
npc_personas=[
NPCPersona(
name="David Chen",
role="CISO",
security_awareness=0.95,
susceptibility={"phishing_email": 0.05},
accounts={"ldap": "dchen"},
),
]
)
mock_acompletion = AsyncMock(side_effect=Exception("API rate limit exceeded"))
with patch("litellm.acompletion", mock_acompletion):
result = await NPCConsistencyCheck().check(spec, mock_containers)
# LLM failure should not cause the check to fail β mechanical checks passed.
assert result.passed is True
assert result.advisory is True
@pytest.mark.asyncio
async def test_npc_consistency_skips_mid_awareness_llm_test(mock_containers):
"""Mid-range awareness personas (0.3-0.8) skip LLM behavioral test."""
from open_range.validator.npc_consistency import NPCConsistencyCheck
spec = SnapshotSpec(
npc_personas=[
NPCPersona(
name="Bob Neutral",
role="Accountant",
security_awareness=0.5,
susceptibility={"phishing_email": 0.5},
),
]
)
# The LLM should NOT be called for mid-range personas.
mock_acompletion = AsyncMock(
side_effect=AssertionError("LLM should not be called for mid-range awareness")
)
with patch("litellm.acompletion", mock_acompletion):
result = await NPCConsistencyCheck().check(spec, mock_containers)
assert result.passed is True
mock_acompletion.assert_not_called()
# ---------------------------------------------------------------------------
# Check 10: Realism review (LLM advisory)
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_realism_review_advisory_flag(mock_containers):
from open_range.validator.realism_review import RealismReviewCheck
spec = SnapshotSpec(topology={"hosts": ["web"], "tier": 1})
with patch("litellm.acompletion", AsyncMock(side_effect=Exception("no provider configured"))):
result = await RealismReviewCheck().check(spec, mock_containers)
# Should pass (advisory) when the LLM path is unavailable or misconfigured.
assert result.advisory is True
assert result.passed is True
@pytest.mark.asyncio
async def test_realism_review_passes_with_llm(mock_containers):
"""Realism review passes when LLM finds no issues."""
from open_range.validator.realism_review import RealismReviewCheck
spec = SnapshotSpec(
topology={"hosts": ["web", "db"], "tier": 1},
truth_graph=TruthGraph(vulns=[
Vulnerability(id="v1", type="sqli", host="web"),
]),
golden_path=[GoldenPathStep(step=i, command=f"cmd_{i}") for i in range(1, 9)],
task=TaskSpec(
red_briefing="Investigate the corporate network.",
blue_briefing="Monitor for threats.",
),
)
llm_response_content = json.dumps({"pass": True, "issues": []})
message = MagicMock()
message.content = llm_response_content
choice = MagicMock()
choice.message = message
mock_response = MagicMock()
mock_response.choices = [choice]
mock_acompletion = AsyncMock(return_value=mock_response)
with patch("litellm.acompletion", mock_acompletion):
result = await RealismReviewCheck().check(spec, mock_containers)
assert result.passed is True
assert result.advisory is True
assert result.details["issues"] == []
@pytest.mark.asyncio
async def test_realism_review_fails_with_issues(mock_containers):
"""Realism review fails when LLM finds issues (but still advisory)."""
from open_range.validator.realism_review import RealismReviewCheck
spec = SnapshotSpec(
topology={"hosts": ["web"], "tier": 1},
truth_graph=TruthGraph(vulns=[
Vulnerability(id="v1", type="sqli", host="web"),
]),
golden_path=[GoldenPathStep(step=1, command="cmd_1")],
task=TaskSpec(
red_briefing="Find the SQL injection vulnerability.",
blue_briefing="Monitor for threats.",
),
)
issues = ["Red briefing leaks vulnerability type (SQL injection)"]
llm_response_content = json.dumps({"pass": False, "issues": issues})
message = MagicMock()
message.content = llm_response_content
choice = MagicMock()
choice.message = message
mock_response = MagicMock()
mock_response.choices = [choice]
mock_acompletion = AsyncMock(return_value=mock_response)
with patch("litellm.acompletion", mock_acompletion):
result = await RealismReviewCheck().check(spec, mock_containers)
assert result.passed is False
assert result.advisory is True
assert "SQL injection" in result.error
assert result.details["issues"] == issues
@pytest.mark.asyncio
async def test_realism_review_never_sends_flags_to_llm(mock_containers):
"""Verify the redacted summary sent to LLM never contains flag values."""
from open_range.validator.realism_review import RealismReviewCheck
flag_value = "FLAG{super_secret_123}"
spec = SnapshotSpec(
topology={"hosts": ["web", "db"], "tier": 1},
truth_graph=TruthGraph(vulns=[
Vulnerability(id="v1", type="sqli", host="web"),
]),
flags=[FlagSpec(id="f1", value=flag_value, path="/f.txt", host="db")],
golden_path=[
GoldenPathStep(
step=1,
command=f"cat /f.txt # reveals {flag_value}",
expect_in_stdout=flag_value,
),
],
task=TaskSpec(
red_briefing="Investigate the network.",
blue_briefing="Monitor for threats.",
),
)
captured_messages = []
async def capturing_acompletion(**kwargs):
captured_messages.append(kwargs.get("messages", []))
content = json.dumps({"pass": True, "issues": []})
message = MagicMock()
message.content = content
choice = MagicMock()
choice.message = message
response = MagicMock()
response.choices = [choice]
return response
with patch("litellm.acompletion", capturing_acompletion):
result = await RealismReviewCheck().check(spec, mock_containers)
assert result.passed is True
# Verify the flag value was NOT in the messages sent to LLM
for msg_list in captured_messages:
for msg in msg_list:
assert flag_value not in msg.get("content", ""), \
"Flag value was leaked to the LLM reviewer!"
# Also verify golden path commands are not leaked
assert "cat /f.txt" not in msg.get("content", ""), \
"Golden path command was leaked to the LLM reviewer!"
@pytest.mark.asyncio
async def test_realism_review_llm_failure_degrades_gracefully(mock_containers):
"""LLM failure should not block validation β passes with advisory note."""
from open_range.validator.realism_review import RealismReviewCheck
spec = SnapshotSpec(
topology={"hosts": ["web"], "tier": 1},
truth_graph=TruthGraph(vulns=[
Vulnerability(id="v1", type="sqli", host="web"),
]),
golden_path=[GoldenPathStep(step=i, command=f"cmd_{i}") for i in range(1, 9)],
task=TaskSpec(red_briefing="Investigate.", blue_briefing="Monitor."),
)
mock_acompletion = AsyncMock(side_effect=Exception("API key invalid"))
with patch("litellm.acompletion", mock_acompletion):
result = await RealismReviewCheck().check(spec, mock_containers)
# Should pass even though LLM failed β advisory check degrades gracefully.
assert result.passed is True
assert result.advisory is True
assert "LLM review failed" in result.details["note"]
@pytest.mark.asyncio
async def test_realism_review_malformed_llm_response(mock_containers):
"""Malformed LLM JSON response degrades gracefully."""
from open_range.validator.realism_review import RealismReviewCheck
spec = SnapshotSpec(
topology={"hosts": ["web"], "tier": 1},
truth_graph=TruthGraph(vulns=[
Vulnerability(id="v1", type="sqli", host="web"),
]),
golden_path=[GoldenPathStep(step=i, command=f"cmd_{i}") for i in range(1, 9)],
task=TaskSpec(red_briefing="Investigate.", blue_briefing="Monitor."),
)
# Return invalid JSON
message = MagicMock()
message.content = "not valid json at all"
choice = MagicMock()
choice.message = message
mock_response = MagicMock()
mock_response.choices = [choice]
mock_acompletion = AsyncMock(return_value=mock_response)
with patch("litellm.acompletion", mock_acompletion):
result = await RealismReviewCheck().check(spec, mock_containers)
# Should pass gracefully β bad JSON is handled like an LLM failure.
assert result.passed is True
assert result.advisory is True
# ---------------------------------------------------------------------------
# ValidatorGate
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_validator_gate_all_pass(sample_snapshot_spec, mock_containers):
"""Gate with passing checks returns passed=True."""
class AlwaysPass:
async def check(self, snapshot, containers):
return CheckResult(name="pass_check", passed=True)
gate = ValidatorGate([AlwaysPass(), AlwaysPass()])
result = await gate.validate(sample_snapshot_spec, mock_containers)
assert result.passed is True
assert len(result.checks) == 2
assert result.total_time_s >= 0
@pytest.mark.asyncio
async def test_validator_gate_fail_fast_on_mechanical(sample_snapshot_spec, mock_containers):
"""Mechanical failure stops the pipeline."""
class Fail:
async def check(self, snapshot, containers):
return CheckResult(name="fail_check", passed=False, error="broken")
class NeverReached:
async def check(self, snapshot, containers):
raise AssertionError("should not be reached")
gate = ValidatorGate([Fail(), NeverReached()])
result = await gate.validate(sample_snapshot_spec, mock_containers)
assert result.passed is False
assert len(result.checks) == 1 # second check was never run
@pytest.mark.asyncio
async def test_validator_gate_advisory_does_not_block(sample_snapshot_spec, mock_containers):
"""Advisory check failure does not prevent overall pass."""
class Pass:
async def check(self, snapshot, containers):
return CheckResult(name="ok", passed=True)
class AdvisoryFail:
async def check(self, snapshot, containers):
return CheckResult(name="adv", passed=False, advisory=True, error="meh")
gate = ValidatorGate([Pass(), AdvisoryFail()])
result = await gate.validate(sample_snapshot_spec, mock_containers)
assert result.passed is True
assert len(result.checks) == 2
@pytest.mark.asyncio
async def test_validator_gate_catches_exception(sample_snapshot_spec, mock_containers):
"""Unhandled exception in a check is caught and recorded as failure."""
class Boom:
async def check(self, snapshot, containers):
raise RuntimeError("kaboom")
gate = ValidatorGate([Boom()])
result = await gate.validate(sample_snapshot_spec, mock_containers)
assert result.passed is False
assert "kaboom" in result.checks[0].error
@pytest.mark.asyncio
async def test_validator_gate_advisory_failure_does_not_stop_pipeline(
sample_snapshot_spec, mock_containers
):
"""Advisory failures do not stop the pipeline β subsequent checks still run."""
class MechanicalPass:
async def check(self, snapshot, containers):
return CheckResult(name="mechanical_ok", passed=True)
class AdvisoryFail:
async def check(self, snapshot, containers):
return CheckResult(name="advisory_fail", passed=False, advisory=True, error="soft fail")
class SecondMechanicalPass:
async def check(self, snapshot, containers):
return CheckResult(name="mechanical_ok_2", passed=True)
gate = ValidatorGate([MechanicalPass(), AdvisoryFail(), SecondMechanicalPass()])
result = await gate.validate(sample_snapshot_spec, mock_containers)
assert result.passed is True
assert len(result.checks) == 3 # All three checks ran
@pytest.mark.asyncio
async def test_validator_gate_mixed_mechanical_advisory(sample_snapshot_spec, mock_containers):
"""Mechanical pass + advisory fail = overall pass."""
checks_run = []
class Mechanical:
async def check(self, snapshot, containers):
checks_run.append("mechanical")
return CheckResult(name="mechanical", passed=True)
class Advisory:
async def check(self, snapshot, containers):
checks_run.append("advisory")
return CheckResult(name="advisory", passed=False, advisory=True, error="issue")
gate = ValidatorGate([Mechanical(), Advisory()])
result = await gate.validate(sample_snapshot_spec, mock_containers)
assert result.passed is True
assert checks_run == ["mechanical", "advisory"]
# Advisory failure should be recorded
assert result.checks[1].passed is False
assert result.checks[1].advisory is True
@pytest.mark.asyncio
async def test_validator_gate_mechanical_fail_before_advisory(
sample_snapshot_spec, mock_containers
):
"""Mechanical failure before advisory checks prevents advisory from running."""
class MechanicalFail:
async def check(self, snapshot, containers):
return CheckResult(name="mech_fail", passed=False, error="hard fail")
class AdvisoryNeverReached:
async def check(self, snapshot, containers):
raise AssertionError("should not reach advisory check")
gate = ValidatorGate([MechanicalFail(), AdvisoryNeverReached()])
result = await gate.validate(sample_snapshot_spec, mock_containers)
assert result.passed is False
assert len(result.checks) == 1
# ---------------------------------------------------------------------------
# Full 10-check pipeline simulation
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_full_pipeline_all_mechanical_pass_advisory_pass(
sample_snapshot_spec, mock_containers
):
"""Simulate all 10 checks passing."""
class MechanicalPass:
async def check(self, snapshot, containers):
return CheckResult(name="mechanical", passed=True)
class NPCConsistencyCheck:
async def check(self, snapshot, containers):
return CheckResult(name="npc_consistency", passed=True, advisory=True)
class RealismReviewCheck:
async def check(self, snapshot, containers):
return CheckResult(name="realism_review", passed=True, advisory=True)
checks = [MechanicalPass() for _ in range(8)]
checks.append(NPCConsistencyCheck())
checks.append(RealismReviewCheck())
gate = ValidatorGate(checks)
result = await gate.validate(sample_snapshot_spec, mock_containers)
assert result.passed is True
assert len(result.checks) == 10
@pytest.mark.asyncio
async def test_full_pipeline_mechanical_pass_advisory_fail(
sample_snapshot_spec, mock_containers
):
"""All mechanical pass, advisory checks fail β overall still passes."""
class MechanicalPass:
async def check(self, snapshot, containers):
return CheckResult(name="mechanical", passed=True)
class NPCConsistencyCheck:
async def check(self, snapshot, containers):
return CheckResult(
name="npc_consistency", passed=False, advisory=True,
error="NPC miscalibrated"
)
class RealismReviewCheck:
async def check(self, snapshot, containers):
return CheckResult(
name="realism_review", passed=False, advisory=True,
error="briefing leakage"
)
checks = [MechanicalPass() for _ in range(8)]
checks.append(NPCConsistencyCheck())
checks.append(RealismReviewCheck())
gate = ValidatorGate(checks)
result = await gate.validate(sample_snapshot_spec, mock_containers)
assert result.passed is True
assert len(result.checks) == 10
# Advisory failures are recorded
assert result.checks[8].passed is False
assert result.checks[8].advisory is True
assert result.checks[9].passed is False
assert result.checks[9].advisory is True
@pytest.mark.asyncio
async def test_full_pipeline_mechanical_fail_skips_rest(
sample_snapshot_spec, mock_containers
):
"""Mechanical failure at check 3 stops pipeline β checks 4-10 never run."""
run_order = []
class TrackedPass:
def __init__(self, n):
self.n = n
async def check(self, snapshot, containers):
run_order.append(self.n)
return CheckResult(name=f"check_{self.n}", passed=True)
class TrackedFail:
def __init__(self, n):
self.n = n
async def check(self, snapshot, containers):
run_order.append(self.n)
return CheckResult(name=f"check_{self.n}", passed=False, error="fail")
checks = [TrackedPass(1), TrackedPass(2), TrackedFail(3)]
checks.extend([TrackedPass(i) for i in range(4, 9)])
# Checks 9 and 10 are advisory but never reached
checks.append(TrackedPass(9))
checks.append(TrackedPass(10))
gate = ValidatorGate(checks)
result = await gate.validate(sample_snapshot_spec, mock_containers)
assert result.passed is False
assert run_order == [1, 2, 3] # Only first 3 ran
assert len(result.checks) == 3
|