Spaces:
Running
Running
File size: 78,910 Bytes
6360508 f8dbd1b 6360508 f8dbd1b 2f51a0f 38403fa 6360508 38403fa 6360508 621c68e f8dbd1b 6360508 f4e8387 085f660 6360508 621c68e 6360508 085f660 adfad95 085f660 adfad95 085f660 adfad95 085f660 adfad95 085f660 adfad95 085f660 adfad95 085f660 f4e8387 27cb6df f4e8387 6b389a5 085f660 adfad95 085f660 adfad95 085f660 f8dbd1b f4e8387 f8dbd1b 38403fa f8dbd1b 38403fa f8dbd1b 085f660 f4e8387 f8dbd1b 085f660 f8dbd1b 621c68e 38403fa 085f660 38403fa 085f660 adfad95 085f660 38403fa f8dbd1b 2f51a0f 085f660 2f51a0f 085f660 2f51a0f 085f660 2f51a0f 085f660 2f51a0f f4e8387 f8dbd1b f4e8387 f8dbd1b f4e8387 f8dbd1b f4e8387 f8dbd1b 6360508 38403fa 6360508 a67aa64 38403fa 03c2136 38403fa 6360508 | 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 | from __future__ import annotations
import contextlib
import importlib.util
import io
import json
import os
import stat
import tempfile
import unittest
import warnings
import zipfile
from pathlib import Path
from types import SimpleNamespace
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
TAG_COMMIT = "a" * 40
EXPECTED_FIRST_KILL_COMMANDS = frozenset(
{
"/bin/sleep",
"/usr/bin/env",
"/usr/bin/git",
"/usr/bin/gpg",
"/usr/bin/journalctl",
"/usr/bin/nsenter",
"/usr/bin/python3",
"/usr/bin/systemctl",
"/usr/bin/systemd-run",
"/usr/sbin/groupdel",
"/usr/sbin/ip",
"/usr/sbin/nft",
"/usr/sbin/runuser",
"/usr/sbin/useradd",
"/usr/sbin/userdel",
}
)
SPEC = importlib.util.spec_from_file_location("first_kill", ROOT / "scripts" / "first_kill.py")
if SPEC is None or SPEC.loader is None:
raise RuntimeError("cannot load first-kill script")
first_kill = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(first_kill)
def success_receipt(**overrides: object) -> dict[str, object]:
value: dict[str, object] = {
"result": "TERMINATED",
"detector": {"profile": "content.gguf-llama", "path": "PRIVATE"},
"trigger": {"kind": "UNAPPROVED_AI_MATCH", "pid": 424242},
"capture": {"captured_processes": 1, "path": "PRIVATE"},
"containment": {
"primitive": "pidfd-stop+cgroup.kill",
"root_populated": 0,
"surviving_pids": [],
"trigger_to_empty_ms": 42.5,
},
}
value.update(overrides)
return value
@contextlib.contextmanager
def publication_mocks(
*,
destination_exists: bool = False,
link_race: bool = False,
parent_race: bool = False,
write_side_effect=None,
fsync_side_effect=None,
):
"""Exercise publish_success_result through mocked POSIX descriptor calls."""
destination = Path(os.path.abspath(os.path.join(os.sep, "synthetic-result", "result.json")))
parent_fd = 101
temporary_fd = 102
parent_info = SimpleNamespace(
st_mode=stat.S_IFDIR | 0o700,
st_uid=0,
st_dev=11,
st_ino=22,
st_file_attributes=0,
)
temporary_info = SimpleNamespace(
st_mode=stat.S_IFREG | 0o600,
st_uid=0,
st_dev=11,
st_ino=33,
st_file_attributes=0,
)
existing_info = SimpleNamespace(
st_mode=stat.S_IFREG | 0o600,
st_uid=0,
st_dev=11,
st_ino=44,
st_file_attributes=0,
)
temporary_name: list[str | None] = [None]
temporary_stats = 0
destination_checked = False
destination_unlinked = False
stat_calls: list[tuple[object, object]] = []
def fake_open(name, _flags, _mode=0o777, **kwargs):
if kwargs.get("dir_fd") == parent_fd:
temporary_name[0] = name
return temporary_fd
return parent_fd
def fake_stat(name, **kwargs):
nonlocal destination_checked, temporary_stats
stat_calls.append((name, kwargs.get("dir_fd")))
if name == destination.name:
if destination_unlinked:
raise FileNotFoundError(name)
if destination_exists:
return existing_info
if not destination_checked:
destination_checked = True
raise FileNotFoundError(name)
return temporary_info
temporary_stats += 1
if temporary_stats <= 2:
return temporary_info
raise FileNotFoundError(name)
def fake_link(*_args, **_kwargs):
if link_race:
raise FileExistsError(destination.name)
def fake_unlink(name, **_kwargs):
nonlocal destination_unlinked
if name == destination.name:
destination_unlinked = True
if write_side_effect is None:
write_side_effect = lambda _fd, view: len(view)
write = mock.Mock(side_effect=write_side_effect)
open_call = mock.Mock(side_effect=fake_open)
stat_call = mock.Mock(side_effect=fake_stat)
link = mock.Mock(side_effect=fake_link)
unlink = mock.Mock(side_effect=fake_unlink)
close = mock.Mock()
fsync = mock.Mock(side_effect=fsync_side_effect)
class SupportsAll:
def __contains__(self, _value):
return True
with contextlib.ExitStack() as stack:
stack.enter_context(mock.patch.object(first_kill, "validate_result_output", return_value=destination))
stack.enter_context(mock.patch.object(first_kill, "_result_output_effective_uid", return_value=0))
stack.enter_context(mock.patch.object(first_kill, "_result_output_parent_matches", return_value=not parent_race))
stack.enter_context(mock.patch.object(first_kill, "_result_output_parent_path_matches", return_value=True))
stack.enter_context(mock.patch.object(first_kill.os, "O_DIRECTORY", 0x10000, create=True))
stack.enter_context(mock.patch.object(first_kill.os, "O_NOFOLLOW", 0x20000, create=True))
stack.enter_context(mock.patch.object(first_kill.os, "supports_dir_fd", SupportsAll(), create=True))
stack.enter_context(mock.patch.object(first_kill.os, "lstat", return_value=parent_info))
stack.enter_context(mock.patch.object(first_kill.os, "open", open_call))
stack.enter_context(mock.patch.object(first_kill.os, "fchmod", mock.Mock(), create=True))
stack.enter_context(mock.patch.object(first_kill.os, "fstat", return_value=temporary_info))
stack.enter_context(mock.patch.object(first_kill.os, "write", write))
stack.enter_context(mock.patch.object(first_kill.os, "fsync", fsync))
stack.enter_context(mock.patch.object(first_kill.os, "close", close))
stack.enter_context(mock.patch.object(first_kill.os, "stat", stat_call))
stack.enter_context(mock.patch.object(first_kill.os, "link", link))
stack.enter_context(mock.patch.object(first_kill.os, "unlink", unlink))
stack.enter_context(mock.patch.object(first_kill.secrets, "token_hex", return_value="fixed"))
yield {
"destination": destination,
"fsync": fsync,
"link": link,
"open": open_call,
"stat": stat_call,
"stat_calls": stat_calls,
"temporary_name": temporary_name,
"unlink": unlink,
"write": write,
}
class FirstKillTests(unittest.TestCase):
def assert_entrypoint_refuses_before_side_effects(
self,
expected_reason_code: str,
passwd=None,
group=None,
platform_release: str = "6.8.0-generic",
wsl_distro_name: str | None = None,
total_memory_bytes: int | None = None,
free_root_bytes: int | None = None,
) -> None:
if passwd is None:
passwd = mock.Mock()
def clean_passwd_lookup(name: str):
if name == first_kill.WORKLOAD_USER:
raise KeyError(name)
return object()
passwd.getpwnam.side_effect = clean_passwd_lookup
if group is None:
group = mock.Mock()
group.getgrnam.side_effect = KeyError(first_kill.WORKLOAD_USER)
operator_name = mock.Mock(return_value="tester")
repository_root = mock.Mock()
prepare_workspace = mock.Mock()
release_files = mock.Mock()
install_release = mock.Mock()
run_real_smoke = mock.Mock()
remove_installation = mock.Mock()
make_temporary = mock.Mock()
environment = {}
if wsl_distro_name is not None:
environment["WSL_DISTRO_NAME"] = wsl_distro_name
errors = io.StringIO()
memory = mock.Mock(
return_value=(
first_kill.MIN_TOTAL_MEMORY_BYTES
if total_memory_bytes is None
else total_memory_bytes
)
)
disk = mock.Mock(
return_value=(
first_kill.MIN_FREE_ROOT_BYTES
if free_root_bytes is None
else free_root_bytes
)
)
with (
mock.patch.multiple(
first_kill,
operator_name=operator_name,
pwd=passwd,
grp=group,
repository_root=repository_root,
prepare_workspace=prepare_workspace,
release_files=release_files,
install_release=install_release,
run_real_smoke=run_real_smoke,
remove_installation=remove_installation,
total_memory_bytes=memory,
free_root_bytes=disk,
),
mock.patch.multiple(
first_kill.os,
geteuid=mock.Mock(return_value=0),
pidfd_open=mock.Mock(),
access=mock.Mock(return_value=True),
environ=environment,
create=True,
),
mock.patch.object(first_kill.signal, "pidfd_send_signal", create=True),
mock.patch.multiple(
first_kill.platform,
system=mock.Mock(return_value="Linux"),
release=mock.Mock(return_value=platform_release),
),
mock.patch.multiple(
first_kill.Path,
read_text=mock.Mock(return_value="pids"),
exists=mock.Mock(return_value=False),
is_symlink=mock.Mock(return_value=False),
),
mock.patch.object(first_kill.shutil, "which", return_value="/usr/bin/tool"),
mock.patch.object(first_kill.tempfile, "mkdtemp", make_temporary),
contextlib.redirect_stderr(errors),
):
result = first_kill.main(
["--operator", "tester", "--accept-third-party-downloads"]
)
self.assertEqual(2, result)
summary = json.loads(errors.getvalue())
self.assertEqual(first_kill.FULL_RUN_FAILURE_FIELDS, set(summary))
self.assertEqual(first_kill.FULL_RUN_FAILURE_SCHEMA, summary["schema"])
self.assertEqual(first_kill.FULL_RUN_FAILURE_VERSION, summary["version"])
self.assertEqual("FULL_RUN_FAILED", summary["result"])
self.assertEqual(first_kill.FULL_RUN_STAGE_PRE_INSTALL, summary["stage"])
self.assertEqual(expected_reason_code, summary["reason_code"])
self.assertEqual(
first_kill.FULL_RUN_INSTALL_STATE_NOT_INSTALLED,
summary["installation_state"],
)
self.assertEqual(first_kill.FULL_RUN_REMOVAL_NOT_REQUIRED, summary["removal_guidance"])
self.assertEqual(first_kill.FULL_RUN_NEXT_ACTION, summary["next_action"])
for forbidden in (
repository_root,
prepare_workspace,
release_files,
install_release,
run_real_smoke,
remove_installation,
make_temporary,
):
forbidden.assert_not_called()
def test_minimum_memory_is_seven_gibibytes(self) -> None:
self.assertEqual(7 * 1024 * 1024 * 1024, first_kill.MIN_TOTAL_MEMORY_BYTES)
def test_minimum_free_root_disk_is_eight_gibibytes(self) -> None:
self.assertEqual(8 * 1024 * 1024 * 1024, first_kill.MIN_FREE_ROOT_BYTES)
def test_low_memory_refusal_precedes_entrypoint_side_effects(self) -> None:
with mock.patch.object(
first_kill.Path, "is_file", autospec=True, return_value=True
):
self.assert_entrypoint_refuses_before_side_effects(
"PRE_INSTALL_FAILURE",
total_memory_bytes=first_kill.MIN_TOTAL_MEMORY_BYTES - 1,
)
def test_low_disk_refusal_precedes_entrypoint_side_effects(self) -> None:
with mock.patch.object(
first_kill.Path, "is_file", autospec=True, return_value=True
):
self.assert_entrypoint_refuses_before_side_effects(
"PRE_INSTALL_FAILURE",
free_root_bytes=first_kill.MIN_FREE_ROOT_BYTES - 1,
)
def test_wsl_refusal_precedes_entrypoint_side_effects(self) -> None:
with mock.patch.object(
first_kill.Path, "is_file", autospec=True, return_value=True
):
self.assert_entrypoint_refuses_before_side_effects(
"PRE_INSTALL_FAILURE",
platform_release="6.18.33.1-microsoft-standard-WSL2",
)
def test_wsl_environment_refusal_precedes_entrypoint_side_effects(self) -> None:
with mock.patch.object(
first_kill.Path, "is_file", autospec=True, return_value=True
):
self.assert_entrypoint_refuses_before_side_effects(
"PRE_INSTALL_FAILURE",
platform_release="6.8.0-custom",
wsl_distro_name="test-wsl",
)
def test_default_release_identity_is_the_1_0_candidate(self) -> None:
self.assertEqual("v1.0.10", first_kill.DEFAULT_TAG)
def test_third_party_plan_is_exact_and_deterministic(self) -> None:
expected = {
"schema_version": "lumi-eggcracker.third-party-download-plan.v1",
"plan_version": 1,
"result": "THIRD_PARTY_DOWNLOAD_PLAN",
"mode": "offline-source-only",
"llama": {
"repository": "https://github.com/ggml-org/llama.cpp.git",
"tag": "b10240",
"commit": "0b14b87d7c20cb753b94b96854dd7b45306fc696",
"license": "MIT",
"license_status": "DECLARED_METADATA_NOT_VERIFIED",
"license_verified": False,
"legal_clearance": False,
},
"model": {
"url": "https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/9217f5db79a29953eb74d5343926648285ec7e67/qwen2.5-0.5b-instruct-q4_k_m.gguf",
"revision": "9217f5db79a29953eb74d5343926648285ec7e67",
"sha256": "74a4da8c9fdbcd15bd1f6d01d621410d31c6fc00986f5eb687824e7b93d7a9db",
"license": "Apache-2.0",
"license_status": "DECLARED_METADATA_NOT_VERIFIED",
"license_verified": False,
"legal_clearance": False,
},
"model_download_max_bytes": 600 * 1024 * 1024,
"minimum_total_memory_bytes": 7 * 1024 * 1024 * 1024,
"minimum_free_root_bytes": 8 * 1024 * 1024 * 1024,
"transfer_limits": {
"llama_cpp_clone": {
"status": "UNKNOWN",
"bound": "UNCAPPED_BY_THIS_TOOL",
"max_bytes": None,
"bounded_by_this_tool": False,
},
"model_download": {
"max_bytes": 600 * 1024 * 1024,
"bounded_by_this_tool": True,
"is_total_transfer_bound": False,
},
"source_clone_build_package_release": {
"status": "UNCAPPED_BY_THIS_TOOL",
"max_bytes": None,
"bounded_by_this_tool": False,
},
},
}
first = first_kill.build_third_party_download_plan()
second = first_kill.build_third_party_download_plan()
self.assertEqual(expected, first)
self.assertEqual(first, second)
self.assertEqual(json.dumps(first, sort_keys=True), json.dumps(second, sort_keys=True))
def test_third_party_plan_rejects_malformed_pinned_projection_without_reflection(self) -> None:
canary = "https://unsafe.example/private-path?argv=secret"
output = io.StringIO()
errors = io.StringIO()
with (
mock.patch.object(first_kill, "MODEL_URL", canary),
contextlib.redirect_stdout(output),
contextlib.redirect_stderr(errors),
self.assertRaises(SystemExit) as raised,
):
first_kill.main(["--third-party-download-plan"])
self.assertEqual("third-party download plan unavailable: pinned inputs are invalid", str(raised.exception))
self.assertEqual("", output.getvalue())
self.assertNotIn(canary, errors.getvalue())
def test_third_party_plan_is_zero_effect_before_host_or_install_steps(self) -> None:
output = io.StringIO()
with (
mock.patch.object(first_kill, "operator_name") as operator,
mock.patch.object(first_kill, "compatibility") as compatibility,
mock.patch.object(first_kill, "repository_root") as repository_root,
mock.patch.object(first_kill, "local_release_identity") as identity,
mock.patch.object(first_kill, "prepare_workspace") as prepare_workspace,
mock.patch.object(first_kill, "release_files") as release_files,
mock.patch.object(first_kill, "download") as download,
mock.patch.object(first_kill, "run") as run,
mock.patch.object(first_kill, "install_release") as install_release,
mock.patch.object(first_kill, "run_real_smoke") as run_real_smoke,
mock.patch.object(first_kill, "remove_installation") as remove_installation,
mock.patch.object(first_kill.tempfile, "mkdtemp") as make_temporary,
mock.patch.object(first_kill.urllib.request, "urlopen") as urlopen,
mock.patch.object(first_kill, "total_memory_bytes") as memory,
mock.patch.object(first_kill, "free_root_bytes") as disk,
contextlib.redirect_stdout(output),
):
result = first_kill.main(["--third-party-download-plan"])
self.assertEqual(0, result)
payload = output.getvalue()
self.assertEqual(first_kill.build_third_party_download_plan(), json.loads(payload))
for forbidden_field in ('"path"', '"argv"', '"env"', '"platform"', '"host"'):
self.assertNotIn(forbidden_field, payload)
for forbidden in (
operator,
compatibility,
repository_root,
identity,
prepare_workspace,
release_files,
download,
run,
install_release,
run_real_smoke,
remove_installation,
make_temporary,
urlopen,
memory,
disk,
):
forbidden.assert_not_called()
def test_third_party_plan_rejects_preflight_flag_before_effects(self) -> None:
errors = io.StringIO()
with (
mock.patch.object(first_kill, "operator_name") as operator,
contextlib.redirect_stderr(errors),
self.assertRaises(SystemExit) as raised,
):
first_kill.main(["--third-party-download-plan", "--preflight-only"])
self.assertEqual(2, raised.exception.code)
self.assertIn("--third-party-download-plan cannot be combined", errors.getvalue())
operator.assert_not_called()
def test_preflight_requires_every_fixed_installer_command(self) -> None:
self.assertEqual(
EXPECTED_FIRST_KILL_COMMANDS,
frozenset(first_kill.REQUIRED_HOST_COMMANDS),
)
for missing in EXPECTED_FIRST_KILL_COMMANDS:
with self.subTest(missing=missing):
def present(path: Path, expected: str = missing) -> bool:
return path.as_posix() != expected
with (
mock.patch.object(
first_kill.Path, "is_file", autospec=True, side_effect=present
),
mock.patch.object(first_kill.os, "access", return_value=True),
self.assertRaisesRegex(
first_kill.FirstKillError, missing.replace("/", r"\/")
),
):
first_kill.require_host_commands()
def test_each_missing_command_refusal_precedes_entrypoint_side_effects(self) -> None:
for missing in EXPECTED_FIRST_KILL_COMMANDS:
with self.subTest(missing=missing):
def present(path: Path, expected: str = missing) -> bool:
return path.as_posix() != expected
with mock.patch.object(
first_kill.Path, "is_file", autospec=True, side_effect=present
):
self.assert_entrypoint_refuses_before_side_effects(
"PRE_INSTALL_FAILURE"
)
def test_preflight_rejects_residual_workload_identity(self) -> None:
passwd = mock.Mock()
group = mock.Mock()
passwd.getpwnam.return_value = object()
with (
mock.patch.object(first_kill, "pwd", passwd),
mock.patch.object(first_kill, "grp", group),
self.assertRaisesRegex(first_kill.FirstKillError, "workload account"),
):
first_kill.require_clean_workload_identity()
passwd.getpwnam.side_effect = KeyError(first_kill.WORKLOAD_USER)
group.getgrnam.return_value = object()
with (
mock.patch.object(first_kill, "pwd", passwd),
mock.patch.object(first_kill, "grp", group),
self.assertRaisesRegex(first_kill.FirstKillError, "workload group"),
):
first_kill.require_clean_workload_identity()
def test_each_residual_identity_refusal_precedes_entrypoint_side_effects(self) -> None:
for residual in ("account", "group"):
with self.subTest(residual=residual):
passwd = mock.Mock()
group = mock.Mock()
if residual == "account":
passwd.getpwnam.return_value = object()
else:
def passwd_lookup(name: str):
if name == first_kill.WORKLOAD_USER:
raise KeyError(name)
return object()
passwd.getpwnam.side_effect = passwd_lookup
group.getgrnam.return_value = object()
with (
mock.patch.object(
first_kill.Path, "is_file", autospec=True, return_value=True
),
):
self.assert_entrypoint_refuses_before_side_effects(
"PRE_INSTALL_FAILURE",
passwd,
group,
)
def test_preflight_exits_before_every_mutating_or_network_step(self) -> None:
output = io.StringIO()
with (
mock.patch.object(first_kill, "operator_name", return_value="tester") as operator,
mock.patch.object(first_kill, "compatibility") as compatibility,
mock.patch.object(first_kill, "repository_root", return_value=Path("/checkout")),
mock.patch.object(
first_kill,
"local_release_identity",
return_value=TAG_COMMIT,
),
mock.patch.object(first_kill, "prepare_workspace") as prepare_workspace,
mock.patch.object(first_kill, "release_files") as release_files,
mock.patch.object(first_kill, "verify_tag") as verify_tag,
mock.patch.object(
first_kill, "verify_checksum_signature"
) as verify_checksum_signature,
mock.patch.object(first_kill, "verify_bundle_checksum") as verify_bundle_checksum,
mock.patch.object(first_kill, "install_release") as install_release,
mock.patch.object(first_kill, "run_real_smoke") as run_real_smoke,
mock.patch.object(first_kill.tempfile, "mkdtemp") as make_temporary,
contextlib.redirect_stdout(output),
):
result = first_kill.main(["--operator", "tester", "--preflight-only"])
self.assertEqual(0, result)
operator.assert_called_once_with("tester")
compatibility.assert_called_once_with("tester")
for forbidden in (
prepare_workspace,
release_files,
verify_tag,
verify_checksum_signature,
verify_bundle_checksum,
install_release,
run_real_smoke,
make_temporary,
):
forbidden.assert_not_called()
summary = json.loads(output.getvalue())
self.assertEqual("PREFLIGHT_PASSED", summary["result"])
self.assertEqual(first_kill.PREFLIGHT_SCHEMA, summary["schema"])
self.assertTrue(summary["supported"])
self.assertEqual(TAG_COMMIT, summary["tag_commit"])
self.assertNotIn("qualified_commit", summary)
self.assertFalse(summary["changes_made"])
self.assertNotIn("/checkout", output.getvalue())
def test_preflight_incompatibilities_emit_trusted_bounded_diagnostics(self) -> None:
canary = "SECRET_PATH=/private/operator-name pid=424242 --danger"
non_default_tag = "v9.9.9"
blocked_fields = {
"changes_made",
"failed_check",
"mode",
"next_action",
"reason_code",
"result",
"schema",
"supported",
"tag",
}
cases = (
("operator_database", "operator"),
("operator_required", "operator"),
("operator_missing", "operator"),
("operator_root", "operator"),
("host_root", "compatibility"),
("host_platform", "compatibility"),
("host_wsl", "compatibility"),
("host_memory", "compatibility"),
("host_memory_limit", "compatibility"),
("host_disk", "compatibility"),
("host_disk_limit", "compatibility"),
("host_cgroup", "compatibility"),
("host_pidfd", "compatibility"),
("host_command", "compatibility"),
("build_tool", "compatibility"),
("install_target", "compatibility"),
("workload_database", "compatibility"),
("workload_residue", "compatibility"),
("local_git", "repository"),
("tag_unsupported", "identity"),
("tag_not_annotated", "identity"),
("tag_commit", "identity"),
)
self.assertEqual(first_kill.DEFAULT_TAG, first_kill._safe_preflight_tag(first_kill.DEFAULT_TAG))
self.assertEqual("<redacted>", first_kill._safe_preflight_tag(non_default_tag))
for diagnostic_key, stage in cases:
with self.subTest(diagnostic_key=diagnostic_key):
output = io.StringIO()
errors = io.StringIO()
with (
mock.patch.object(first_kill, "operator_name", return_value="tester") as operator,
mock.patch.object(first_kill, "compatibility") as compatibility,
mock.patch.object(
first_kill, "repository_root", return_value=Path("/private/repo")
) as root,
mock.patch.object(
first_kill, "local_release_identity", return_value=TAG_COMMIT
) as identity,
mock.patch.object(first_kill, "prepare_workspace") as prepare_workspace,
mock.patch.object(first_kill, "release_files") as release_files,
mock.patch.object(first_kill, "verify_tag") as verify_tag,
mock.patch.object(first_kill, "verify_checksum_signature") as signature,
mock.patch.object(first_kill, "verify_bundle_checksum") as checksum,
mock.patch.object(first_kill, "install_release") as install,
mock.patch.object(first_kill, "run_real_smoke") as smoke,
mock.patch.object(first_kill.tempfile, "mkdtemp") as make_temporary,
mock.patch.object(first_kill, "download") as download,
mock.patch.object(first_kill.urllib.request, "urlopen") as urlopen,
contextlib.redirect_stdout(output),
contextlib.redirect_stderr(errors),
):
failure = first_kill.preflight_failure(
diagnostic_key, f"refusal {diagnostic_key}: {canary}"
)
if stage == "operator":
operator.side_effect = failure
elif stage == "compatibility":
compatibility.side_effect = failure
elif stage == "repository":
root.side_effect = failure
else:
identity.side_effect = failure
result = first_kill.main(
[
"--operator",
"tester",
"--tag",
non_default_tag,
"--preflight-only",
]
)
self.assertEqual(2, result)
summary = json.loads(output.getvalue())
self.assertEqual(blocked_fields, set(summary))
self.assertEqual(first_kill.PREFLIGHT_SCHEMA, summary["schema"])
self.assertEqual("preflight-only", summary["mode"])
self.assertEqual("PREFLIGHT_BLOCKED", summary["result"])
self.assertFalse(summary["changes_made"])
self.assertFalse(summary["supported"])
self.assertEqual("<redacted>", summary["tag"])
diagnostic = first_kill.PREFLIGHT_DIAGNOSTICS[diagnostic_key]
self.assertEqual(diagnostic.failed_check, summary["failed_check"])
self.assertEqual(diagnostic.reason_code, summary["reason_code"])
self.assertEqual(diagnostic.next_action, summary["next_action"])
self.assertNotIn(canary, output.getvalue())
self.assertNotIn("private", output.getvalue().lower())
self.assertEqual("", errors.getvalue())
for forbidden in (
prepare_workspace,
release_files,
verify_tag,
signature,
checksum,
install,
smoke,
make_temporary,
download,
urlopen,
):
forbidden.assert_not_called()
if stage == "operator":
operator.assert_called_once_with("tester")
compatibility.assert_not_called()
root.assert_not_called()
identity.assert_not_called()
elif stage == "compatibility":
operator.assert_called_once_with("tester")
compatibility.assert_called_once_with("tester")
root.assert_not_called()
identity.assert_not_called()
elif stage == "repository":
operator.assert_called_once_with("tester")
compatibility.assert_called_once_with("tester")
root.assert_called_once_with()
identity.assert_not_called()
else:
operator.assert_called_once_with("tester")
compatibility.assert_called_once_with("tester")
root.assert_called_once_with()
identity.assert_called_once_with(Path("/private/repo"), non_default_tag)
def test_normal_run_still_requires_download_acceptance(self) -> None:
with (
contextlib.redirect_stderr(io.StringIO()),
self.assertRaises(SystemExit) as raised,
):
first_kill.main(["--operator", "tester"])
self.assertEqual(2, raised.exception.code)
def _run_result_mode(
self,
choice: str,
*,
receipt: dict[str, object] | None = None,
remove_failure: BaseException | None = None,
publish_failure: BaseException | None = None,
ai_preexisting: bool = False,
) -> tuple[int, mock.Mock, mock.Mock, mock.Mock, str, str]:
release = {
"artifact": "lumi-eggcracker-1.0.0.pyz",
"sha256": "a" * 64,
"source_archive": "lumi-eggcracker-1.0.0-source.zip",
"source_commit": TAG_COMMIT,
"version": "1.0.0",
}
workspace = Path("/private-workspace")
output_path = Path("/private-result.json")
published = mock.Mock(side_effect=publish_failure)
removed = mock.Mock(side_effect=remove_failure)
verified = mock.Mock()
output = io.StringIO()
errors = io.StringIO()
root_directory_patcher = mock.patch.object(first_kill, "require_root_directory")
root_directory_patcher.start()
self.addCleanup(root_directory_patcher.stop)
with tempfile.TemporaryDirectory() if ai_preexisting else contextlib.nullcontext() as ai_workspace_raw:
ai_workspace_arg = Path(ai_workspace_raw) if ai_workspace_raw is not None else None
argv = [
"--operator",
"tester",
"--workspace",
str(workspace),
"--accept-third-party-downloads",
"--result-output",
str(output_path),
choice,
]
if ai_workspace_arg is not None:
argv.extend(["--ai-workspace", str(ai_workspace_arg)])
with contextlib.ExitStack() as stack:
stack.enter_context(mock.patch.object(first_kill, "operator_name", return_value="tester"))
stack.enter_context(mock.patch.object(first_kill, "compatibility"))
stack.enter_context(
mock.patch.object(first_kill, "repository_root", return_value=Path("/checkout"))
)
stack.enter_context(mock.patch.object(first_kill, "prepare_workspace", return_value=workspace))
stack.enter_context(
mock.patch.object(
first_kill,
"release_files",
return_value=(Path("/bundle.zip"), Path("/key.asc"), Path("/SHA256SUMS"), Path("/SHA256SUMS.asc")),
)
)
stack.enter_context(mock.patch.object(first_kill, "verify_tag", return_value=TAG_COMMIT))
stack.enter_context(mock.patch.object(first_kill, "verify_checksum_signature"))
stack.enter_context(mock.patch.object(first_kill, "verify_bundle_checksum"))
stack.enter_context(
mock.patch.object(first_kill, "extracted_release", return_value=Path("/release"))
)
stack.enter_context(mock.patch.object(first_kill, "manifest", return_value=release))
stack.enter_context(mock.patch.object(first_kill, "run"))
stack.enter_context(mock.patch.object(first_kill, "install_release"))
stack.enter_context(
mock.patch.object(first_kill, "installed_workload_user", return_value="workload")
)
stack.enter_context(
mock.patch.object(first_kill, "run_real_smoke", return_value=receipt or success_receipt())
)
stack.enter_context(mock.patch.object(first_kill, "remove_installation", removed))
stack.enter_context(mock.patch.object(first_kill, "verify_removed_targets", verified))
stack.enter_context(
mock.patch.object(first_kill, "validate_result_output", return_value=output_path)
)
stack.enter_context(mock.patch.object(first_kill, "publish_success_result", published))
stack.enter_context(contextlib.redirect_stdout(output))
stack.enter_context(contextlib.redirect_stderr(errors))
result = first_kill.main(argv)
return result, published, verified, removed, output.getvalue(), errors.getvalue()
def test_result_output_requires_one_explicit_cleanup_choice(self) -> None:
output = Path("/private-result.json")
with (
mock.patch.object(first_kill, "validate_result_output") as validate,
contextlib.redirect_stderr(io.StringIO()),
self.assertRaises(SystemExit) as raised,
):
first_kill.main(
["--accept-third-party-downloads", "--result-output", str(output)]
)
self.assertEqual(2, raised.exception.code)
validate.assert_not_called()
def test_result_destination_is_validated_before_download_or_install(self) -> None:
release_files = mock.Mock()
with (
mock.patch.object(
first_kill,
"validate_result_output",
side_effect=first_kill.FirstKillError("PRIVATE destination"),
),
mock.patch.object(first_kill, "release_files", release_files),
contextlib.redirect_stderr(io.StringIO()),
self.assertRaises(SystemExit) as raised,
):
first_kill.main(
[
"--accept-third-party-downloads",
"--keep",
"--result-output",
"/private-result.json",
]
)
self.assertEqual(2, raised.exception.code)
release_files.assert_not_called()
def test_result_output_rejects_plan_and_preflight_before_effects(self) -> None:
for flags in (
["--third-party-download-plan", "--result-output", "/private-result.json", "--keep"],
["--preflight-only", "--result-output", "/private-result.json", "--keep"],
):
with self.subTest(flags=flags), contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
first_kill.main(flags)
def test_result_output_keep_publishes_fixed_projection_without_sensitive_fields(self) -> None:
result, published, verified, removed, output, errors = self._run_result_mode("--keep")
self.assertEqual(0, result)
document = published.call_args.args[1]
self.assertEqual(first_kill.SUCCESS_RESULT_FIELDS, set(document))
self.assertEqual(first_kill.SUCCESS_DISPOSITION_RETAINED, document["disposition"])
self.assertEqual(first_kill.SUCCESS_AI_ASSETS_NEW_RETAINED, document["ai_assets_disposition"])
self.assertEqual(first_kill.SUCCESS_RUN_SCOPE, document["run_scope"])
self.assertFalse(document["authenticated"])
self.assertFalse(document["independent_containment_proof"])
self.assertEqual(first_kill.SUCCESS_SOURCE_COMMIT_ROLE, document["source_commit_role"])
self.assertEqual(TAG_COMMIT, document["source_commit"])
self.assertNotIn("PRIVATE", json.dumps(document))
self.assertNotIn("424242", output + errors)
removed.assert_not_called()
verified.assert_not_called()
def test_result_output_remove_requires_read_only_absence_verification(self) -> None:
result, published, verified, removed, _output, errors = self._run_result_mode("--remove")
self.assertEqual(0, result)
self.assertEqual(first_kill.SUCCESS_DISPOSITION_REMOVED, published.call_args.args[1]["disposition"])
self.assertEqual(first_kill.SUCCESS_AI_ASSETS_NEW_REMOVED, published.call_args.args[1]["ai_assets_disposition"])
removed.assert_called_once()
verified.assert_called_once_with(
Path("/private-workspace"),
first_kill.DEFAULT_AI_SMOKE_WORKSPACE.absolute(),
assets_preexisting=False,
)
self.assertEqual("", errors)
def test_result_output_remove_excludes_preexisting_ai_assets_from_claim(self) -> None:
result, published, verified, removed, _output, errors = self._run_result_mode(
"--remove", ai_preexisting=True
)
self.assertEqual(0, result)
document = published.call_args.args[1]
self.assertEqual(first_kill.SUCCESS_DISPOSITION_REMOVED, document["disposition"])
self.assertEqual(
first_kill.SUCCESS_AI_ASSETS_PREEXISTING_EXCLUDED,
document["ai_assets_disposition"],
)
removed.assert_called_once_with(Path("/release"), Path("/private-workspace"), None)
verified.assert_called_once_with(
Path("/private-workspace"), None, assets_preexisting=True
)
self.assertEqual("", errors)
def test_result_output_malformed_receipt_and_removal_failure_publish_nothing(self) -> None:
malformed = success_receipt()
malformed["containment"] = {"root_populated": 0, "surviving_pids": []}
result, published, verified, removed, _output, errors = self._run_result_mode(
"--remove", receipt=malformed
)
self.assertEqual(2, result)
published.assert_not_called()
removed.assert_not_called()
verified.assert_not_called()
self.assertNotIn("PRIVATE", errors)
failed_canary = success_receipt(canary_survived=False)
result, published, verified, removed, _output, errors = self._run_result_mode(
"--keep", receipt=failed_canary
)
self.assertEqual(2, result)
published.assert_not_called()
removed.assert_not_called()
verified.assert_not_called()
self.assertNotIn("PRIVATE", errors)
result, published, verified, removed, _output, errors = self._run_result_mode(
"--remove", remove_failure=first_kill.FirstKillError("PRIVATE removal failure")
)
self.assertEqual(2, result)
published.assert_not_called()
verified.assert_not_called()
self.assertNotIn("PRIVATE", errors)
def test_result_publication_parent_identity_race_fails_closed(self) -> None:
info = SimpleNamespace(
st_mode=stat.S_IFDIR | 0o700,
st_uid=0,
st_dev=1,
st_ino=2,
st_file_attributes=0,
)
replacement = SimpleNamespace(
st_mode=stat.S_IFDIR | 0o700,
st_uid=0,
st_dev=1,
st_ino=3,
st_file_attributes=0,
)
with mock.patch.object(first_kill, "_result_output_effective_uid", return_value=0):
with mock.patch.object(first_kill.os, "lstat", return_value=info):
self.assertTrue(first_kill._result_output_parent_path_matches(Path("/safe"), (1, 2)))
with mock.patch.object(first_kill.os, "lstat", return_value=replacement):
self.assertFalse(first_kill._result_output_parent_path_matches(Path("/safe"), (1, 2)))
def test_result_publication_posix_calls_complete_and_cleans_exact_temp(self) -> None:
with publication_mocks() as calls:
first_kill.publish_success_result(calls["destination"], {"result": "ok"})
self.assertEqual(1, calls["write"].call_count)
calls["link"].assert_called_once_with(
calls["temporary_name"][0],
calls["destination"].name,
src_dir_fd=101,
dst_dir_fd=101,
follow_symlinks=False,
)
calls["unlink"].assert_called_once_with(calls["temporary_name"][0], dir_fd=101)
self.assertEqual(2, calls["open"].call_count)
def test_result_publication_posix_calls_partial_write_loop(self) -> None:
first_write = True
def partial_write(_fd, view):
nonlocal first_write
if first_write:
first_write = False
return 1
return len(view)
with publication_mocks(write_side_effect=partial_write) as calls:
first_kill.publish_success_result(calls["destination"], {"result": "partial"})
self.assertEqual(2, calls["write"].call_count)
calls["unlink"].assert_called_once_with(calls["temporary_name"][0], dir_fd=101)
def test_result_publication_posix_calls_write_failure_is_safe(self) -> None:
with (
publication_mocks(write_side_effect=OSError("private write failure")) as calls,
self.assertRaisesRegex(first_kill.FirstKillError, first_kill.RESULT_OUTPUT_FAILURE),
):
first_kill.publish_success_result(calls["destination"], {"result": "write-failure"})
calls["link"].assert_not_called()
calls["unlink"].assert_called_once_with(calls["temporary_name"][0], dir_fd=101)
def test_result_publication_posix_calls_existing_or_raced_destination_never_overwrites(self) -> None:
with (
publication_mocks(destination_exists=True) as existing,
self.assertRaisesRegex(first_kill.FirstKillError, first_kill.RESULT_OUTPUT_FAILURE),
):
first_kill.publish_success_result(existing["destination"], {"result": "existing"})
existing["link"].assert_not_called()
existing["unlink"].assert_called_once_with(existing["temporary_name"][0], dir_fd=101)
with (
publication_mocks(link_race=True) as raced,
self.assertRaisesRegex(first_kill.FirstKillError, first_kill.RESULT_OUTPUT_FAILURE),
):
first_kill.publish_success_result(raced["destination"], {"result": "raced"})
raced["link"].assert_called_once()
raced["unlink"].assert_called_once_with(raced["temporary_name"][0], dir_fd=101)
def test_result_publication_posix_calls_parent_identity_race_before_link(self) -> None:
with (
publication_mocks(parent_race=True) as calls,
self.assertRaisesRegex(first_kill.FirstKillError, first_kill.RESULT_OUTPUT_FAILURE),
):
first_kill.publish_success_result(calls["destination"], {"result": "parent-race"})
calls["link"].assert_not_called()
calls["unlink"].assert_not_called()
def test_result_publication_post_link_failure_removes_only_our_destination(self) -> None:
with (
publication_mocks(
fsync_side_effect=[None, OSError("private parent fsync"), None]
) as calls,
self.assertRaisesRegex(first_kill.FirstKillError, first_kill.RESULT_OUTPUT_FAILURE),
):
first_kill.publish_success_result(calls["destination"], {"result": "post-link"})
self.assertEqual(
[
mock.call(calls["temporary_name"][0], dir_fd=101),
mock.call(calls["destination"].name, dir_fd=101),
],
calls["unlink"].call_args_list,
)
self.assertTrue(any(name == calls["destination"].name for name, _fd in calls["stat_calls"]))
def test_result_publication_cleanup_never_unlinks_foreign_temp(self) -> None:
foreign = SimpleNamespace(
st_mode=stat.S_IFREG | 0o600,
st_uid=0,
st_dev=11,
st_ino=99,
st_file_attributes=0,
)
with (
mock.patch.object(first_kill, "_result_output_effective_uid", return_value=0),
mock.patch.object(first_kill, "_result_output_parent_matches", return_value=True),
mock.patch.object(first_kill, "_result_output_parent_path_matches", return_value=True),
mock.patch.object(first_kill.os, "stat", return_value=foreign),
mock.patch.object(first_kill.os, "unlink") as unlink,
):
first_kill._result_output_unlink_owned(
101,
".result.tmp",
(11, 33),
(11, 22),
Path("/synthetic-result"),
)
unlink.assert_not_called()
def test_result_output_publication_failure_reports_known_kept_state(self) -> None:
result, published, verified, removed, _output, errors = self._run_result_mode(
"--keep", publish_failure=first_kill.FirstKillError("PRIVATE write failure")
)
self.assertEqual(2, result)
published.assert_called_once()
removed.assert_not_called()
verified.assert_not_called()
summary = json.loads(errors)
self.assertEqual(first_kill.FULL_RUN_INSTALL_STATE_INSTALLED, summary["installation_state"])
self.assertEqual(first_kill.FULL_RUN_STAGE_RESULT_PUBLICATION, summary["stage"])
self.assertEqual("RESULT_PUBLICATION_FAILURE", summary["reason_code"])
self.assertEqual(first_kill.FULL_RUN_REMOVAL_MANUAL_REVIEW_REQUIRED, summary["removal_guidance"])
self.assertNotIn("PRIVATE", errors)
def test_result_output_publication_failure_reports_verified_removed_state(self) -> None:
result, published, verified, removed, _output, errors = self._run_result_mode(
"--remove", publish_failure=first_kill.FirstKillError("PRIVATE write failure")
)
self.assertEqual(2, result)
published.assert_called_once()
removed.assert_called_once()
verified.assert_called_once()
summary = json.loads(errors)
self.assertEqual(first_kill.FULL_RUN_INSTALL_STATE_NOT_INSTALLED, summary["installation_state"])
self.assertEqual(first_kill.FULL_RUN_STAGE_RESULT_PUBLICATION, summary["stage"])
self.assertEqual("RESULT_PUBLICATION_FAILURE", summary["reason_code"])
self.assertEqual(first_kill.FULL_RUN_REMOVAL_NOT_REQUIRED, summary["removal_guidance"])
self.assertNotIn("PRIVATE", errors)
def test_result_destination_rejects_relative_existing_nonregular_and_symlink(self) -> None:
with tempfile.TemporaryDirectory() as raw:
root = Path(raw)
root.chmod(0o700)
existing = root / "existing.json"
existing.write_text("preserve", encoding="utf-8")
directory = root / "directory.json"
directory.mkdir()
with mock.patch.object(first_kill, "_result_output_effective_uid", return_value=0):
with self.assertRaises(first_kill.FirstKillError):
first_kill.validate_result_output(Path("relative-result.json"))
with self.assertRaises(first_kill.FirstKillError):
first_kill.validate_result_output(existing)
with self.assertRaises(first_kill.FirstKillError):
first_kill.validate_result_output(directory)
try:
link = root / "link.json"
os.symlink(existing, link)
except (NotImplementedError, OSError):
link = None
if link is not None:
with self.assertRaises(first_kill.FirstKillError):
first_kill.validate_result_output(link)
self.assertEqual("preserve", existing.read_text(encoding="utf-8"))
def test_result_removal_verification_rejects_residue_dangling_link_and_keeps_unrelated(self) -> None:
with tempfile.TemporaryDirectory() as raw:
root = Path(raw)
workspace = root / "workspace"
assets = root / "assets"
workspace.mkdir()
assets.mkdir()
unrelated = root / "unrelated.txt"
unrelated.write_text("preserve", encoding="utf-8")
original_targets = first_kill.INSTALL_TARGETS
first_kill.INSTALL_TARGETS = (root / "managed",)
try:
with self.assertRaises(first_kill.FirstKillError):
first_kill.verify_removed_targets(workspace, assets, assets_preexisting=False)
workspace.rmdir()
assets.rmdir()
first_kill.verify_removed_targets(workspace, assets, assets_preexisting=False)
self.assertEqual("preserve", unrelated.read_text(encoding="utf-8"))
dangling = root / "managed"
try:
os.symlink(root / "gone", dangling, target_is_directory=True)
except (NotImplementedError, OSError):
pass
else:
with self.assertRaises(first_kill.FirstKillError):
first_kill.verify_removed_targets(workspace, assets, assets_preexisting=False)
finally:
first_kill.INSTALL_TARGETS = original_targets
def test_normal_run_authenticates_checksums_before_extraction_or_install(self) -> None:
events: list[str] = []
release = {
"artifact": "lumi-eggcracker-1.0.0.pyz",
"sha256": "a" * 64,
"source_archive": "lumi-eggcracker-1.0.0-source.zip",
"source_commit": TAG_COMMIT,
"version": "1.0.0",
}
receipt = {
"result": "TERMINATED",
"containment": {"surviving_pids": [], "root_populated": 0},
}
with (
mock.patch.object(first_kill, "operator_name", return_value="tester"),
mock.patch.object(first_kill, "compatibility"),
mock.patch.object(first_kill, "repository_root", return_value=Path("/checkout")),
mock.patch.object(
first_kill, "prepare_workspace", return_value=Path("/private-workspace")
),
mock.patch.object(
first_kill,
"release_files",
return_value=(
Path("/bundle.zip"),
Path("/key.asc"),
Path("/SHA256SUMS"),
Path("/SHA256SUMS.asc"),
),
),
mock.patch.object(first_kill, "verify_tag", return_value=TAG_COMMIT),
mock.patch.object(
first_kill,
"verify_checksum_signature",
side_effect=lambda *_: events.append("signature"),
),
mock.patch.object(
first_kill,
"verify_bundle_checksum",
side_effect=lambda *_: events.append("checksum"),
),
mock.patch.object(
first_kill,
"extracted_release",
side_effect=lambda *_: events.append("extract") or Path("/release"),
),
mock.patch.object(first_kill, "manifest", return_value=release),
mock.patch.object(first_kill, "run"),
mock.patch.object(
first_kill,
"install_release",
side_effect=lambda *_: events.append("install"),
),
mock.patch.object(
first_kill, "installed_workload_user", return_value="workload"
),
mock.patch.object(
first_kill, "run_real_smoke", return_value=receipt
) as run_real_smoke,
mock.patch.object(first_kill, "remove_installation"),
contextlib.redirect_stdout(io.StringIO()),
):
result = first_kill.main(
[
"--operator",
"tester",
"--workspace",
"/private-workspace",
"--accept-third-party-downloads",
"--remove",
]
)
self.assertEqual(0, result)
self.assertEqual(["signature", "checksum", "extract", "install"], events)
smoke_args = run_real_smoke.call_args.args
self.assertEqual(Path("/checkout"), smoke_args[0])
self.assertNotEqual(Path("/release"), smoke_args[0])
self.assertEqual(
(
Path("/private-workspace"),
"workload",
first_kill.DEFAULT_AI_SMOKE_WORKSPACE.absolute(),
0,
),
smoke_args[1:],
)
def test_full_run_pre_install_failure_is_bounded_and_redacted(self) -> None:
canary = "SECRET_PATH=/private/pre-install --argv=hidden ENV_SECRET=hidden"
output = io.StringIO()
errors = io.StringIO()
with (
mock.patch.object(
first_kill,
"operator_name",
side_effect=first_kill.FirstKillError(canary),
),
contextlib.redirect_stdout(output),
contextlib.redirect_stderr(errors),
):
result = first_kill.main(
["--operator", "tester", "--accept-third-party-downloads"]
)
self.assertEqual(2, result)
summary = json.loads(errors.getvalue())
self.assertEqual(first_kill.FULL_RUN_FAILURE_FIELDS, set(summary))
self.assertEqual(first_kill.FULL_RUN_FAILURE_SCHEMA, summary["schema"])
self.assertEqual(first_kill.FULL_RUN_FAILURE_VERSION, summary["version"])
self.assertEqual("FULL_RUN_FAILED", summary["result"])
self.assertEqual(first_kill.FULL_RUN_STAGE_PRE_INSTALL, summary["stage"])
self.assertEqual("PRE_INSTALL_FAILURE", summary["reason_code"])
self.assertEqual(
first_kill.FULL_RUN_INSTALL_STATE_NOT_INSTALLED,
summary["installation_state"],
)
self.assertEqual(first_kill.FULL_RUN_REMOVAL_NOT_REQUIRED, summary["removal_guidance"])
self.assertEqual(first_kill.FULL_RUN_NEXT_ACTION, summary["next_action"])
self.assertNotIn(canary, output.getvalue() + errors.getvalue())
def test_full_run_install_failure_reports_partial_install_without_leaks(self) -> None:
canary = "SECRET_PATH=/private/install --argv=hidden ENV_SECRET=hidden"
output = io.StringIO()
errors = io.StringIO()
with (
mock.patch.object(first_kill, "operator_name", return_value="tester"),
mock.patch.object(first_kill, "compatibility"),
mock.patch.object(first_kill, "repository_root", return_value=Path("/checkout")),
mock.patch.object(
first_kill, "prepare_workspace", return_value=Path("/private-workspace")
),
mock.patch.object(
first_kill,
"release_files",
return_value=(
Path("/bundle.zip"),
Path("/key.asc"),
Path("/SHA256SUMS"),
Path("/SHA256SUMS.asc"),
),
),
mock.patch.object(first_kill, "verify_tag", return_value=TAG_COMMIT),
mock.patch.object(first_kill, "verify_checksum_signature"),
mock.patch.object(first_kill, "verify_bundle_checksum"),
mock.patch.object(first_kill, "extracted_release", return_value=Path("/release")),
mock.patch.object(
first_kill,
"manifest",
return_value={
"artifact": "lumi-eggcracker-1.0.0.pyz",
"sha256": "a" * 64,
"source_archive": "lumi-eggcracker-1.0.0-source.zip",
"source_commit": TAG_COMMIT,
"version": "1.0.0",
},
),
mock.patch.object(first_kill, "run"),
mock.patch.object(
first_kill,
"install_release",
side_effect=first_kill.FirstKillError(canary),
),
contextlib.redirect_stdout(output),
contextlib.redirect_stderr(errors),
):
result = first_kill.main(
["--operator", "tester", "--accept-third-party-downloads"]
)
self.assertEqual(2, result)
summary = json.loads(errors.getvalue())
self.assertEqual(first_kill.FULL_RUN_FAILURE_FIELDS, set(summary))
self.assertEqual(first_kill.FULL_RUN_STAGE_INSTALL, summary["stage"])
self.assertEqual("INSTALL_FAILURE", summary["reason_code"])
self.assertEqual(
first_kill.FULL_RUN_INSTALL_STATE_UNKNOWN_OR_PARTIAL,
summary["installation_state"],
)
self.assertEqual(
first_kill.FULL_RUN_REMOVAL_MANUAL_REVIEW_REQUIRED,
summary["removal_guidance"],
)
self.assertEqual(first_kill.FULL_RUN_NEXT_ACTION, summary["next_action"])
self.assertNotIn(canary, output.getvalue() + errors.getvalue())
def test_full_run_post_install_failure_reports_installed_and_redacts(self) -> None:
canary = "SECRET_PATH=/private/post-install --argv=hidden ENV_SECRET=hidden"
output = io.StringIO()
errors = io.StringIO()
release = {
"artifact": "lumi-eggcracker-1.0.0.pyz",
"sha256": "a" * 64,
"source_archive": "lumi-eggcracker-1.0.0-source.zip",
"source_commit": TAG_COMMIT,
"version": "1.0.0",
}
with (
mock.patch.object(first_kill, "operator_name", return_value="tester"),
mock.patch.object(first_kill, "compatibility"),
mock.patch.object(first_kill, "repository_root", return_value=Path("/checkout")),
mock.patch.object(
first_kill, "prepare_workspace", return_value=Path("/private-workspace")
),
mock.patch.object(
first_kill,
"release_files",
return_value=(
Path("/bundle.zip"),
Path("/key.asc"),
Path("/SHA256SUMS"),
Path("/SHA256SUMS.asc"),
),
),
mock.patch.object(first_kill, "verify_tag", return_value=TAG_COMMIT),
mock.patch.object(first_kill, "verify_checksum_signature"),
mock.patch.object(first_kill, "verify_bundle_checksum"),
mock.patch.object(first_kill, "extracted_release", return_value=Path("/release")),
mock.patch.object(first_kill, "manifest", return_value=release),
mock.patch.object(first_kill, "run"),
mock.patch.object(first_kill, "install_release"),
mock.patch.object(first_kill, "installed_workload_user", return_value="workload"),
mock.patch.object(
first_kill,
"run_real_smoke",
side_effect=first_kill.FirstKillError(canary),
),
contextlib.redirect_stdout(output),
contextlib.redirect_stderr(errors),
):
result = first_kill.main(
["--operator", "tester", "--accept-third-party-downloads"]
)
self.assertEqual(2, result)
summary = json.loads(errors.getvalue())
self.assertEqual(first_kill.FULL_RUN_FAILURE_FIELDS, set(summary))
self.assertEqual(first_kill.FULL_RUN_STAGE_POST_INSTALL, summary["stage"])
self.assertEqual("POST_INSTALL_FAILURE", summary["reason_code"])
self.assertEqual(first_kill.FULL_RUN_INSTALL_STATE_INSTALLED, summary["installation_state"])
self.assertEqual(
first_kill.FULL_RUN_REMOVAL_MANUAL_REVIEW_REQUIRED,
summary["removal_guidance"],
)
self.assertEqual(first_kill.FULL_RUN_NEXT_ACTION, summary["next_action"])
self.assertNotIn(canary, output.getvalue() + errors.getvalue())
self.assertNotIn("--remove", output.getvalue() + errors.getvalue())
def test_full_run_removal_failure_reports_unknown_state_and_redacts(self) -> None:
canary = "SECRET_PATH=/private/removal --argv=hidden ENV_SECRET=hidden"
output = io.StringIO()
errors = io.StringIO()
release = {
"artifact": "lumi-eggcracker-1.0.0.pyz",
"sha256": "a" * 64,
"source_archive": "lumi-eggcracker-1.0.0-source.zip",
"source_commit": TAG_COMMIT,
"version": "1.0.0",
}
receipt = {
"result": "TERMINATED",
"containment": {"surviving_pids": [], "root_populated": 0},
}
with (
mock.patch.object(first_kill, "operator_name", return_value="tester"),
mock.patch.object(first_kill, "compatibility"),
mock.patch.object(first_kill, "repository_root", return_value=Path("/checkout")),
mock.patch.object(
first_kill, "prepare_workspace", return_value=Path("/private-workspace")
),
mock.patch.object(
first_kill,
"release_files",
return_value=(
Path("/bundle.zip"),
Path("/key.asc"),
Path("/SHA256SUMS"),
Path("/SHA256SUMS.asc"),
),
),
mock.patch.object(first_kill, "verify_tag", return_value=TAG_COMMIT),
mock.patch.object(first_kill, "verify_checksum_signature"),
mock.patch.object(first_kill, "verify_bundle_checksum"),
mock.patch.object(first_kill, "extracted_release", return_value=Path("/release")),
mock.patch.object(first_kill, "manifest", return_value=release),
mock.patch.object(first_kill, "run"),
mock.patch.object(first_kill, "install_release"),
mock.patch.object(first_kill, "installed_workload_user", return_value="workload"),
mock.patch.object(first_kill, "run_real_smoke", return_value=receipt),
mock.patch.object(
first_kill,
"remove_installation",
side_effect=first_kill.FirstKillError(canary),
),
contextlib.redirect_stdout(output),
contextlib.redirect_stderr(errors),
):
result = first_kill.main(
[
"--operator",
"tester",
"--accept-third-party-downloads",
"--remove",
]
)
self.assertEqual(2, result)
summary = json.loads(errors.getvalue())
self.assertEqual(first_kill.FULL_RUN_FAILURE_FIELDS, set(summary))
self.assertEqual(first_kill.FULL_RUN_STAGE_REMOVAL, summary["stage"])
self.assertEqual("REMOVAL_FAILURE", summary["reason_code"])
self.assertEqual(
first_kill.FULL_RUN_INSTALL_STATE_UNKNOWN_OR_PARTIAL,
summary["installation_state"],
)
self.assertEqual(
first_kill.FULL_RUN_REMOVAL_MANUAL_REVIEW_REQUIRED,
summary["removal_guidance"],
)
self.assertEqual(first_kill.FULL_RUN_NEXT_ACTION, summary["next_action"])
self.assertNotIn(canary, output.getvalue() + errors.getvalue())
self.assertNotIn("--remove", output.getvalue() + errors.getvalue())
def test_real_smoke_uses_current_campaign_preparer(self) -> None:
campaign_root = Path("/campaign-checkout")
expected = campaign_root / "scripts" / "prepare_ai_smoke.py"
stop = first_kill.FirstKillError("stop after selecting preparer")
with (
mock.patch.object(first_kill, "require_regular") as require_regular,
mock.patch.object(first_kill, "run", side_effect=stop) as run,
self.assertRaisesRegex(first_kill.FirstKillError, "stop after selecting preparer"),
):
first_kill.run_real_smoke(
campaign_root,
Path("/workspace"),
"workload",
Path("/assets"),
)
require_regular.assert_called_once_with(expected, "AI smoke preparer")
self.assertEqual(str(expected), run.call_args.args[0][3])
self.assertNotIn("release", str(run.call_args.args[0][3]))
def test_preflight_rejects_mutation_only_flags(self) -> None:
with (
contextlib.redirect_stderr(io.StringIO()),
self.assertRaises(SystemExit) as raised,
):
first_kill.main(["--preflight-only", "--keep"])
self.assertEqual(2, raised.exception.code)
def test_preflight_error_redacts_sudo_user_identity(self) -> None:
canary = "operator-identity-must-not-appear"
output = io.StringIO()
errors = io.StringIO()
passwd = mock.Mock()
passwd.getpwnam.side_effect = KeyError(canary)
with (
mock.patch.object(first_kill, "pwd", passwd),
mock.patch.dict(os.environ, {"SUDO_USER": canary}),
contextlib.redirect_stdout(output),
contextlib.redirect_stderr(errors),
):
result = first_kill.main(["--preflight-only"])
self.assertEqual(2, result)
summary = json.loads(output.getvalue())
self.assertEqual("PREFLIGHT_BLOCKED", summary["result"])
self.assertEqual("OPERATOR_ACCOUNT_MISSING", summary["reason_code"])
self.assertNotIn(canary, errors.getvalue())
self.assertNotIn(canary, output.getvalue())
self.assertNotIn("operator account does not exist", output.getvalue())
def test_local_release_identity_requires_annotated_tag(self) -> None:
annotated = mock.Mock(returncode=0, stdout="tag\n")
resolved = mock.Mock(returncode=0, stdout=f"{TAG_COMMIT}\n")
with mock.patch.object(first_kill, "run", side_effect=[annotated, resolved]):
result = first_kill.local_release_identity(Path("/checkout"), first_kill.DEFAULT_TAG)
self.assertEqual(TAG_COMMIT, result)
def test_local_release_identity_rejects_non_commit_output(self) -> None:
annotated = mock.Mock(returncode=0, stdout="tag\n")
malformed = mock.Mock(returncode=0, stdout="not-a-commit\n")
with (
mock.patch.object(first_kill, "run", side_effect=[annotated, malformed]),
self.assertRaisesRegex(first_kill.FirstKillError, "does not resolve"),
):
first_kill.local_release_identity(Path("/checkout"), first_kill.DEFAULT_TAG)
def test_local_release_identity_rejects_lightweight_tag(self) -> None:
lightweight = mock.Mock(returncode=0, stdout="commit\n")
resolved = mock.Mock(returncode=0, stdout=f"{TAG_COMMIT}\n")
with (
mock.patch.object(first_kill, "run", side_effect=[lightweight, resolved]),
self.assertRaisesRegex(first_kill.FirstKillError, "not an annotated tag"),
):
first_kill.local_release_identity(Path("/checkout"), first_kill.DEFAULT_TAG)
def test_receipt_summary_is_bounded_and_redacts_paths(self) -> None:
value = first_kill.receipt_summary(
{
"result": "TERMINATED",
"detector": {"profile": "content.gguf-llama", "trigger": "UNAPPROVED"},
"trigger": {"kind": "UNAPPROVED_AI_MATCH"},
"capture": {"captured_processes": 2},
"containment": {
"primitive": "pidfd-stop+cgroup.kill",
"root_populated": 0,
"surviving_pids": [],
"trigger_to_empty_ms": 42.5,
"local_path": "/tmp/private-model.gguf",
},
}
)
self.assertEqual("TERMINATED", value["result"])
self.assertEqual("content.gguf-llama", value["profile"])
self.assertEqual("UNAPPROVED_AI_MATCH", value["trigger"])
self.assertEqual(2, value["captured_processes"])
self.assertEqual(0, value["root_populated"])
self.assertEqual(42.5, value["trigger_to_empty_ms"])
self.assertNotIn("local_path", value)
self.assertNotIn("private-model", str(value))
def test_checksums_parse_only_sha256_lines(self) -> None:
with tempfile.TemporaryDirectory() as raw:
path = Path(raw) / "SHA256SUMS"
path.write_text("a" * 64 + " payload.zip\n", encoding="ascii")
self.assertEqual({"payload.zip": "a" * 64}, first_kill.parse_checksums(path))
def test_checksums_reject_non_hex_and_duplicate_names(self) -> None:
with tempfile.TemporaryDirectory() as raw:
path = Path(raw) / "SHA256SUMS"
path.write_text("z" * 64 + " payload.zip\n", encoding="ascii")
with self.assertRaisesRegex(first_kill.FirstKillError, "invalid line"):
first_kill.parse_checksums(path)
path.write_text(
"a" * 64 + " payload.zip\n" + "b" * 64 + " payload.zip\n",
encoding="ascii",
)
with self.assertRaisesRegex(first_kill.FirstKillError, "duplicate"):
first_kill.parse_checksums(path)
def test_safe_extract_rejects_path_traversal(self) -> None:
with tempfile.TemporaryDirectory() as raw:
root = Path(raw)
archive = root / "bad.zip"
with zipfile.ZipFile(archive, "w") as bundle:
bundle.writestr("../outside.txt", "no")
with self.assertRaisesRegex(first_kill.FirstKillError, "unsafe path"):
first_kill.safe_extract(archive, root / "out")
def test_safe_extract_rejects_noncanonical_components(self) -> None:
for member_name in ("release/./install.py", "release//install.py"):
with self.subTest(member_name=member_name), tempfile.TemporaryDirectory() as raw:
root = Path(raw)
archive = root / "noncanonical.zip"
with zipfile.ZipFile(archive, "w") as bundle:
bundle.writestr(member_name, "untrusted")
with self.assertRaisesRegex(first_kill.FirstKillError, "unsafe path"):
first_kill.safe_extract(archive, root / "out")
def test_safe_extract_rejects_duplicate_paths(self) -> None:
with tempfile.TemporaryDirectory() as raw:
root = Path(raw)
archive = root / "duplicate.zip"
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
with zipfile.ZipFile(archive, "w") as bundle:
bundle.writestr("release/install.py", "trusted")
bundle.writestr("release/install.py", "hostile")
with self.assertRaisesRegex(first_kill.FirstKillError, "duplicate path"):
first_kill.safe_extract(archive, root / "out")
def test_safe_extract_rejects_symlink_members(self) -> None:
with tempfile.TemporaryDirectory() as raw:
root = Path(raw)
archive = root / "link.zip"
member = zipfile.ZipInfo("release/install.py")
member.create_system = 3
member.external_attr = (stat.S_IFLNK | 0o777) << 16
with zipfile.ZipFile(archive, "w") as bundle:
bundle.writestr(member, "../../outside")
with self.assertRaisesRegex(first_kill.FirstKillError, "link or special"):
first_kill.safe_extract(archive, root / "out")
def test_safe_extract_rejects_trailing_data(self) -> None:
with tempfile.TemporaryDirectory() as raw:
root = Path(raw)
archive = root / "appended.zip"
with zipfile.ZipFile(archive, "w") as bundle:
bundle.writestr("release/install.py", "trusted")
with archive.open("ab") as handle:
handle.write(b"DAYBREAK-TRAILING-DATA")
with self.assertRaisesRegex(first_kill.FirstKillError, "trailing data"):
first_kill.safe_extract(archive, root / "out")
def test_safe_extract_rejects_prepended_data(self) -> None:
with tempfile.TemporaryDirectory() as raw:
root = Path(raw)
original = root / "original.zip"
archive = root / "prepended.zip"
with zipfile.ZipFile(original, "w") as bundle:
bundle.writestr("release/install.py", "trusted")
archive.write_bytes(b"DAYBREAK-PREFIX" + original.read_bytes())
with self.assertRaisesRegex(first_kill.FirstKillError, "prepended"):
first_kill.safe_extract(archive, root / "out")
def test_checksum_signature_requires_valid_pinned_key_signature(self) -> None:
imported = mock.Mock(returncode=0, stdout="", stderr="")
shown = mock.Mock(
returncode=0,
stdout=(
"pub:::::::::\n"
f"fpr:::::::::{first_kill.RELEASE_KEY_FINGERPRINT}:\n"
),
stderr="",
)
verified = mock.Mock(
returncode=0,
stdout=(
"[GNUPG:] VALIDSIG "
f"{first_kill.RELEASE_KEY_FINGERPRINT} 2026 0 0 4 0 1 10 00 "
f"{first_kill.RELEASE_KEY_FINGERPRINT}\n"
),
stderr="",
)
with mock.patch.object(first_kill, "run", side_effect=[imported, shown, verified]) as run:
first_kill.verify_checksum_signature(
Path("/release-key.asc"),
Path("/SHA256SUMS"),
Path("/SHA256SUMS.asc"),
)
self.assertIn("--verify", run.call_args_list[-1].args[0])
def test_checksum_signature_failure_is_fatal(self) -> None:
imported = mock.Mock(returncode=0, stdout="", stderr="")
shown = mock.Mock(
returncode=0,
stdout=(
"pub:::::::::\n"
f"fpr:::::::::{first_kill.RELEASE_KEY_FINGERPRINT}:\n"
),
stderr="",
)
rejected = mock.Mock(returncode=1, stdout="", stderr="BAD signature")
with (
mock.patch.object(first_kill, "run", side_effect=[imported, shown, rejected]),
self.assertRaisesRegex(first_kill.FirstKillError, "signature verification failed"),
):
first_kill.verify_checksum_signature(
Path("/release-key.asc"),
Path("/SHA256SUMS"),
Path("/SHA256SUMS.asc"),
)
def test_release_key_bundle_cannot_add_an_attacker_primary_key(self) -> None:
attacker = "B" * 40
imported = mock.Mock(returncode=0, stdout="", stderr="")
shown = mock.Mock(
returncode=0,
stdout=(
"pub:::::::::\n"
f"fpr:::::::::{first_kill.RELEASE_KEY_FINGERPRINT}:\n"
"pub:::::::::\n"
f"fpr:::::::::{attacker}:\n"
),
stderr="",
)
with (
mock.patch.object(first_kill, "run", side_effect=[imported, shown]),
self.assertRaisesRegex(first_kill.FirstKillError, "exactly the published"),
):
first_kill.import_release_key(Path("/gpg-home"), Path("/release-key.asc"))
def test_public_key_fingerprint_is_pinned(self) -> None:
self.assertEqual(40, len(first_kill.RELEASE_KEY_FINGERPRINT))
self.assertEqual(first_kill.RELEASE_KEY_FINGERPRINT.upper(), first_kill.RELEASE_KEY_FINGERPRINT)
if __name__ == "__main__":
unittest.main()
|