diff --git a/scripts/firebase_runtime_failure.py b/scripts/firebase_runtime_failure.py index 0bc7f5d8fd..035c240a41 100644 --- a/scripts/firebase_runtime_failure.py +++ b/scripts/firebase_runtime_failure.py @@ -145,6 +145,11 @@ def staged_backend(path, skills, data): if not case.is_absolute() or case.name != "plugin-06" or ".." in case.parts: raise ValueError("case authority") directory(case) + canonical_case = case.resolve(strict=True) + directory(canonical_case) + if directories[case] != directories[canonical_case]: + raise ValueError("case authority") + case = canonical_case refusal_phase = "native-projection" source_facts = [] entrypoint = None diff --git a/scripts/live-install-audit.py b/scripts/live-install-audit.py index 5b2aa37495..778f0d2069 100644 --- a/scripts/live-install-audit.py +++ b/scripts/live-install-audit.py @@ -2266,6 +2266,44 @@ def kimi_log_fact(facts, reason, changed=None): return None +def kimi_workspace_lock_capture(home, case_root, scope): + """Bind the native empty coordination target to the held scoped snapshot.""" + relative = ".kimi-code/.projects-write-lock" + path = home / relative + metadata_key = "metadata:0:" + relative + content_key = home.name + "/" + relative + # proper-lockfile's live companion must not survive native completion. + if "metadata:0:" + relative + ".lock" in scope: + raise ValueError("Kimi workspace coordinator remains locked") + try: + initial = path.lstat() + except FileNotFoundError: + if metadata_key in scope or content_key in scope: + raise ValueError("Kimi workspace coordinator disappeared") + return None + fields = ("st_dev", "st_mode", "st_nlink", "st_size", + "st_uid", "st_gid", "st_ino", "st_mtime_ns") + identity = tuple(getattr(initial, field) for field in fields) + if (not stat.S_ISREG(initial.st_mode) or stat.S_IMODE(initial.st_mode) != 0o600 + or initial.st_nlink != 1 or initial.st_size != 0 + or initial.st_uid != home.lstat().st_uid): + raise ValueError("Kimi workspace coordinator is not private and empty") + body, error = copilot_settings_read(path, case_root) + if (error is not None or body != "" + or identity != tuple(getattr(path.lstat(), field) for field in fields) + or scope.get(metadata_key) != (initial.st_mode, initial.st_dev, + initial.st_ino, initial.st_mtime_ns) + or scope.get(content_key) != hashlib.sha256(b"").hexdigest()): + raise ValueError("Kimi workspace coordinator changed during capture") + try: + path.with_name(path.name + ".lock").lstat() + except FileNotFoundError: + pass + else: + raise ValueError("Kimi workspace coordinator remains locked") + return identity + + def kimi_repeat_log_capture(home, project, case_root, facts=None): """Private bounded bytes; only hashes leave the isolated audit case.""" path = home / ".kimi-code/logs/kimi-code.log" @@ -2294,6 +2332,7 @@ def parent_facts(): body = body.encode("utf-8") if scope.get(log_key) != hashlib.sha256(body).hexdigest(): return kimi_log_fact(facts, "log-hash-mismatch") + workspace_lock = kimi_workspace_lock_capture(home, case_root, scope) if identity != tuple(getattr(path.lstat(), key) for key in fields): return kimi_log_fact(facts, "log-identity-after-scope-changed") if before_parents != parent_facts(): @@ -2307,7 +2346,8 @@ def parent_facts(): if isinstance(facts, dict): facts["log_bytes"] = len(body) return {"body": body, "identity": identity, "native": native, - "parents": before_parents, "scope": scope, "log_key": log_key} + "parents": before_parents, "scope": scope, "log_key": log_key, + "workspace_lock": workspace_lock} except OSError: return kimi_log_fact(facts, "filesystem-read-refused") except ValueError: @@ -2380,6 +2420,13 @@ def kimi_repeat_log_append(before, after, listed, added, repeated, command, nati if len(after["body"]) <= len(before["body"]): return kimi_log_fact(facts, "log-not-append") ignored = {before["log_key"], "metadata:0:.kimi-code/logs/kimi-code.log"} + left, right = before["workspace_lock"], after["workspace_lock"] + if ((left is None) != (right is None) + or left is not None and left[:6] != right[:6]): + return kimi_log_fact(facts, "workspace-lock-authority-changed") + if left is not None: + # Native 2.5.2 atomically rewrites this empty target before taking its lock. + ignored.add("metadata:0:.kimi-code/.projects-write-lock") original = {key: value for key, value in before["scope"].items() if key not in ignored} current = {key: value for key, value in after["scope"].items() if key not in ignored} if original != current: @@ -2393,7 +2440,8 @@ def kimi_repeat_log_append(before, after, listed, added, repeated, command, nati "before_sha256": hashlib.sha256(before["body"]).hexdigest(), "after_sha256": hashlib.sha256(after["body"]).hexdigest(), "append_sha256": hashlib.sha256(after["body"][len(before["body"]):]).hexdigest(), - "same_inode_mode_parents": True, "post_list_unchanged": True} + "same_inode_mode_parents": True, "post_list_unchanged": True, + **({"workspace_lock": "verified-empty-native-coordinator"} if left is not None else {})} def copilot_settings_sanitized_shape(home, case_root, identity): diff --git a/scripts/test_firebase_runtime_failure.py b/scripts/test_firebase_runtime_failure.py index 256930ee67..33b963f21e 100644 --- a/scripts/test_firebase_runtime_failure.py +++ b/scripts/test_firebase_runtime_failure.py @@ -11,12 +11,19 @@ class FirebaseRuntimeFailureTest(unittest.TestCase): def test_owned_stage_facts_and_all_or_refusal(self): - collect = run_path(str(Path(__file__).with_name("firebase_runtime_failure.py")))["collect"] - for mutation in (None, "link", "foreign", "large", "unknown", "extra-log", + self.check_owned_stage_facts((None, "link", "foreign", "large", "unknown", "extra-log", "missing-owner", "owner-state", "owner-digest", "owner-id", "owner-shape", "data-extra", "parent-link", "parent-replacement", "large-log", "package", "lock", "source-shape", "source-staging", "stage-data", "stage-root", "stage-manifest", - "stage-duplicate", "stage-link", "stage-name", "stage-owner"): + "stage-duplicate", "stage-link", "stage-name", "stage-owner")) + + @unittest.skipUnless(os.name == "nt", "Windows short TEMP spelling") + def test_windows_short_case_spelling_preserves_custody(self): + self.check_owned_stage_facts(("stage-short-case", "stage-short-case-link")) + + def check_owned_stage_facts(self, mutations): + collect = run_path(str(Path(__file__).with_name("firebase_runtime_failure.py")))["collect"] + for mutation in mutations: with self.subTest(mutation=mutation), tempfile.TemporaryDirectory() as temporary: case = Path(temporary).resolve() / "plugin-06" backend = case / "uap-data/plugin-data/firebase-123456789abc" @@ -121,14 +128,32 @@ def replacing_open(path): stage.rename(stage.with_name(stage.name + "-old")) stage.mkdir() return fd + collect_case = case + if mutation in ("stage-short-case", "stage-short-case-link"): + import ctypes + short = ctypes.create_unicode_buffer(32768) + get_short = ctypes.windll.kernel32.GetShortPathNameW + get_short.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint) + get_short.restype = ctypes.c_uint + length = get_short(str(case.parent), short, len(short)) + if not 0 < length < len(short) or Path(short.value) == case.parent: + self.skipTest("Windows short directory names unavailable") + collect_case = Path(short.value) / case.name + if mutation == "stage-short-case-link": + old_case = case.with_name("owned-original") + case.rename(old_case) + try: + case.symlink_to(old_case, target_is_directory=True) + except OSError as error: + self.skipTest(str(error)) with patch.dict(files, {"open_member": replacing_open}): - result = collect(case) + result = collect(collect_case) self.assertIs(result["qualified"], False) self.assertNotIn("PRIVATE", json.dumps(result)) self.assertNotIn("secret.invalid", json.dumps(result)) self.assertNotIn(str(case), json.dumps(result)) self.assertEqual(foreign.read_bytes(), b"foreign untouched") - if mutation in (None, "large-log", "source-staging"): + if mutation in (None, "large-log", "source-staging", "stage-short-case"): self.assertEqual(result["status"], "observed-unqualified") self.assertEqual(result["facts"][0]["staging"][0]["package_sha256"], hashlib.sha256(package).hexdigest()) diff --git a/scripts/test_gemini_windows_runtime_audit.py b/scripts/test_gemini_windows_runtime_audit.py index f235c3da64..77dc34c05d 100644 --- a/scripts/test_gemini_windows_runtime_audit.py +++ b/scripts/test_gemini_windows_runtime_audit.py @@ -316,7 +316,8 @@ def test_same_bytes_swapped_during_the_real_os_read_are_refused(self): changed = [] def swap(fd, count): block = read(fd, count) - if not changed: + selected = case["observer"].windows.leaves.get(str(new)) + if not changed and selected is not None and fd == selected[0]: new.rename(new.with_name("held-old-session")) new.write_bytes(original) changed.append(True) diff --git a/scripts/test_kimi_repeat_log_audit.py b/scripts/test_kimi_repeat_log_audit.py index 400f424a8f..a8c425cab4 100644 --- a/scripts/test_kimi_repeat_log_audit.py +++ b/scripts/test_kimi_repeat_log_audit.py @@ -5,6 +5,7 @@ import stat from pathlib import Path from tempfile import TemporaryDirectory +from types import SimpleNamespace import unittest from unittest.mock import patch @@ -67,6 +68,133 @@ def classify(self, before, after, listed, *, native_before=None, native_after=No (before or {}).get("native") if native_before is None else native_before, (listed or {}).get("native") if native_after is None else native_after, facts) + def workspace_lock(self): + target = self.home / ".kimi-code/.projects-write-lock" + target.write_bytes(b"") + target.chmod(0o600) + return target + + def test_native_empty_workspace_lock_replacement_with_log_append(self): + self.fixture() + target = self.workspace_lock() + before = self.capture() + self.assertIsNotNone(before) + self.append() + temporary = target.with_name(target.name + ".tmp") + temporary.write_bytes(b"") + temporary.chmod(0o600) + os.replace(temporary, target) + after = self.capture() + self.assertIsNotNone(after) + self.assertNotEqual(before["workspace_lock"][6], after["workspace_lock"][6]) + self.assertEqual(before["workspace_lock"][:6], after["workspace_lock"][:6]) + proof = self.classify(before, after, self.capture()) + self.assertIsNotNone(proof) + self.assertEqual(proof["status"], "verified-owned-log-append") + self.assertTrue(proof["post_list_unchanged"]) + + def test_workspace_lock_refuses_unsafe_capture_and_read_replacement(self): + for mutation in ("content", "mode", "uid", "hardlink", "symlink", "directory", + "companion", "read-replacement"): + with self.subTest(mutation=mutation): + self.fixture() + target = self.workspace_lock() + if mutation == "content": + target.write_bytes(b"private-coordinator-canary") + elif mutation == "mode": + target.chmod(0o640) + elif mutation == "hardlink": + os.link(target, self.home / "another-link") + elif mutation == "symlink": + target.unlink() + target.symlink_to(self.home / "foreign") + elif mutation == "directory": + target.unlink() + target.mkdir() + elif mutation == "companion": + target.with_name(target.name + ".lock").mkdir() + read, lstat = self.audit.copilot_settings_read, Path.lstat + reached = [] + def changed_owner(path, *args, **kwargs): + value = lstat(path, *args, **kwargs) + if mutation == "uid" and path == target: + reached.append(True) + fields = {key: getattr(value, key) for key in dir(value) if key.startswith("st_")} + fields["st_uid"] += 1 + return SimpleNamespace(**fields) + return value + def changed_read(path, *args, **kwargs): + value = read(path, *args, **kwargs) + if mutation == "read-replacement" and path == target: + reached.append(True) + temporary = target.with_name(target.name + ".tmp") + temporary.write_bytes(b"") + temporary.chmod(0o600) + os.replace(temporary, target) + return value + facts = {} + with patch.object(Path, "lstat", changed_owner), \ + patch.object(self.audit, "copilot_settings_read", changed_read): + self.assertIsNone(self.capture(facts)) + if mutation in ("uid", "read-replacement"): + self.assertTrue(reached) + self.assertNotIn("private-coordinator-canary", json.dumps(facts)) + self.assertNotIn(str(self.root), json.dumps(facts)) + + def test_workspace_companion_created_during_final_held_read_refuses(self): + self.fixture() + target = self.workspace_lock() + before = self.capture() + self.append() + after = self.capture() + self.assertIsNotNone(self.classify(before, after, self.capture())) + read, reached = self.audit.copilot_settings_read, [] + def create_companion(path, *args, **kwargs): + result = read(path, *args, **kwargs) + if path == target: + reached.append(True) + target.with_name(target.name + ".lock").mkdir() + return result + with patch.object(self.audit, "copilot_settings_read", create_companion): + listed = self.capture() + self.assertEqual(reached, [True]) + self.assertIsNone(listed) + self.assertIsNone(self.classify(before, after, listed)) + + def test_workspace_lock_exception_preserves_all_other_scope_guards(self): + for mutation in ("unexpected-path", "parent", "config", "missing", "created", + "post-list", "public-ready", "closure"): + with self.subTest(mutation=mutation): + self.fixture() + target = self.workspace_lock() + config = self.home / ".kimi-code/config.toml" + config.write_bytes(b"telemetry = false\n") + other = target.with_name("unrelated-empty-file") + other.write_bytes(b"") + other.chmod(0o600) + if mutation == "created": + target.unlink() + before = self.capture() + self.assertIsNotNone(before) + self.append() + selected = other if mutation == "unexpected-path" else config if mutation == "config" else target + temporary = selected.with_name(selected.name + ".tmp") + temporary.write_bytes(selected.read_bytes() if selected.exists() else b"") + temporary.chmod(0o600) + os.replace(temporary, selected) + if mutation == "parent": + selected.parent.chmod(stat.S_IMODE(selected.parent.stat().st_mode) ^ stat.S_IRGRP) + elif mutation == "missing": + target.unlink() + elif mutation == "public-ready": + self.repeated["readiness"] = "needs_action" + elif mutation == "closure": + self.command["timeout"] = True + after = self.capture() + if mutation == "post-list": + target.write_bytes(b"changed after repeat") + self.assertIsNone(self.classify(before, after, self.capture())) + def test_same_inode_append_retains_ready_and_exports_only_hashes(self): self.fixture() before = self.capture()