release: freeze Nexus One AI 1.0.0-rc1
This commit is contained in:
1 parent
63acefd890
commit
4f1419ca93
152 files changed
+9445
-828
No files matched your search
@@ -0,0 +1,97 @@
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MODULE_PATH = Path(__file__).parents[2] / "autoinstall/offline/activation-health-window.py"
|
||||
SPEC = importlib.util.spec_from_file_location("activation_health_window", MODULE_PATH)
|
||||
MODULE = importlib.util.module_from_spec(SPEC)
|
||||
assert SPEC.loader
|
||||
SPEC.loader.exec_module(MODULE)
|
||||
|
||||
|
||||
def profile(required=True):
|
||||
return {"schema": "com.cezen.nexus-one.activation-health-profile.v1", "components": [
|
||||
{"name": "api", "url": "http://127.0.0.1:18080/health", "required": required,
|
||||
"expected_service": "api", "systemd_unit": None, "max_restarts": 0}
|
||||
]}
|
||||
|
||||
|
||||
class ActivationHealthWindowTests(unittest.TestCase):
|
||||
def test_ready_requires_all_consecutive_samples(self):
|
||||
evidence = MODULE.evaluate(profile(), "op-1", 3, 1, 2, 10, False,
|
||||
lambda component, timeout: {"ok": True, "code": "READY", "status": "ready"},
|
||||
lambda component: {"ok": True, "code": "RESTARTS_OK", "restarts": 0},
|
||||
lambda interval: None)
|
||||
self.assertEqual(evidence["outcome"], "ready")
|
||||
self.assertEqual(evidence["samples_completed"], 3)
|
||||
self.assertEqual(len(evidence["checks"]), 3)
|
||||
|
||||
def test_optional_degraded_requires_explicit_policy(self):
|
||||
degraded = lambda component, timeout: {"ok": False, "code": "DEGRADED", "status": "degraded"}
|
||||
accepted = MODULE.evaluate(profile(False), "op-1", 1, 0, 2, 10, True, degraded)
|
||||
rejected = MODULE.evaluate(profile(False), "op-1", 1, 0, 2, 10, False, degraded)
|
||||
self.assertEqual(accepted["outcome"], "degraded")
|
||||
self.assertEqual(rejected["outcome"], "rejected")
|
||||
|
||||
def test_timeout_and_malformed_response_reject(self):
|
||||
for code in ("TIMEOUT", "MALFORMED_JSON"):
|
||||
with self.subTest(code=code):
|
||||
evidence = MODULE.evaluate(profile(), "op-1", 3, 0, 2, 10, False,
|
||||
lambda component, timeout, code=code: {"ok": False, "code": code})
|
||||
self.assertEqual(evidence["outcome"], "rejected")
|
||||
self.assertEqual(evidence["samples_completed"], 1)
|
||||
self.assertEqual(evidence["checks"][-1]["code"], code)
|
||||
|
||||
def test_rejected_window_returns_23_for_systemd_onfailure(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
config = root / "profile.json"
|
||||
config.write_text(json.dumps(profile()))
|
||||
evidence = root / "evidence.json"
|
||||
arguments = ["--operation-id", "op-1", "--profile-config", str(config),
|
||||
"--samples", "3", "--interval-seconds", "0", "--timeout-seconds", "2",
|
||||
"--window-timeout-seconds", "10",
|
||||
"--evidence", str(evidence)]
|
||||
result = MODULE.main(arguments,
|
||||
lambda component, timeout: {"ok": False, "code": "HTTP_503"})
|
||||
self.assertEqual(result, 23)
|
||||
self.assertEqual(json.loads(evidence.read_text())["outcome"], "rejected")
|
||||
self.assertEqual(os.stat(evidence).st_mode & 0o777, 0o600)
|
||||
|
||||
def test_non_loopback_and_hostname_urls_fail_closed(self):
|
||||
for url in ("http://172.16.10.144:8080/health", "http://localhost:8080/health"):
|
||||
candidate = profile()
|
||||
candidate["components"][0]["url"] = url
|
||||
with self.assertRaises(MODULE.HealthConfigError):
|
||||
MODULE.validate_config(candidate)
|
||||
|
||||
def test_total_window_deadline_rejects_before_next_sample(self):
|
||||
now = [0.0]
|
||||
evidence = MODULE.evaluate(
|
||||
profile(), "op-1", 3, 2, 1, 1.5, False,
|
||||
lambda component, timeout: {"ok": True, "code": "READY", "status": "ready"},
|
||||
lambda component: {"ok": True, "code": "RESTARTS_OK", "restarts": 0},
|
||||
lambda interval: now.__setitem__(0, now[0] + interval), lambda: now[0])
|
||||
self.assertEqual(evidence["outcome"], "rejected")
|
||||
self.assertEqual(evidence["checks"][-1]["code"], "WINDOW_TIMEOUT")
|
||||
|
||||
def test_restart_storm_rejects_before_http_probe(self):
|
||||
called = []
|
||||
candidate = profile()
|
||||
candidate["components"][0].update(systemd_unit="cezen-api.service", max_restarts=2)
|
||||
evidence = MODULE.evaluate(
|
||||
candidate, "op-1", 3, 0, 1, 10, False,
|
||||
lambda component, timeout: called.append(component),
|
||||
lambda component: {"ok": False, "code": "RESTART_STORM", "restarts": 3})
|
||||
self.assertEqual(evidence["outcome"], "rejected")
|
||||
self.assertEqual(evidence["checks"][-1]["code"], "RESTART_STORM")
|
||||
self.assertEqual(evidence["checks"][-1]["restart_count"], 3)
|
||||
self.assertEqual(called, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,74 @@
|
||||
import importlib.util
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MODULE_PATH = Path(__file__).parents[2] / "autoinstall/offline/atomic-profile-journal.py"
|
||||
SPEC = importlib.util.spec_from_file_location("atomic_profile_journal", MODULE_PATH)
|
||||
MODULE = importlib.util.module_from_spec(SPEC)
|
||||
assert SPEC.loader
|
||||
SPEC.loader.exec_module(MODULE)
|
||||
|
||||
|
||||
IDENTITY = {"operation_id": "op-1", "profile": "cpu-only", "manifest_sha256": "a" * 64}
|
||||
|
||||
|
||||
class AtomicProfileJournalTests(unittest.TestCase):
|
||||
def test_atomic_sequence_and_permissions(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "journal.json"
|
||||
first = MODULE.update(path, expected_generation=0, state="profile_selected",
|
||||
checkpoint_id=None, **IDENTITY)
|
||||
self.assertEqual(first["generation"], 1)
|
||||
self.assertEqual(os.stat(path).st_mode & 0o777, 0o600)
|
||||
second = MODULE.update(path, expected_generation=1, state="checkpoint_ready",
|
||||
checkpoint_id="checkpoint-1", **IDENTITY)
|
||||
third = MODULE.update(path, expected_generation=2, state="installing",
|
||||
checkpoint_id=None, **IDENTITY)
|
||||
self.assertEqual(third["checkpoint_id"], "checkpoint-1")
|
||||
self.assertEqual(third["previous_record_sha256"], second["record_sha256"])
|
||||
|
||||
def test_stale_generation_and_identity_change_fail(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "journal.json"
|
||||
MODULE.update(path, expected_generation=0, state="profile_selected",
|
||||
checkpoint_id=None, **IDENTITY)
|
||||
with self.assertRaisesRegex(MODULE.JournalError, "GENERATION_STALE"):
|
||||
MODULE.update(path, expected_generation=0, state="checkpoint_ready",
|
||||
checkpoint_id="checkpoint-1", **IDENTITY)
|
||||
with self.assertRaisesRegex(MODULE.JournalError, "IDENTITY_CHANGED"):
|
||||
MODULE.update(path, expected_generation=1, state="checkpoint_ready",
|
||||
checkpoint_id="checkpoint-1", **{**IDENTITY, "profile": "nvidia-cu128"})
|
||||
|
||||
def test_checkpoint_required_before_installing(self):
|
||||
current = MODULE.next_record(None, 0, "op-1", "cpu-only", "a" * 64,
|
||||
"profile_selected", None)
|
||||
with self.assertRaisesRegex(MODULE.JournalError, "TRANSITION_INVALID"):
|
||||
MODULE.next_record(current, 1, "op-1", "cpu-only", "a" * 64, "installing", None)
|
||||
with self.assertRaisesRegex(MODULE.JournalError, "CHECKPOINT_ID_REQUIRED"):
|
||||
MODULE.next_record(current, 1, "op-1", "cpu-only", "a" * 64,
|
||||
"checkpoint_ready", None)
|
||||
|
||||
def test_tamper_is_detected(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "journal.json"
|
||||
MODULE.update(path, expected_generation=0, state="profile_selected",
|
||||
checkpoint_id=None, **IDENTITY)
|
||||
path.write_text(path.read_text().replace("cpu-only", "nvidia-cu128"))
|
||||
with self.assertRaisesRegex(MODULE.JournalError, "DIGEST_INVALID"):
|
||||
MODULE.read_verified(path)
|
||||
|
||||
def test_rollback_is_terminal(self):
|
||||
current = MODULE.next_record(None, 0, "op-1", "cpu-only", "a" * 64,
|
||||
"profile_selected", None)
|
||||
rolled_back = MODULE.next_record(current, 1, "op-1", "cpu-only", "a" * 64,
|
||||
"rolled_back", None)
|
||||
with self.assertRaisesRegex(MODULE.JournalError, "TRANSITION_INVALID"):
|
||||
MODULE.next_record(rolled_back, 2, "op-1", "cpu-only", "a" * 64,
|
||||
"profile_selected", None)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,91 @@
|
||||
import importlib.util
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MODULE_PATH = Path(__file__).parents[2] / "autoinstall/offline/install-python-profile.py"
|
||||
SPEC = importlib.util.spec_from_file_location("install_python_profile", MODULE_PATH)
|
||||
MODULE = importlib.util.module_from_spec(SPEC)
|
||||
assert SPEC.loader
|
||||
SPEC.loader.exec_module(MODULE)
|
||||
|
||||
|
||||
class InstallPythonProfileTests(unittest.TestCase):
|
||||
def test_service_probe_must_be_absolute_regular_and_executable(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
with self.assertRaisesRegex(ValueError, "SERVICE_HEALTH_PROBE_NOT_ABSOLUTE"):
|
||||
MODULE.validate_service_probe(Path("relative-probe"))
|
||||
probe = root / "probe"
|
||||
probe.write_text("#!/bin/sh\nexit 0\n")
|
||||
with self.assertRaisesRegex(ValueError, "SERVICE_HEALTH_PROBE_NOT_EXECUTABLE"):
|
||||
MODULE.validate_service_probe(probe)
|
||||
os.chmod(probe, 0o700)
|
||||
MODULE.validate_service_probe(probe)
|
||||
|
||||
def test_service_probe_failure_and_timeout_are_failures(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
probe = Path(directory) / "probe"
|
||||
probe.write_text("#!/bin/sh\nexit 23\n")
|
||||
os.chmod(probe, 0o700)
|
||||
with self.assertRaises(Exception):
|
||||
MODULE.service_health(probe, Path(directory), "cpu-only", 1)
|
||||
with self.assertRaisesRegex(ValueError, "SERVICE_HEALTH_TIMEOUT_INVALID"):
|
||||
MODULE.install(Path("journal"), Path("checkpoint"), Path("target"),
|
||||
Path("wheels"), Path("requirements"), Path(sys.executable),
|
||||
probe, 0)
|
||||
|
||||
def test_failed_offline_resolution_rolls_back_without_target_change(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
target = root / "venv"
|
||||
target.mkdir()
|
||||
(target / "old").write_text("old")
|
||||
checkpoint = root / "checkpoint"
|
||||
manifest = MODULE.checkpoint_api.create(target, checkpoint, "op-1")
|
||||
journal = root / "journal.json"
|
||||
identity = dict(operation_id="op-1", profile="cpu-only", manifest_sha256="a" * 64)
|
||||
current = MODULE.journal_api.update(journal, expected_generation=0,
|
||||
state="profile_selected", checkpoint_id=None, **identity)
|
||||
MODULE.journal_api.update(journal, expected_generation=current["generation"],
|
||||
state="checkpoint_ready",
|
||||
checkpoint_id=manifest["inventory_sha256"], **identity)
|
||||
requirements = root / "requirements.txt"
|
||||
requirements.write_text("definitely-not-a-real-package==1\n")
|
||||
wheels = root / "wheels"
|
||||
wheels.mkdir()
|
||||
with self.assertRaises(Exception):
|
||||
MODULE.install(journal, checkpoint, target, wheels, requirements, Path(sys.executable))
|
||||
self.assertEqual((target / "old").read_text(), "old")
|
||||
self.assertEqual(MODULE.journal_api.read_verified(journal)["state"], "rolled_back")
|
||||
|
||||
def test_recover_activated_target_restores_checkpoint(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
target = root / "venv"
|
||||
target.mkdir()
|
||||
(target / "marker").write_text("old")
|
||||
checkpoint = root / "checkpoint"
|
||||
manifest = MODULE.checkpoint_api.create(target, checkpoint, "op-1")
|
||||
journal = root / "journal.json"
|
||||
identity = dict(operation_id="op-1", profile="cpu-only", manifest_sha256="a" * 64)
|
||||
current = MODULE.journal_api.update(journal, expected_generation=0,
|
||||
state="profile_selected", checkpoint_id=None, **identity)
|
||||
current = MODULE.journal_api.update(journal, expected_generation=current["generation"],
|
||||
state="checkpoint_ready",
|
||||
checkpoint_id=manifest["inventory_sha256"], **identity)
|
||||
MODULE.journal_api.update(journal, expected_generation=current["generation"],
|
||||
state="installing", checkpoint_id=manifest["inventory_sha256"],
|
||||
**identity)
|
||||
(target / "marker").write_text("activated")
|
||||
result = MODULE.recover(journal, checkpoint, target)
|
||||
self.assertEqual(result["state"], "rolled_back")
|
||||
self.assertEqual((target / "marker").read_text(), "old")
|
||||
self.assertEqual((root / ".venv.rollback-discard/marker").read_text(), "activated")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,89 @@
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
VALIDATOR = ROOT / "autoinstall/offline/validate-payload-lock.py"
|
||||
CANDIDATE = ROOT / "autoinstall/offline/payload-lock.candidate.json"
|
||||
|
||||
|
||||
def run(lock: Path) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run(
|
||||
[sys.executable, str(VALIDATOR), str(lock)],
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def complete_lock() -> dict:
|
||||
digest = "a" * 64
|
||||
groups = {}
|
||||
for group in ("apt", "python", "runtime", "models", "source"):
|
||||
groups[group] = [{
|
||||
"id": f"test-{group}",
|
||||
"version": "1.0.0-test",
|
||||
"architecture": "amd64" if group != "source" else "all",
|
||||
"source": f"https://invalid.example/{group}/1.0.0-test",
|
||||
"target": f"payload/{group}/test.bin",
|
||||
"sha256": digest,
|
||||
"bytes": 1,
|
||||
"bytes_basis": "measured",
|
||||
"license": "TEST-ONLY"
|
||||
}]
|
||||
groups["containers"] = [{
|
||||
"id": "test-container",
|
||||
"version": "1.0.0-test",
|
||||
"architecture": "amd64",
|
||||
"source": f"invalid.example/test/image@sha256:{digest}",
|
||||
"target": "payload/containers/test.oci",
|
||||
"sha256": digest,
|
||||
"bytes": 1,
|
||||
"bytes_basis": "measured",
|
||||
"license": "TEST-ONLY"
|
||||
}]
|
||||
return {
|
||||
"schema": "nexus-one-ai.offline-workstation-payload-lock.v1",
|
||||
"product": "offline-workstation",
|
||||
"architecture": "amd64",
|
||||
"ubuntu_release": "22.04.5",
|
||||
"approval_record": "CT-G1-2026-009",
|
||||
"status": "reviewed",
|
||||
"unresolved": [],
|
||||
"objects": groups,
|
||||
}
|
||||
|
||||
|
||||
class PayloadLockTests(unittest.TestCase):
|
||||
def test_candidate_fails_closed(self) -> None:
|
||||
result = run(CANDIDATE)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertIn("status must be reviewed", result.stderr)
|
||||
self.assertIn("unresolved must be an empty array", result.stderr)
|
||||
|
||||
def test_complete_test_lock_passes(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
lock = Path(directory) / "payload-lock.json"
|
||||
lock.write_text(json.dumps(complete_lock()), encoding="utf-8")
|
||||
result = run(lock)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_mutable_container_and_duplicate_target_fail(self) -> None:
|
||||
data = complete_lock()
|
||||
data["objects"]["containers"][0]["source"] = "invalid.example/test/image:latest"
|
||||
data["objects"]["python"][0]["target"] = data["objects"]["apt"][0]["target"]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
lock = Path(directory) / "payload-lock.json"
|
||||
lock.write_text(json.dumps(data), encoding="utf-8")
|
||||
result = run(lock)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertIn("must be an OCI reference pinned with @sha256", result.stderr)
|
||||
self.assertIn("duplicate target path", result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,65 @@
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MODULE_PATH = Path(__file__).parents[2] / "autoinstall/offline/prepare-python-profile-operation.py"
|
||||
SPEC = importlib.util.spec_from_file_location("prepare_python_profile_operation", MODULE_PATH)
|
||||
MODULE = importlib.util.module_from_spec(SPEC)
|
||||
assert SPEC.loader
|
||||
SPEC.loader.exec_module(MODULE)
|
||||
|
||||
|
||||
class PreparePythonProfileOperationTests(unittest.TestCase):
|
||||
def test_prepares_and_resumes_without_mutating_target(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
target = root / "venv"
|
||||
target.mkdir()
|
||||
(target / "old").write_text("old")
|
||||
wheels = root / "wheels"
|
||||
wheels.mkdir()
|
||||
wheel = wheels / "torch-cpu.whl"
|
||||
wheel.write_bytes(b"cpu")
|
||||
contract = {"profiles": {"cpu-only": {
|
||||
"required": {wheel.name: hashlib.sha256(b"cpu").hexdigest()},
|
||||
"forbidden_filename_patterns": ["cu12"],
|
||||
}}}
|
||||
receipt = {
|
||||
"schema": "com.cezen.nexus-one.profile-membership-verification-receipt.v1",
|
||||
"environment": "test", "result": "verified", "manifest_sha256": "a" * 64,
|
||||
"namespace": "offline-workstation/python-runtime-profiles", "profiles": ["cpu-only"],
|
||||
}
|
||||
args = ({"architecture": "amd64"}, receipt, "auto", "op-1", root / "journal.json",
|
||||
target, root / "checkpoint", contract, wheels, True)
|
||||
first = MODULE.prepare(*args)
|
||||
second = MODULE.prepare(*args)
|
||||
self.assertEqual(first["checkpoint_id"], second["checkpoint_id"])
|
||||
self.assertEqual((target / "old").read_text(), "old")
|
||||
self.assertFalse(first["mutation_performed"])
|
||||
|
||||
def test_invalid_payload_creates_no_journal_or_checkpoint(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
wheels = root / "wheels"
|
||||
wheels.mkdir()
|
||||
receipt = {
|
||||
"schema": "com.cezen.nexus-one.profile-membership-verification-receipt.v1",
|
||||
"environment": "test", "result": "verified", "manifest_sha256": "a" * 64,
|
||||
"namespace": "offline-workstation/python-runtime-profiles", "profiles": ["cpu-only"],
|
||||
}
|
||||
journal = root / "journal.json"
|
||||
checkpoint = root / "checkpoint"
|
||||
with self.assertRaisesRegex(ValueError, "PROFILE_PAYLOAD_INVALID"):
|
||||
MODULE.prepare({"architecture": "amd64"}, receipt, "auto", "op-1", journal,
|
||||
root / "target", checkpoint,
|
||||
{"profiles": {"cpu-only": {"required": {"missing.whl": "0" * 64}}}},
|
||||
wheels, True)
|
||||
self.assertFalse(journal.exists())
|
||||
self.assertFalse(checkpoint.exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,74 @@
|
||||
import importlib.util
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MODULE_PATH = Path(__file__).parents[2] / "autoinstall/offline/python-environment-checkpoint.py"
|
||||
SPEC = importlib.util.spec_from_file_location("python_environment_checkpoint", MODULE_PATH)
|
||||
MODULE = importlib.util.module_from_spec(SPEC)
|
||||
assert SPEC.loader
|
||||
SPEC.loader.exec_module(MODULE)
|
||||
|
||||
|
||||
class PythonEnvironmentCheckpointTests(unittest.TestCase):
|
||||
def test_create_verify_modify_and_restore(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
target = root / "venv"
|
||||
target.mkdir()
|
||||
(target / "package.py").write_text("old\n")
|
||||
(target / "link").symlink_to("package.py")
|
||||
checkpoint = root / "checkpoint"
|
||||
created = MODULE.create(target, checkpoint, "op-1")
|
||||
self.assertEqual(MODULE.verify(checkpoint, target)["inventory_sha256"],
|
||||
created["inventory_sha256"])
|
||||
(target / "package.py").write_text("new\n")
|
||||
MODULE.restore(checkpoint, target)
|
||||
self.assertEqual((target / "package.py").read_text(), "old\n")
|
||||
self.assertEqual((target / "link").readlink(), Path("package.py"))
|
||||
|
||||
def test_payload_tamper_fails(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
target = root / "venv"
|
||||
target.mkdir()
|
||||
(target / "package.py").write_text("old\n")
|
||||
checkpoint = root / "checkpoint"
|
||||
MODULE.create(target, checkpoint, "op-1")
|
||||
(checkpoint / "payload/package.py").write_text("tampered\n")
|
||||
with self.assertRaisesRegex(MODULE.CheckpointError, "PAYLOAD_INVALID"):
|
||||
MODULE.verify(checkpoint, target)
|
||||
|
||||
def test_absent_target_restore_quarantines_new_tree(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
target = root / "venv"
|
||||
checkpoint = root / "checkpoint"
|
||||
MODULE.create(target, checkpoint, "op-1")
|
||||
target.mkdir()
|
||||
(target / "new").write_text("new")
|
||||
MODULE.restore(checkpoint, target)
|
||||
self.assertFalse(target.exists())
|
||||
self.assertTrue((root / ".venv.rollback-discard/new").exists())
|
||||
|
||||
def test_recover_after_quarantine_and_after_activation(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
target = root / "venv"
|
||||
target.mkdir()
|
||||
(target / "package.py").write_text("old\n")
|
||||
checkpoint = root / "checkpoint"
|
||||
MODULE.create(target, checkpoint, "op-1")
|
||||
(target / "package.py").write_text("new\n")
|
||||
quarantine = root / ".venv.rollback-discard"
|
||||
target.rename(quarantine)
|
||||
MODULE.recover_restore(checkpoint, target)
|
||||
self.assertEqual((target / "package.py").read_text(), "old\n")
|
||||
# A retry after activation is idempotent and preserves the failed tree.
|
||||
MODULE.recover_restore(checkpoint, target)
|
||||
self.assertEqual((quarantine / "package.py").read_text(), "new\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,41 @@
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MODULE_PATH = Path(__file__).parents[2] / "autoinstall/offline/validate-python-runtime-profile.py"
|
||||
SPEC = importlib.util.spec_from_file_location("validate_python_runtime_profile", MODULE_PATH)
|
||||
MODULE = importlib.util.module_from_spec(SPEC)
|
||||
assert SPEC.loader
|
||||
SPEC.loader.exec_module(MODULE)
|
||||
|
||||
|
||||
class PythonRuntimeProfileTests(unittest.TestCase):
|
||||
def test_accepts_required_wheel_with_matching_digest(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
wheel = Path(directory) / "torch-cpu.whl"
|
||||
wheel.write_bytes(b"cpu")
|
||||
contract = {"profiles": {"cpu-only": {
|
||||
"required": {wheel.name: hashlib.sha256(b"cpu").hexdigest()},
|
||||
"forbidden_filename_patterns": ["cu12"],
|
||||
}}}
|
||||
self.assertEqual(MODULE.validate(contract, "cpu-only", Path(directory)), [])
|
||||
|
||||
def test_rejects_forbidden_gpu_wheel_and_digest_mismatch(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / "torch-cpu.whl").write_bytes(b"changed")
|
||||
(root / "nvidia_cuda_cu12.whl").write_bytes(b"gpu")
|
||||
contract = {"profiles": {"cpu-only": {
|
||||
"required": {"torch-cpu.whl": hashlib.sha256(b"cpu").hexdigest()},
|
||||
"forbidden_filename_patterns": ["nvidia_", "cu12"],
|
||||
}}}
|
||||
errors = MODULE.validate(contract, "cpu-only", root)
|
||||
self.assertTrue(any("forbidden pattern" in error for error in errors))
|
||||
self.assertIn("digest mismatch: torch-cpu.whl", errors)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,76 @@
|
||||
import importlib.util
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MODULE_PATH = Path(__file__).parents[2] / "autoinstall/offline/plan-python-runtime-profile.py"
|
||||
SPEC = importlib.util.spec_from_file_location("plan_python_runtime_profile", MODULE_PATH)
|
||||
MODULE = importlib.util.module_from_spec(SPEC)
|
||||
assert SPEC.loader
|
||||
SPEC.loader.exec_module(MODULE)
|
||||
|
||||
|
||||
RECEIPT = {
|
||||
"schema": "com.cezen.nexus-one.profile-membership-verification-receipt.v1",
|
||||
"environment": "production",
|
||||
"result": "verified",
|
||||
"manifest_sha256": "a" * 64,
|
||||
"namespace": "offline-workstation/python-runtime-profiles",
|
||||
"profiles": ["cpu-only", "nvidia-cu128"],
|
||||
}
|
||||
|
||||
|
||||
class PythonRuntimeProfilePlanTests(unittest.TestCase):
|
||||
def test_auto_defaults_to_cpu_when_nvidia_probe_is_incomplete(self):
|
||||
result = MODULE.plan({"architecture": "amd64", "nvidia": {"present": True}}, RECEIPT,
|
||||
"auto", "op-1", None)
|
||||
self.assertEqual(result["selected_profile"], "cpu-only")
|
||||
|
||||
def test_auto_selects_nvidia_only_when_all_readiness_facts_pass(self):
|
||||
probe = {"architecture": "amd64", "nvidia": {
|
||||
"present": True, "supported": True, "driver_ready": True,
|
||||
}}
|
||||
result = MODULE.plan(probe, RECEIPT, "auto", "op-1", None)
|
||||
self.assertEqual(result["selected_profile"], "nvidia-cu128")
|
||||
|
||||
def test_unverified_or_unsigned_profile_fails_closed(self):
|
||||
with self.assertRaises(MODULE.PlanError) as invalid:
|
||||
MODULE.plan({"architecture": "amd64"}, {}, "auto", "op-1", None)
|
||||
self.assertEqual(invalid.exception.code, "MEMBERSHIP_RECEIPT_INVALID")
|
||||
receipt = {**RECEIPT, "profiles": ["cpu-only"]}
|
||||
probe = {"architecture": "amd64", "nvidia": {
|
||||
"present": True, "supported": True, "driver_ready": True,
|
||||
}}
|
||||
with self.assertRaisesRegex(MODULE.PlanError, "not signed membership"):
|
||||
MODULE.plan(probe, receipt, "auto", "op-1", None)
|
||||
|
||||
def test_test_receipt_requires_explicit_test_mode(self):
|
||||
receipt = {**RECEIPT, "environment": "test"}
|
||||
with self.assertRaises(MODULE.PlanError) as forbidden:
|
||||
MODULE.plan({"architecture": "amd64"}, receipt, "auto", "op-1", None)
|
||||
self.assertEqual(forbidden.exception.code, "TEST_RECEIPT_FORBIDDEN")
|
||||
result = MODULE.plan({"architecture": "amd64"}, receipt, "auto", "op-1", None, True)
|
||||
self.assertEqual(result["selected_profile"], "cpu-only")
|
||||
|
||||
def test_resume_reuses_recorded_profile(self):
|
||||
journal = {"operation_id": "op-1", "selected_profile": "cpu-only", "state": "installing"}
|
||||
result = MODULE.plan({"architecture": "amd64"}, RECEIPT, "cpu-only", "op-1", journal)
|
||||
self.assertEqual(result["action"], "resume")
|
||||
|
||||
def test_profile_change_requires_rollback(self):
|
||||
journal = {"operation_id": "op-1", "selected_profile": "cpu-only", "state": "installing"}
|
||||
probe = {"architecture": "amd64", "nvidia": {
|
||||
"present": True, "supported": True, "driver_ready": True,
|
||||
}}
|
||||
with self.assertRaises(MODULE.PlanError) as raised:
|
||||
MODULE.plan(probe, RECEIPT, "nvidia-cu128", "op-1", journal)
|
||||
self.assertEqual(raised.exception.code, "PROFILE_CHANGE_REQUIRES_ROLLBACK")
|
||||
|
||||
def test_rolled_back_operation_id_cannot_be_reused(self):
|
||||
journal = {"operation_id": "op-1", "selected_profile": "cpu-only", "state": "rolled_back"}
|
||||
with self.assertRaisesRegex(MODULE.PlanError, "new operation id"):
|
||||
MODULE.plan({"architecture": "amd64"}, RECEIPT, "cpu-only", "op-1", journal)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,48 @@
|
||||
import importlib.util
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MODULE_PATH = Path(__file__).parents[2] / "autoinstall/offline/recover-python-profile-on-boot.py"
|
||||
SPEC = importlib.util.spec_from_file_location("recover_python_profile_on_boot", MODULE_PATH)
|
||||
MODULE = importlib.util.module_from_spec(SPEC)
|
||||
assert SPEC.loader
|
||||
SPEC.loader.exec_module(MODULE)
|
||||
|
||||
|
||||
class RecoverPythonProfileOnBootTests(unittest.TestCase):
|
||||
def test_absent_and_terminal_states_are_noop(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
self.assertEqual(MODULE.recover(root / "missing", root / "cp", root / "target")["action"],
|
||||
"none")
|
||||
|
||||
def test_installing_state_rolls_back(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
target = root / "venv"
|
||||
target.mkdir()
|
||||
(target / "marker").write_text("old")
|
||||
checkpoint = root / "checkpoint"
|
||||
manifest = MODULE.installer.checkpoint_api.create(target, checkpoint, "op-1")
|
||||
journal = root / "journal.json"
|
||||
identity = dict(operation_id="op-1", profile="cpu-only", manifest_sha256="a" * 64)
|
||||
current = MODULE.journal_api.update(journal, expected_generation=0,
|
||||
state="profile_selected", checkpoint_id=None, **identity)
|
||||
current = MODULE.journal_api.update(journal, expected_generation=current["generation"],
|
||||
state="checkpoint_ready",
|
||||
checkpoint_id=manifest["inventory_sha256"], **identity)
|
||||
MODULE.journal_api.update(journal, expected_generation=current["generation"],
|
||||
state="installing", checkpoint_id=manifest["inventory_sha256"],
|
||||
**identity)
|
||||
(target / "marker").write_text("activated")
|
||||
result = MODULE.recover(journal, checkpoint, target)
|
||||
self.assertEqual(result["state"], "rolled_back")
|
||||
self.assertEqual((target / "marker").read_text(), "old")
|
||||
self.assertEqual(MODULE.recover(journal, checkpoint, target)["reason"],
|
||||
"terminal_rolled_back")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,76 @@
|
||||
import base64
|
||||
import importlib.util
|
||||
import json
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MODULE_PATH = Path(__file__).parents[2] / "autoinstall/offline/verify-python-profile-membership.py"
|
||||
SPEC = importlib.util.spec_from_file_location("verify_python_profile_membership", MODULE_PATH)
|
||||
MODULE = importlib.util.module_from_spec(SPEC)
|
||||
assert SPEC.loader
|
||||
SPEC.loader.exec_module(MODULE)
|
||||
|
||||
|
||||
class VerifyPythonProfileMembershipTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
algorithms = subprocess.run(["openssl", "list", "-public-key-algorithms"],
|
||||
capture_output=True, text=True)
|
||||
if algorithms.returncode != 0 or "ED25519" not in algorithms.stdout.upper():
|
||||
raise unittest.SkipTest("OpenSSL build has no Ed25519 support")
|
||||
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
root = Path(self.temp.name)
|
||||
self.private = root / "test-private.pem"
|
||||
self.public = root / "test-public.pem"
|
||||
subprocess.run(["openssl", "genpkey", "-algorithm", "ED25519", "-out", self.private], check=True)
|
||||
subprocess.run(["openssl", "pkey", "-in", self.private, "-pubout", "-out", self.public], check=True)
|
||||
self.manifest = {
|
||||
"namespace": "offline-workstation/python-runtime-profiles",
|
||||
"profiles": {"cpu-only": {}, "nvidia-cu128": {}},
|
||||
}
|
||||
body = root / "body"
|
||||
signature = root / "signature"
|
||||
body.write_bytes(MODULE.canonical(self.manifest))
|
||||
subprocess.run(["openssl", "pkeyutl", "-sign", "-inkey", self.private, "-rawin",
|
||||
"-in", body, "-out", signature], check=True)
|
||||
der = subprocess.run(["openssl", "pkey", "-pubin", "-in", self.public, "-outform", "DER"],
|
||||
check=True, capture_output=True).stdout
|
||||
self.trust = {"policy_version": "test-v1", "keys": [{
|
||||
"key_id": "TEST-PROFILE-KEY", "algorithm": "ed25519",
|
||||
"purpose": "profile-membership", "status": "active", "environment": "test",
|
||||
"public_key_sha256": MODULE.sha256(der),
|
||||
}]}
|
||||
self.envelope = {
|
||||
"schema": "com.cezen.nexus-one.signature-envelope.v1",
|
||||
"manifest_digest": "sha256:" + MODULE.sha256(MODULE.canonical(self.manifest)),
|
||||
"algorithm": "ed25519", "key_id": "TEST-PROFILE-KEY",
|
||||
"policy_version": "test-v1", "signature": base64.b64encode(signature.read_bytes()).decode(),
|
||||
}
|
||||
|
||||
def tearDown(self):
|
||||
self.temp.cleanup()
|
||||
|
||||
def test_valid_signature_emits_bound_test_receipt(self):
|
||||
receipt = MODULE.verify(self.manifest, self.envelope, self.trust, self.public, "test",
|
||||
"2026-07-14T00:00:00Z", "f" * 64)
|
||||
self.assertEqual(receipt["result"], "verified")
|
||||
self.assertEqual(receipt["profiles"], ["cpu-only", "nvidia-cu128"])
|
||||
|
||||
def test_tamper_and_wrong_environment_fail(self):
|
||||
tampered = json.loads(json.dumps(self.manifest))
|
||||
tampered["profiles"]["extra"] = {}
|
||||
with self.assertRaisesRegex(MODULE.VerificationError, "DIGEST_MISMATCH"):
|
||||
MODULE.verify(tampered, self.envelope, self.trust, self.public, "test",
|
||||
"2026-07-14T00:00:00Z", "f" * 64)
|
||||
with self.assertRaisesRegex(MODULE.VerificationError, "KEY_POLICY_REJECTED"):
|
||||
MODULE.verify(self.manifest, self.envelope, self.trust, self.public, "production",
|
||||
"2026-07-14T00:00:00Z", "f" * 64)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user