From 137e1f8205f2a4daa99d4565b6772bf00d253191 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:25:01 -0800 Subject: [PATCH 1/5] Fix credential helper release verification trust boundary --- SHA256SUMS | 14 +- SOURCE.json | 2 +- keel-setup/SKILL.md | 7 +- keel-setup/scripts/authoring_context.py | 80 +++++++--- keel-setup/scripts/verify_execute.py | 80 +++++++--- keel-setup/tests/test_authoring_context.py | 12 +- keel-setup/tests/test_verify_execute.py | 167 ++++++++++++++++++--- scripts/check_release_bundle.py | 2 +- 8 files changed, 295 insertions(+), 69 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 9ebcaf2..fd23da2 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -7ae01826ace06b5d590e11be83aaf3a1831dc47c45514bc955538be2b63bb677 SOURCE.json +d1429e0528c516407d30533bd107fc7fae2790e7f2637a5ba02c8e44f39e9897 SOURCE.json 41f17c2c3b0d7ab61fd6c985c553bfe6df4df12be8eeb1feaa60437a7ee30ac1 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -16,29 +16,29 @@ b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore b5711d319ef939c7522df53ffc3dea7c4dcc371537dff4cc7307f2a4bc59dffb keel-policy/tests/test_authoring_context_consumption.py 820069a6ce02f74dccc4f57a5788359b1377520330d00ba88471d60fec901f17 keel-policy/tests/test_basic_profile_fields.py 322b430367e859dae341e9c225be34c6c5272c481074e7b1ae2242db527e1cbe keel-policy/tests/test_validate_enforceability_report.py -006a589270c0bd1c17248ee6b1a73e513f265b068e6671edea7085a516f79c61 keel-setup/SKILL.md +b8387c9667d558cf76ac0c77ec586121955647a24cb1c863d6665edb205c0f28 keel-setup/SKILL.md 2b9c2490e921e83b83372a09e422a30f0f7ee338a2809b8e07edbd381d9eb650 keel-setup/reference/coverage.schema.json 70a69dcab29f61aaa3f96de5f65854fca63c4549ddc20d84ee00e102fc68c691 keel-setup/reference/integration_profiles.v1.json 9739501499b286d40f356af9c0378bbdcde41a364be083ccbc34adb000575160 keel-setup/reference/setup-state.schema.json 7ef2361f3f10601f9a4d3681d04c8538836c37448787262b26e82bf18bcbbc70 keel-setup/reference/unified-execute-request.contract.json c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/reference/voice-gateway.md -8c51cf0384ae0acf2684a913292da7788f40be3fd40c35afcbf4f89bfb79a05b keel-setup/scripts/authoring_context.py +85087e7fcc58ae504feef3fb06cf1efeaa10c6c943cbbee1c5a509edf49a732c keel-setup/scripts/authoring_context.py 01dc74c03b3d7a2a73979394c3a3d5608375759e73415bd0fbc01b17d0d5aab3 keel-setup/scripts/fast_first_run.py 6ceba0ec23ff2e2023972d34805dc98ffc0e60349968db49363da0f08f82bc4a keel-setup/scripts/inventory.py 35858168e04738aed586856ff5bd4284b173ee20d829cca12bbdc8a319e8ec03 keel-setup/scripts/prepare_voice.py 0499357999da09f5d9ead351f5e9d6b7d1fb15162d25241f8a67ffd0353e6282 keel-setup/scripts/setup_state.py -d12266c786de8ebbc45295b428df35a88356167a2c58dee2e60f829b63067181 keel-setup/scripts/verify_execute.py +059a9145d7189ead4e459b2803cd257f938be950ea1d9295c5aa42e9f130931c keel-setup/scripts/verify_execute.py d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py -ac6f58d87ccbc60f652f97abe77c28b6c3f56ca8176a8b3b7bdba8bf043f0604 keel-setup/tests/test_authoring_context.py +0d7edbf3cd594c7cc4d2277c8c87aa43e4c6528a68c4886e1364466ec4114fdd keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py d681beacfb06738388025738b1e9deca0c43398b988b5c31e44ac88af92f35dc keel-setup/tests/test_fast_first_run.py f7297409fb8095ded69070a4e3c2a5cd9199a00a70a0a26df39e0ee608b1e6ca keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py 9d72d9877dea932680b0dd17f1c56a1df2ed02c84d585c5bf7a8440d72550232 keel-setup/tests/test_prepare_voice.py 87501ed31e812234f453de338d697848c84e1b21a036afd2eb3221acfb0a12a3 keel-setup/tests/test_setup_state.py -434fca83d18332ec05cc099329a1033244aa9ef7e6089742b82d47e220ce80df keel-setup/tests/test_verify_execute.py +3f0ac2541450f04aba6875cde762fa40f8ed3370944ad1389151bb3152bd98d6 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -dc253a27f34bf6d224d3f498b9ffe5ede6b955360500cc256d9bbea7ac6f3bd9 scripts/check_release_bundle.py +7da130b07ba9cecc4d6cc17f632c25e4c76e71d7c3ef65e60d6613c16596c685 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 92b11e2380bb588b2a00be8d5eae9665b4667747fd044278a65ec2a698de7889 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index d729df6..84c016a 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "be9eda7cf7cd8bea88473493901a649baad9a6faa4bfe0bb2b98573122f16dfb", + "product_source_sha256": "cbc48d16b1fec3049ab921347fb2426c849d0eaf76082db5a7672867b8ad390f", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/SKILL.md b/keel-setup/SKILL.md index ee97da0..fbcd5aa 100644 --- a/keel-setup/SKILL.md +++ b/keel-setup/SKILL.md @@ -440,8 +440,11 @@ matching, and surface them in `verification details` rather than in the default either is null, say there that exact correlation is unavailable; never infer it from a nearby model name or timestamp. -In interactive mode, the helper verifies the exact public bundle identity, allowlist, provenance, -product digest, and checksums before opening the no-echo TTY prompt. It fetches the authoritative +In interactive mode, the helper verifies the exact public bundle identity and compares every tracked +file with the caller-pinned Git commit before opening the no-echo TTY prompt. This authenticates the +release metadata and checksums reviewed by publication CI without importing or executing a bundled +verifier. The credential entrypoint and caller-supplied commit pin must themselves be trusted. +It fetches the authoritative verification profile, generates an integer timestamp and a distinct nonce inside each request, sends `input.messages`, performs the allow and deny requests, then refetches the profile and requires the same profile digest before reporting success. It prints only bounded classification fields. Exit `0` means diff --git a/keel-setup/scripts/authoring_context.py b/keel-setup/scripts/authoring_context.py index c5dc693..1b7224e 100644 --- a/keel-setup/scripts/authoring_context.py +++ b/keel-setup/scripts/authoring_context.py @@ -22,11 +22,11 @@ import argparse import decimal import getpass -import importlib.util import json import pathlib import re import secrets +import subprocess import sys import time import urllib.error @@ -238,25 +238,71 @@ def _contains_secret_argument(argv: list[str]) -> bool: def _verify_pinned_release(bundle_sha: str) -> None: - """Run the existing public release verifier before accepting a credential.""" + """Authenticate bundle data against the caller's pin without executing it. + + Keep this gate in each credential entrypoint: importing a sibling to decide + whether that sibling is trusted would run its code before authentication. + The entrypoint and the caller-supplied commit pin are the trust anchors. + """ try: + if re.fullmatch(r"[0-9a-f]{40}", bundle_sha) is None: + raise ValueError("invalid bundle SHA") bundle = pathlib.Path(__file__).resolve().parents[2] - helper_path = bundle / "keel-setup" / "scripts" / "fast_first_run.py" - spec = importlib.util.spec_from_file_location("keel_release_verifier", helper_path) - if spec is None or spec.loader is None: - raise RuntimeError("pinned release verifier is unavailable") - module = importlib.util.module_from_spec(spec) - previous_module = sys.modules.get(spec.name) - sys.modules[spec.name] = module - try: - spec.loader.exec_module(module) - finally: - if previous_module is None: - sys.modules.pop(spec.name, None) - else: - sys.modules[spec.name] = previous_module - module.verify_release(bundle, bundle_sha) + + def git(*args: str) -> bytes: + # No inherited Git configuration, object replacements, hooks, shell, + # credential, or network operations. All commands below only read. + result = subprocess.run( + ["git", "--no-replace-objects", "-c", "core.fsmonitor=false", + "-C", str(bundle), *args], + env={ + "PATH": "/usr/bin:/bin", + "LANG": "C", + "LC_ALL": "C", + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": "/dev/null", + "GIT_NO_LAZY_FETCH": "1", + "GIT_OPTIONAL_LOCKS": "0", + }, + capture_output=True, + timeout=20, + check=True, + ) + return result.stdout + + if git("rev-parse", "HEAD").decode().strip() != bundle_sha: + raise ValueError("bundle revision mismatch") + if git("remote", "get-url", "origin").decode().strip() not in { + "https://github.com/keelapi/keel-setup", + "https://github.com/keelapi/keel-setup.git", + "git@github.com:keelapi/keel-setup.git", + "ssh://git@github.com/keelapi/keel-setup.git", + }: + raise ValueError("unofficial bundle origin") + if (git("ls-files", "--others", "--exclude-standard") + or git("diff", "--cached", "--name-only", "--no-ext-diff", + "--no-textconv", bundle_sha)): + raise ValueError("bundle checkout is not clean") + + # Compare actual bytes, not index stat data or a mutable SHA256SUMS. + # This also catches tracked edits hidden by assume-unchanged flags. + entries = git("ls-tree", "-rz", bundle_sha).split(b"\0") + if len(entries) < 2: + raise ValueError("empty bundle tree") + for entry in entries[:-1]: + metadata, raw_path = entry.split(b"\t", 1) + mode, kind, oid = metadata.decode("ascii").split() + relative = pathlib.PurePosixPath(raw_path.decode("utf-8")) + if (mode not in {"100644", "100755"} or kind != "blob" + or relative.is_absolute() or ".." in relative.parts): + raise ValueError("unsupported bundle entry") + path = bundle.joinpath(*relative.parts) + if any(bundle.joinpath(*relative.parts[:i]).is_symlink() + for i in range(1, len(relative.parts) + 1)): + raise ValueError("symlink in bundle path") + if path.read_bytes() != git("cat-file", "blob", oid): + raise ValueError("bundle file differs from pinned bytes") except Exception as exc: raise RuntimeError("pinned release verification failed") from exc diff --git a/keel-setup/scripts/verify_execute.py b/keel-setup/scripts/verify_execute.py index 6b1856a..0b265a8 100644 --- a/keel-setup/scripts/verify_execute.py +++ b/keel-setup/scripts/verify_execute.py @@ -10,12 +10,12 @@ import argparse from datetime import datetime import getpass -import importlib.util import json import os import pathlib import re import secrets +import subprocess import sys import time import urllib.error @@ -137,25 +137,71 @@ def _contains_secret_argument(argv: list[str]) -> bool: def _verify_pinned_release(bundle_sha: str) -> None: - """Run the existing public release verifier before accepting a credential.""" + """Authenticate bundle data against the caller's pin without executing it. + + Keep this gate in each credential entrypoint: importing a sibling to decide + whether that sibling is trusted would run its code before authentication. + The entrypoint and the caller-supplied commit pin are the trust anchors. + """ try: + if re.fullmatch(r"[0-9a-f]{40}", bundle_sha) is None: + raise ValueError("invalid bundle SHA") bundle = pathlib.Path(__file__).resolve().parents[2] - helper_path = bundle / "keel-setup" / "scripts" / "fast_first_run.py" - spec = importlib.util.spec_from_file_location("keel_release_verifier", helper_path) - if spec is None or spec.loader is None: - raise RuntimeError("pinned release verifier is unavailable") - module = importlib.util.module_from_spec(spec) - previous_module = sys.modules.get(spec.name) - sys.modules[spec.name] = module - try: - spec.loader.exec_module(module) - finally: - if previous_module is None: - sys.modules.pop(spec.name, None) - else: - sys.modules[spec.name] = previous_module - module.verify_release(bundle, bundle_sha) + + def git(*args: str) -> bytes: + # No inherited Git configuration, object replacements, hooks, shell, + # credential, or network operations. All commands below only read. + result = subprocess.run( + ["git", "--no-replace-objects", "-c", "core.fsmonitor=false", + "-C", str(bundle), *args], + env={ + "PATH": "/usr/bin:/bin", + "LANG": "C", + "LC_ALL": "C", + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": "/dev/null", + "GIT_NO_LAZY_FETCH": "1", + "GIT_OPTIONAL_LOCKS": "0", + }, + capture_output=True, + timeout=20, + check=True, + ) + return result.stdout + + if git("rev-parse", "HEAD").decode().strip() != bundle_sha: + raise ValueError("bundle revision mismatch") + if git("remote", "get-url", "origin").decode().strip() not in { + "https://github.com/keelapi/keel-setup", + "https://github.com/keelapi/keel-setup.git", + "git@github.com:keelapi/keel-setup.git", + "ssh://git@github.com/keelapi/keel-setup.git", + }: + raise ValueError("unofficial bundle origin") + if (git("ls-files", "--others", "--exclude-standard") + or git("diff", "--cached", "--name-only", "--no-ext-diff", + "--no-textconv", bundle_sha)): + raise ValueError("bundle checkout is not clean") + + # Compare actual bytes, not index stat data or a mutable SHA256SUMS. + # This also catches tracked edits hidden by assume-unchanged flags. + entries = git("ls-tree", "-rz", bundle_sha).split(b"\0") + if len(entries) < 2: + raise ValueError("empty bundle tree") + for entry in entries[:-1]: + metadata, raw_path = entry.split(b"\t", 1) + mode, kind, oid = metadata.decode("ascii").split() + relative = pathlib.PurePosixPath(raw_path.decode("utf-8")) + if (mode not in {"100644", "100755"} or kind != "blob" + or relative.is_absolute() or ".." in relative.parts): + raise ValueError("unsupported bundle entry") + path = bundle.joinpath(*relative.parts) + if any(bundle.joinpath(*relative.parts[:i]).is_symlink() + for i in range(1, len(relative.parts) + 1)): + raise ValueError("symlink in bundle path") + if path.read_bytes() != git("cat-file", "blob", oid): + raise ValueError("bundle file differs from pinned bytes") except Exception as exc: raise RuntimeError("pinned release verification failed") from exc diff --git a/keel-setup/tests/test_authoring_context.py b/keel-setup/tests/test_authoring_context.py index 6105bd2..15c56f7 100644 --- a/keel-setup/tests/test_authoring_context.py +++ b/keel-setup/tests/test_authoring_context.py @@ -722,7 +722,7 @@ def setUp(self): def test_helper_is_standard_library_only(self): allowed = { "__future__", "argparse", "decimal", "getpass", "importlib", "json", - "pathlib", "re", "secrets", "sys", "time", "urllib", "warnings", "typing", + "pathlib", "re", "secrets", "subprocess", "sys", "time", "urllib", "warnings", "typing", } imports = [ line.strip() @@ -756,8 +756,14 @@ def test_helper_issues_no_state_changing_method(self): for verb in ('"POST"', '"PUT"', '"PATCH"', '"DELETE"'): self.assertNotIn(verb, self.source) - def test_helper_starts_no_subprocess(self): - self.assertNotIn("subprocess", self.source) + def test_subprocess_is_confined_to_read_only_release_gate(self): + gate = self.source.split("def _verify_pinned_release(", 1)[1].split( + "def _read_hidden_runtime_key", 1 + )[0] + self.assertEqual(self.source.count("subprocess.run("), 1) + self.assertIn("subprocess.run(", gate) + self.assertIn('"--no-replace-objects"', gate) + self.assertNotIn("exec_module", self.source) diff --git a/keel-setup/tests/test_verify_execute.py b/keel-setup/tests/test_verify_execute.py index f788ab1..1835313 100644 --- a/keel-setup/tests/test_verify_execute.py +++ b/keel-setup/tests/test_verify_execute.py @@ -577,27 +577,6 @@ def test_release_failure_stops_before_credential_prompt(self): prompt.assert_not_called() self.assertEqual(err.getvalue(), "pinned release verification failed\n") - def test_release_verifier_loads_a_dataclass_helper_before_prompt(self): - with tempfile.TemporaryDirectory() as temp_dir: - bundle = pathlib.Path(temp_dir) - scripts = bundle / "keel-setup" / "scripts" - scripts.mkdir(parents=True) - helper = scripts / "fast_first_run.py" - helper.write_text( - "from __future__ import annotations\n" - "from dataclasses import dataclass\n" - "@dataclass(frozen=True)\n" - "class Marker:\n" - " value: str\n" - "def verify_release(bundle, expected_sha):\n" - " assert bundle == __import__('pathlib').Path(__file__).resolve().parents[2]\n" - " assert expected_sha == 'a' * 40\n", - encoding="utf-8", - ) - synthetic_script = scripts / "verify_execute.py" - with mock.patch.object(verify_execute, "__file__", str(synthetic_script)): - verify_execute._verify_pinned_release("a" * 40) - def test_base_url_accepts_only_production_origin_or_explicit_loopback_port(self): accepted = [ "https://api.keelapi.com", "https://api.keelapi.com/", "https://api.keelapi.com:443", @@ -636,5 +615,151 @@ def test_unexpected_upstream_echo_is_redacted(self): self.assertNotIn(sentinel, json.dumps(redacted)) +class PinnedReleaseGateTest(unittest.TestCase): + """Exercise both credential gates against real disposable Git repositories.""" + + def setUp(self): + spec = importlib.util.spec_from_file_location( + "gate_authoring_context", SCRIPT.with_name("authoring_context.py") + ) + self.authoring = importlib.util.module_from_spec(spec) + spec.loader.exec_module(self.authoring) + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.bundle = pathlib.Path(self.temp.name) + scripts = self.bundle / "keel-setup/scripts" + scripts.mkdir(parents=True) + self.sibling = scripts / "fast_first_run.py" + self.sibling.write_text("def verify_release(*args): pass\n") + (self.bundle / "scripts").mkdir() + self.checker = self.bundle / "scripts/check_release_bundle.py" + self.checker.write_text("raise AssertionError('must not execute checker')\n") + self.git("init", "-q") + self.git("config", "user.name", "Gate test") + self.git("config", "user.email", "gate@example.invalid") + self.git("remote", "add", "origin", "https://github.com/keelapi/keel-setup.git") + self.git("add", ".") + self.git("commit", "-qm", "fixture") + self.pin = self.git("rev-parse", "HEAD").strip() + + def git(self, *args): + return subprocess.run( + ["git", "-C", str(self.bundle), *args], check=True, + capture_output=True, text=True, + ).stdout + + def gates(self): + return (verify_execute, self.authoring) + + def check_gate(self, module, pin=None): + with mock.patch.object(module, "__file__", str(self.sibling.with_name("trusted.py"))): + module._verify_pinned_release(self.pin if pin is None else pin) + + def test_clean_pinned_bundle_never_executes_siblings(self): + for module in self.gates(): + with self.subTest(module=module.__name__): + self.check_gate(module) + + def test_tampered_sibling_cannot_patch_prompt_or_network(self): + marker = self.bundle / "executed" + payload = ( + "import pathlib, getpass, urllib.request\n" + f"pathlib.Path({str(marker)!r}).touch()\n" + "getpass.getpass = lambda *a, **k: 'stolen'\n" + "urllib.request.build_opener = lambda *a: None\n" + "def verify_release(*args): pass\n" + ) + original_prompt = verify_execute.getpass.getpass + original_opener = urllib.request.build_opener + self.sibling.write_text(payload) + # Git cleanliness alone misses both of these flags. + for flag in ("--assume-unchanged", "--skip-worktree"): + self.git("update-index", flag, "keel-setup/scripts/fast_first_run.py") + for module in self.gates(): + with self.subTest(flag=flag, module=module.__name__): + with mock.patch.object(module, "__file__", str(self.sibling.with_name("trusted.py"))), \ + mock.patch.object(module, "_read_hidden_runtime_key") as prompt, \ + mock.patch.object(module, "_open") as network, \ + contextlib.redirect_stderr(io.StringIO()): + args = ["--bundle-sha", self.pin] + if module is verify_execute: + args.append("--hidden-input") + self.assertEqual(module.main(args), 2) + prompt.assert_not_called() + network.assert_not_called() + self.assertFalse(marker.exists()) + self.assertIs(verify_execute.getpass.getpass, original_prompt) + self.assertIs(urllib.request.build_opener, original_opener) + self.git("update-index", "--no-assume-unchanged", "--no-skip-worktree", "keel-setup/scripts/fast_first_run.py") + + def test_tampered_checker_hidden_from_status_is_rejected(self): + self.checker.write_text("raise AssertionError('tampered checker executed')\n") + self.git("update-index", "--assume-unchanged", "scripts/check_release_bundle.py") + for module in self.gates(): + with self.subTest(module=module.__name__), self.assertRaises(RuntimeError): + self.check_gate(module) + + def test_symlink_even_to_identical_bytes_is_rejected(self): + target = self.bundle / "target" + target.write_bytes(self.sibling.read_bytes()) + self.sibling.unlink() + self.sibling.symlink_to(target) + self.git("update-index", "--assume-unchanged", "keel-setup/scripts/fast_first_run.py") + target.rename(self.bundle / ".git/target") + self.sibling.unlink() + self.sibling.symlink_to(self.bundle / ".git/target") + for module in self.gates(): + with self.subTest(module=module.__name__), self.assertRaises(RuntimeError): + self.check_gate(module) + + def test_invalid_pin_origin_and_dirty_bundle_are_rejected(self): + for pin in ("a" * 40, self.pin.upper(), "HEAD", ""): + for module in self.gates(): + with self.subTest(pin=pin, module=module.__name__), self.assertRaises(RuntimeError): + self.check_gate(module, pin) + self.git("remote", "set-url", "origin", "https://example.invalid/bundle") + for module in self.gates(): + with self.assertRaises(RuntimeError): + self.check_gate(module) + self.git("remote", "set-url", "origin", "https://github.com/keelapi/keel-setup.git") + (self.bundle / "untracked").touch() + for module in self.gates(): + with self.assertRaises(RuntimeError): + self.check_gate(module) + + def test_replacement_objects_cannot_authenticate_modified_files(self): + original = self.git("rev-parse", "HEAD:keel-setup/scripts/fast_first_run.py").strip() + self.sibling.write_text("def verify_release(*args): return 'forged'\n") + replacement = self.git("hash-object", "-w", str(self.sibling)).strip() + self.git("replace", original, replacement) + self.git("update-index", "--assume-unchanged", "keel-setup/scripts/fast_first_run.py") + for module in self.gates(): + with self.subTest(module=module.__name__), self.assertRaises(RuntimeError): + self.check_gate(module) + + def test_submodule_is_not_an_authenticated_regular_file(self): + self.git("update-index", "--add", "--cacheinfo", f"160000,{self.pin},nested") + self.git("commit", "-qm", "submodule fixture") + self.pin = self.git("rev-parse", "HEAD").strip() + for module in self.gates(): + with self.subTest(module=module.__name__), self.assertRaises(RuntimeError): + self.check_gate(module) + + def test_local_fsmonitor_hook_is_never_executed(self): + marker = self.bundle / "hook-executed" + hook = self.bundle / ".git/fsmonitor" + hook.write_text(f"#!/bin/sh\ntouch {marker}\n") + hook.chmod(0o755) + self.git("config", "core.fsmonitor", str(hook)) + for module in self.gates(): + with self.subTest(module=module.__name__): + self.check_gate(module) + self.assertFalse(marker.exists()) + + def test_gate_implementations_remain_identical(self): + self.assertEqual(inspect.getsource(verify_execute._verify_pinned_release), + inspect.getsource(self.authoring._verify_pinned_release)) + + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 111956e..1ecd581 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "be9eda7cf7cd8bea88473493901a649baad9a6faa4bfe0bb2b98573122f16dfb" +PRODUCT_SOURCE_SHA256 = "cbc48d16b1fec3049ab921347fb2426c849d0eaf76082db5a7672867b8ad390f" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From 95217847d194781bcecd8a23f3aa061e151f107e Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:34:27 -0800 Subject: [PATCH 2/5] Fix setup bundle worktree root verification --- SHA256SUMS | 8 ++-- SOURCE.json | 2 +- keel-setup/scripts/fast_first_run.py | 11 ++++- keel-setup/tests/test_fast_first_run.py | 54 +++++++++++++++++++++++++ scripts/check_release_bundle.py | 2 +- 5 files changed, 69 insertions(+), 8 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index fd23da2..ac966cd 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -d1429e0528c516407d30533bd107fc7fae2790e7f2637a5ba02c8e44f39e9897 SOURCE.json +a4f979ebb7e99a6a5ea500cae34dad651ce8d4aad21937c10a5686a1c44606bf SOURCE.json 41f17c2c3b0d7ab61fd6c985c553bfe6df4df12be8eeb1feaa60437a7ee30ac1 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -23,7 +23,7 @@ b8387c9667d558cf76ac0c77ec586121955647a24cb1c863d6665edb205c0f28 keel-setup/SKI 7ef2361f3f10601f9a4d3681d04c8538836c37448787262b26e82bf18bcbbc70 keel-setup/reference/unified-execute-request.contract.json c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/reference/voice-gateway.md 85087e7fcc58ae504feef3fb06cf1efeaa10c6c943cbbee1c5a509edf49a732c keel-setup/scripts/authoring_context.py -01dc74c03b3d7a2a73979394c3a3d5608375759e73415bd0fbc01b17d0d5aab3 keel-setup/scripts/fast_first_run.py +ff4786d139dbad47b682abee5a3fbf34cbd019f3cd19b56b6c02490a59d01d4a keel-setup/scripts/fast_first_run.py 6ceba0ec23ff2e2023972d34805dc98ffc0e60349968db49363da0f08f82bc4a keel-setup/scripts/inventory.py 35858168e04738aed586856ff5bd4284b173ee20d829cca12bbdc8a319e8ec03 keel-setup/scripts/prepare_voice.py 0499357999da09f5d9ead351f5e9d6b7d1fb15162d25241f8a67ffd0353e6282 keel-setup/scripts/setup_state.py @@ -31,14 +31,14 @@ c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/ref d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 0d7edbf3cd594c7cc4d2277c8c87aa43e4c6528a68c4886e1364466ec4114fdd keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py -d681beacfb06738388025738b1e9deca0c43398b988b5c31e44ac88af92f35dc keel-setup/tests/test_fast_first_run.py +987e0b9332d0572a462f04fb849584b3830fa36fa2552c5d53a4aa915e801754 keel-setup/tests/test_fast_first_run.py f7297409fb8095ded69070a4e3c2a5cd9199a00a70a0a26df39e0ee608b1e6ca keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py 9d72d9877dea932680b0dd17f1c56a1df2ed02c84d585c5bf7a8440d72550232 keel-setup/tests/test_prepare_voice.py 87501ed31e812234f453de338d697848c84e1b21a036afd2eb3221acfb0a12a3 keel-setup/tests/test_setup_state.py 3f0ac2541450f04aba6875cde762fa40f8ed3370944ad1389151bb3152bd98d6 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -7da130b07ba9cecc4d6cc17f632c25e4c76e71d7c3ef65e60d6613c16596c685 scripts/check_release_bundle.py +dd9bfb5c2a9c5d75731a81c4ba80e151c9752748449dc443c9b3f39b46585ed0 scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 92b11e2380bb588b2a00be8d5eae9665b4667747fd044278a65ec2a698de7889 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index 84c016a..53ef8af 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "cbc48d16b1fec3049ab921347fb2426c849d0eaf76082db5a7672867b8ad390f", + "product_source_sha256": "1ab58514355fe16d86e209920ae80596a83efd286c541387e9071892212ce89d", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/scripts/fast_first_run.py b/keel-setup/scripts/fast_first_run.py index f71845b..c6b62d8 100644 --- a/keel-setup/scripts/fast_first_run.py +++ b/keel-setup/scripts/fast_first_run.py @@ -124,11 +124,11 @@ def _run( raise PipelineFailure("validation_failed", f"bounded command failed: {argv[0]}: {exc}") from exc -def _git(repo: pathlib.Path, *args: str, timeout: int = 10) -> str: +def _git(repo: pathlib.Path, *args: str, timeout: int = 10, path_output: bool = False) -> str: result = _run(["git", "-C", str(repo), *args], cwd=repo, timeout=timeout) if result.returncode != 0: raise PipelineFailure("validation_failed", f"git {' '.join(args)} failed") - return result.stdout.strip() + return result.stdout.removesuffix("\n") if path_output else result.stdout.strip() def _load_module(name: str, path: pathlib.Path): @@ -147,6 +147,12 @@ def verify_release(bundle: pathlib.Path, expected_sha: str) -> dict[str, Any]: raise PipelineFailure("untrusted_bundle", "bundle SHA must be 40 lowercase hexadecimal characters") if not bundle.is_dir(): raise PipelineFailure("untrusted_bundle", "bundle path is not a directory") + bundle = bundle.resolve() + # Git discovers enclosing repositories; bind its facts to the directory + # supplying executable bundle files before inspecting or running those files. + worktree_root = pathlib.Path(_git(bundle, "rev-parse", "--show-toplevel", path_output=True)).resolve() + if bundle != worktree_root: + raise PipelineFailure("untrusted_bundle", "bundle path must be the Git worktree root") head = _git(bundle, "rev-parse", "HEAD") if head != expected_sha: raise PipelineFailure("untrusted_bundle", "bundle checkout does not match the requested immutable SHA") @@ -894,6 +900,7 @@ def run_pipeline(bundle: pathlib.Path, bundle_sha: str, repo: pathlib.Path) -> d originals: dict[pathlib.PurePosixPath, bytes | None] = {} edited = False try: + bundle = bundle.resolve() mark = time.perf_counter() trust = verify_release(bundle, bundle_sha) timings["release_trust_ms"] = round((time.perf_counter() - mark) * 1000, 3) diff --git a/keel-setup/tests/test_fast_first_run.py b/keel-setup/tests/test_fast_first_run.py index ec82136..edd4014 100644 --- a/keel-setup/tests/test_fast_first_run.py +++ b/keel-setup/tests/test_fast_first_run.py @@ -95,6 +95,60 @@ def _repo(self, app_source: str = fixtures.GOLDEN_APP, *, with_test: bool = True def _run(self, root: pathlib.Path) -> dict[str, object]: return fast.run_pipeline(self.bundle, self.bundle_sha, root) + def test_nested_bundle_is_rejected_before_checker_or_helper_execution(self): + with tempfile.TemporaryDirectory() as temporary: + parent = pathlib.Path(temporary) / "release" + _git(pathlib.Path(temporary), "clone", "-q", str(self.bundle), str(parent)) + _git(parent, "remote", "set-url", "origin", "https://github.com/keelapi/keel-setup.git") + (parent / ".git/info/exclude").write_text(".worktrees/\n", encoding="utf-8") + child = parent / ".worktrees/fake" + (child / "scripts").mkdir(parents=True) + marker = pathlib.Path(temporary) / "checker-ran" + (child / "scripts/check_release_bundle.py").write_text( + f"from pathlib import Path\nPath({str(marker)!r}).touch()\n" + "print('PASS: public setup bundle (fake)')\n", encoding="utf-8", + ) + shutil.copy2(parent / "SOURCE.json", child / "SOURCE.json") + alias = pathlib.Path(temporary) / "child-alias" + alias.symlink_to(child, target_is_directory=True) + self.assertEqual(_git(child, "rev-parse", "HEAD"), self.bundle_sha) + self.assertEqual(_git(child, "status", "--porcelain=v1", "--untracked-files=all"), "") + for selected in (child, alias, child / "scripts/.."): + with self.subTest(selected=selected): + with self.assertRaisesRegex(fast.PipelineFailure, "worktree root"): + fast.verify_release(selected, self.bundle_sha) + with mock.patch.object(fast, "_load_module") as load: + result = fast.run_pipeline(selected, self.bundle_sha, parent) + self.assertEqual(result["outcome"], "untrusted_bundle", result) + load.assert_not_called() + self.assertFalse(marker.exists()) + + def test_release_root_aliases_remain_trusted(self): + with tempfile.TemporaryDirectory() as temporary: + alias = pathlib.Path(temporary) / "release-alias" + alias.symlink_to(self.bundle, target_is_directory=True) + relative = pathlib.Path(os.path.relpath(self.bundle)) + for selected in (self.bundle, alias, relative): + with self.subTest(selected=selected): + self.assertEqual(fast.verify_release(selected, self.bundle_sha)["status"], "trusted") + + def test_linked_worktree_root_remains_trusted(self): + with tempfile.TemporaryDirectory() as temporary: + parent = pathlib.Path(temporary) / "release" + _git(pathlib.Path(temporary), "clone", "-q", str(self.bundle), str(parent)) + _git(parent, "remote", "set-url", "origin", "https://github.com/keelapi/keel-setup.git") + worktree = pathlib.Path(temporary) / "linked" + _git(parent, "worktree", "add", "--detach", str(worktree), self.bundle_sha) + self.assertTrue((worktree / ".git").is_file()) + self.assertEqual(fast.verify_release(worktree, self.bundle_sha)["status"], "trusted") + + def test_release_root_with_trailing_whitespace_remains_trusted(self): + with tempfile.TemporaryDirectory() as temporary: + root = pathlib.Path(temporary) / "release \n" + _git(pathlib.Path(temporary), "clone", "-q", str(self.bundle), str(root)) + _git(root, "remote", "set-url", "origin", "https://github.com/keelapi/keel-setup.git") + self.assertEqual(fast.verify_release(root, self.bundle_sha)["status"], "trusted") + def test_trivial_openai_responses_summarizer_is_ready_for_human(self): root = self._repo() result = self._run(root) diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 1ecd581..697edb8 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "cbc48d16b1fec3049ab921347fb2426c849d0eaf76082db5a7672867b8ad390f" +PRODUCT_SOURCE_SHA256 = "1ab58514355fe16d86e209920ae80596a83efd286c541387e9071892212ce89d" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From a4a60cb4dadf1338a508fb9631c55ae636e8b2a4 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:36:16 -0800 Subject: [PATCH 3/5] Bind setup fallback helpers to authenticated bundle root --- SHA256SUMS | 8 +-- SOURCE.json | 2 +- keel-setup/SKILL.md | 42 ++++++++--- keel-setup/tests/test_inventory.py | 108 ++++++++++++++++++++++++++++- scripts/check_release_bundle.py | 2 +- 5 files changed, 147 insertions(+), 15 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index ac966cd..7b90238 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -a4f979ebb7e99a6a5ea500cae34dad651ce8d4aad21937c10a5686a1c44606bf SOURCE.json +51cdefca5c7cb80b388fb5a1a939b8cfb0bed05dc0486bc6c70727641f620b52 SOURCE.json 41f17c2c3b0d7ab61fd6c985c553bfe6df4df12be8eeb1feaa60437a7ee30ac1 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -16,7 +16,7 @@ a4f979ebb7e99a6a5ea500cae34dad651ce8d4aad21937c10a5686a1c44606bf SOURCE.json b5711d319ef939c7522df53ffc3dea7c4dcc371537dff4cc7307f2a4bc59dffb keel-policy/tests/test_authoring_context_consumption.py 820069a6ce02f74dccc4f57a5788359b1377520330d00ba88471d60fec901f17 keel-policy/tests/test_basic_profile_fields.py 322b430367e859dae341e9c225be34c6c5272c481074e7b1ae2242db527e1cbe keel-policy/tests/test_validate_enforceability_report.py -b8387c9667d558cf76ac0c77ec586121955647a24cb1c863d6665edb205c0f28 keel-setup/SKILL.md +d63952dd7d035b0805aef4d4aef928173424e8305c122cd7836a32a7557637f6 keel-setup/SKILL.md 2b9c2490e921e83b83372a09e422a30f0f7ee338a2809b8e07edbd381d9eb650 keel-setup/reference/coverage.schema.json 70a69dcab29f61aaa3f96de5f65854fca63c4549ddc20d84ee00e102fc68c691 keel-setup/reference/integration_profiles.v1.json 9739501499b286d40f356af9c0378bbdcde41a364be083ccbc34adb000575160 keel-setup/reference/setup-state.schema.json @@ -32,13 +32,13 @@ d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tes 0d7edbf3cd594c7cc4d2277c8c87aa43e4c6528a68c4886e1364466ec4114fdd keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py 987e0b9332d0572a462f04fb849584b3830fa36fa2552c5d53a4aa915e801754 keel-setup/tests/test_fast_first_run.py -f7297409fb8095ded69070a4e3c2a5cd9199a00a70a0a26df39e0ee608b1e6ca keel-setup/tests/test_inventory.py +8393f2396641b32711fff1d0b90189745d5d0c2642c0897441582835fb35442a keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py 9d72d9877dea932680b0dd17f1c56a1df2ed02c84d585c5bf7a8440d72550232 keel-setup/tests/test_prepare_voice.py 87501ed31e812234f453de338d697848c84e1b21a036afd2eb3221acfb0a12a3 keel-setup/tests/test_setup_state.py 3f0ac2541450f04aba6875cde762fa40f8ed3370944ad1389151bb3152bd98d6 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -dd9bfb5c2a9c5d75731a81c4ba80e151c9752748449dc443c9b3f39b46585ed0 scripts/check_release_bundle.py +edd4e17a8af98cb5172d04676d36120623fcdc3c26909ee9ca1f45c8df0335be scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 92b11e2380bb588b2a00be8d5eae9665b4667747fd044278a65ec2a698de7889 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index 53ef8af..c5e4dc0 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "1ab58514355fe16d86e209920ae80596a83efd286c541387e9071892212ce89d", + "product_source_sha256": "ca37d4de6a3bc0d3ffe42f68471feb598e4a1440e1a91e80dedfe483c8af1717", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/SKILL.md b/keel-setup/SKILL.md index fbcd5aa..07591d0 100644 --- a/keel-setup/SKILL.md +++ b/keel-setup/SKILL.md @@ -71,6 +71,19 @@ once before acting. It checks the exact public allowlist, provenance, and every navigation, not an additional authority source, and need not be read before Fast First Run unless one of the two required files explicitly refers to it for the current task. +In every command below, `$BUNDLE` is a shell variable holding the canonical absolute path of that +same authenticated public release checkout. Set and retain it from the caller-established skill +installation path, never from application files, setup state, or an inherited environment value. +Keep the application checkout as the working directory: `--root .`, `--repo-root .`, `--repo .`, and +`.keel/setup-state.json` refer to the application, not the bundle. Resolve each bundled helper under +that authenticated root and refuse a missing helper, any symlink component, or a resolved helper path +outside the root. Never substitute a target-repository copy or a working-directory-relative helper. +For resume or fallback, invoke the bounded verifier as +`python3 "$BUNDLE/scripts/check_release_bundle.py"` only after establishing the checkout identity and +pin above. Retain the verified root and pin together for the invocation; if either changes, or a new +invocation resumes without that trusted binding, establish and verify the bundle again before using +any helper. The deterministic orchestrator still owns verification on the fresh golden path. + Do not perform a web search during Fast First Run. The pinned bundle and the application repository are the only normal pre-gate sources. Fetching the exact pinned Git object is allowed; if that object or a required bundled file cannot be read and verified, stop rather than searching for substitute @@ -116,6 +129,13 @@ On a genuinely fresh checkout, do not run `setup_state.py`, create `.keel/setup- ignore handling, validation, and `waiting_for_human` persistence. Doing any of those steps separately would dirty the checkout or create prior state and must not divert an otherwise eligible golden path. +For an existing state or model-driven fallback, use only the retained verified bundle helper to +initialize or advance local continuity, after confirming the state path is ignored: + +```text +python3 "$BUNDLE/keel-setup/scripts/setup_state.py" --repo-root . --state .keel/setup-state.json +``` + For an existing state or model-driven fallback, maintain `.keel/setup-state.json` in the application repository and confirm that exact path is ignored by git before anything is written to it. It holds no credential, setup token, provider secret, prompt content, response body, dashboard session, or local claim of mapping authority. It records only schema @@ -158,8 +178,8 @@ After the pinned checkout and the single full read of the Constitution and this bundle's deterministic orchestrator immediately, before state handling or model-driven discovery: ```text -python3 BUNDLE/keel-setup/scripts/fast_first_run.py \ - --bundle BUNDLE --bundle-sha 40_HEX_SHA --repo . +python3 "$BUNDLE/keel-setup/scripts/fast_first_run.py" \ + --bundle "$BUNDLE" --bundle-sha 40_HEX_SHA --repo . ``` It supports exactly one clean Python application shape: one non-streaming official OpenAI SDK @@ -205,7 +225,7 @@ allows it; never broaden the helper's claimed support from resemblance alone. 2. Run the bounded targeted search first: ```text - python3 keel-setup/scripts/inventory.py --fast --root . + python3 "$BUNDLE/keel-setup/scripts/inventory.py" --fast --root . ``` It reports request-site candidates, selection status, scan limits, and elapsed milliseconds without @@ -256,12 +276,12 @@ allows it; never broaden the helper's claimed support from resemblance alone. paths, then validate the state file and issue the concise first handoff: ```text - python3 keel-setup/scripts/setup_state.py --repo-root . --state .keel/setup-state.json \ + python3 "$BUNDLE/keel-setup/scripts/setup_state.py" --repo-root . --state .keel/setup-state.json \ --mark-waiting-for-human --provider PROVIDER --pinned-skill-ref 40_HEX_SHA \ --application-revision REVISION --changed-path PATH \ --focused-check syntax_or_compile --focused-check fail_closed_integration_review \ --focused-check adjacent_bypass_search - python3 keel-setup/scripts/setup_state.py --repo-root . \ + python3 "$BUNDLE/keel-setup/scripts/setup_state.py" --repo-root . \ --state .keel/setup-state.json --validate-only ``` @@ -432,7 +452,7 @@ profile is configuration evidence, not runtime proof. The final command is: ```text -python3 BUNDLE/keel-setup/scripts/verify_execute.py --hidden-input --bundle-sha 40_HEX_SHA +python3 "$BUNDLE/keel-setup/scripts/verify_execute.py" --hidden-input --bundle-sha 40_HEX_SHA ``` Retain the script's non-secret `request_id` and `permit_id` values for exact dashboard and Permit @@ -721,8 +741,14 @@ outstanding, and do not treat a clean close as whole-application assurance. ## Post-gate deep assurance After the human gate is satisfied and the stable verification pair and narrow application path have been -attempted, perform the deferred assurance work. Run `scripts/inventory.py` without `--fast`, or inspect -equivalently, across model SDKs and direct HTTP calls, MCP servers/clients/tool registrations/handlers, +attempted, perform the deferred assurance work. Run the same verified inventory helper without +`--fast`, or inspect equivalently: + +```text +python3 "$BUNDLE/keel-setup/scripts/inventory.py" --root . +``` + +Cover model SDKs and direct HTTP calls, MCP servers/clients/tool registrations/handlers, background work, nested calls, direct handler paths, streaming, credentials, and egress signals. Update application setup documentation here when the repository needs it. Protocol-double and diff --git a/keel-setup/tests/test_inventory.py b/keel-setup/tests/test_inventory.py index 1c38ec2..1f791db 100644 --- a/keel-setup/tests/test_inventory.py +++ b/keel-setup/tests/test_inventory.py @@ -2,7 +2,13 @@ import importlib.util import json +import os import pathlib +import re +import shlex +import shutil +import subprocess +import sys import tempfile import unittest @@ -413,7 +419,8 @@ def test_fresh_golden_path_owns_trust_ignore_and_state_initialization(self): deterministic = text.index("### Deterministic golden path") fallback = text.index("### Model-driven fallback") direct_state_command = text.index( - "python3 keel-setup/scripts/setup_state.py --repo-root . --state .keel/setup-state.json" + 'python3 "$BUNDLE/keel-setup/scripts/setup_state.py" --repo-root . --state .keel/setup-state.json', + fallback, ) self.assertGreater(direct_state_command, fallback) @@ -594,5 +601,104 @@ def test_skill_retains_execution_and_authority_boundaries(self): self.assertIn(required, text) +class PublishedHelperBoundaryTest(unittest.TestCase): + """Run the documented commands with a hostile application working directory.""" + + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = pathlib.Path(temporary.name) + self.app = self.root / "application with spaces" + self.app.mkdir() + self.bundle = self.root / "verified bundle with spaces" + self.bundle.mkdir() + source = SKILL.parents[1] + for relative in ("keel-setup/scripts", "keel-setup/reference", "shared/scripts"): + shutil.copytree(source / relative, self.bundle / relative) + self.marker = self.app / "counterfeit-executed" + for relative in ("keel-setup/scripts/inventory.py", "keel-setup/scripts/setup_state.py", + "scripts/inventory.py"): + target = self.app / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text( + "from pathlib import Path\n" + f"Path({str(self.marker)!r}).touch()\n" + "print('forged setup result')\n", encoding="utf-8", + ) + (self.app / ".gitignore").write_text(".keel/\n", encoding="utf-8") + _write_openai_seam(self.app / "app.py") + self.git("init", "-q") + self.git("add", ".") + self.git("-c", "user.name=Test", "-c", "user.email=test@example.invalid", + "commit", "-qm", "application") + (self.app / "prepared.py").write_text( + "def route(payload):\n return post('/v1/execute', json=payload)\n", + encoding="utf-8", + ) + self.revision = self.git("rev-parse", "HEAD").strip() + + def git(self, *args): + return subprocess.run(["git", "-C", str(self.app), *args], check=True, + capture_output=True, text=True).stdout + + def commands(self, helper): + text = SKILL.read_text(encoding="utf-8").replace("\\\n", " ") + return [line.strip() for line in text.splitlines() + if line.strip().startswith("python3 ") and f"/{helper}.py" in line] + + def run_command(self, command): + args = shlex.split(command) + args[0] = sys.executable + replacements = {"$BUNDLE": str(self.bundle), "40_HEX_SHA": "a" * 40, + "PROVIDER": "openai", "REVISION": self.revision, + "PATH": "prepared.py"} + args = [replacements.get(arg, arg.replace("$BUNDLE", str(self.bundle))) for arg in args] + result = subprocess.run(args, cwd=self.app, capture_output=True, text=True, + env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}, timeout=20) + self.assertFalse(self.marker.exists(), "published command executed a target-side helper") + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout + + def test_inventory_commands_ignore_counterfeits_and_scan_application(self): + commands = self.commands("inventory") + self.assertTrue(commands) + for command in commands: + with self.subTest(command=command): + report = json.loads(self.run_command(command)) + self.assertIn("app.py", json.dumps(report)) + self.assertTrue(any("--fast" not in command for command in commands), + "deep inventory must also publish a rooted command") + + def test_state_commands_ignore_counterfeits_and_preserve_application_state(self): + state = self.app / ".keel/setup-state.json" + commands = self.commands("setup_state") + self.assertGreaterEqual(len(commands), 2) + for command in commands: + self.run_command(command) + updated = json.loads(state.read_text()) + self.assertEqual(updated["stage"], "waiting_for_human") + self.assertEqual(updated["changed_paths"], ["prepared.py"]) + self.assertFalse((self.bundle / ".keel").exists()) + + def test_symlinked_target_helpers_are_also_ignored(self): + payload = self.app / "payload.py" + payload.write_bytes((self.app / "keel-setup/scripts/inventory.py").read_bytes()) + for relative in ("keel-setup/scripts/inventory.py", "keel-setup/scripts/setup_state.py", + "scripts/inventory.py"): + target = self.app / relative + target.unlink() + target.symlink_to(payload) + self.test_inventory_commands_ignore_counterfeits_and_scan_application() + self.test_state_commands_ignore_counterfeits_and_preserve_application_state() + + def test_all_published_helper_commands_use_the_authenticated_root(self): + text = SKILL.read_text(encoding="utf-8") + for line in text.splitlines(): + if line.strip().startswith("python3 "): + self.assertRegex(line.strip(), r'^python3 "\$BUNDLE/[^" ]+\.py"(?: |$)') + self.assertIn("canonical absolute", text) + self.assertIn("symlink", text) + + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 697edb8..f026182 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "1ab58514355fe16d86e209920ae80596a83efd286c541387e9071892212ce89d" +PRODUCT_SOURCE_SHA256 = "ca37d4de6a3bc0d3ffe42f68471feb598e4a1440e1a91e80dedfe483c8af1717" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From 25c25da21e6e9a470bd6c7b0105e1b14f61a9169 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:35:29 -0800 Subject: [PATCH 4/5] fix: prevent target code execution during setup preparation --- SHA256SUMS | 14 +++--- SOURCE.json | 2 +- keel-setup/SKILL.md | 42 +++++++++++++---- keel-setup/scripts/fast_first_run.py | 25 ++++++----- keel-setup/scripts/setup_state.py | 4 +- keel-setup/tests/test_fast_first_run.py | 60 ++++++++++++++++++++++++- keel-setup/tests/test_inventory.py | 3 +- scripts/check_release_bundle.py | 2 +- 8 files changed, 118 insertions(+), 34 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index 7b90238..fbc9722 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,7 +2,7 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -51cdefca5c7cb80b388fb5a1a939b8cfb0bed05dc0486bc6c70727641f620b52 SOURCE.json +87a7b35e3d87d58c6faa7aa0ce11f4575364b60a1f5564b62e6e0aa0a40a06fd SOURCE.json 41f17c2c3b0d7ab61fd6c985c553bfe6df4df12be8eeb1feaa60437a7ee30ac1 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json @@ -16,29 +16,29 @@ b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore b5711d319ef939c7522df53ffc3dea7c4dcc371537dff4cc7307f2a4bc59dffb keel-policy/tests/test_authoring_context_consumption.py 820069a6ce02f74dccc4f57a5788359b1377520330d00ba88471d60fec901f17 keel-policy/tests/test_basic_profile_fields.py 322b430367e859dae341e9c225be34c6c5272c481074e7b1ae2242db527e1cbe keel-policy/tests/test_validate_enforceability_report.py -d63952dd7d035b0805aef4d4aef928173424e8305c122cd7836a32a7557637f6 keel-setup/SKILL.md +aa5a4d45d0979a0a09ab9e0dc5f2b3b056da6a334086c54e7826a8acc98c73b6 keel-setup/SKILL.md 2b9c2490e921e83b83372a09e422a30f0f7ee338a2809b8e07edbd381d9eb650 keel-setup/reference/coverage.schema.json 70a69dcab29f61aaa3f96de5f65854fca63c4549ddc20d84ee00e102fc68c691 keel-setup/reference/integration_profiles.v1.json 9739501499b286d40f356af9c0378bbdcde41a364be083ccbc34adb000575160 keel-setup/reference/setup-state.schema.json 7ef2361f3f10601f9a4d3681d04c8538836c37448787262b26e82bf18bcbbc70 keel-setup/reference/unified-execute-request.contract.json c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/reference/voice-gateway.md 85087e7fcc58ae504feef3fb06cf1efeaa10c6c943cbbee1c5a509edf49a732c keel-setup/scripts/authoring_context.py -ff4786d139dbad47b682abee5a3fbf34cbd019f3cd19b56b6c02490a59d01d4a keel-setup/scripts/fast_first_run.py +530fc920965083baf4a791236c443d8c5db1fbe45e949b28cd7cbee2ff2a2b12 keel-setup/scripts/fast_first_run.py 6ceba0ec23ff2e2023972d34805dc98ffc0e60349968db49363da0f08f82bc4a keel-setup/scripts/inventory.py 35858168e04738aed586856ff5bd4284b173ee20d829cca12bbdc8a319e8ec03 keel-setup/scripts/prepare_voice.py -0499357999da09f5d9ead351f5e9d6b7d1fb15162d25241f8a67ffd0353e6282 keel-setup/scripts/setup_state.py +3dd96fcade09d4e39b29e400c4681325ab8edbec697441ccc761fe98b9d39462 keel-setup/scripts/setup_state.py 059a9145d7189ead4e459b2803cd257f938be950ea1d9295c5aa42e9f130931c keel-setup/scripts/verify_execute.py d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py 0d7edbf3cd594c7cc4d2277c8c87aa43e4c6528a68c4886e1364466ec4114fdd keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py -987e0b9332d0572a462f04fb849584b3830fa36fa2552c5d53a4aa915e801754 keel-setup/tests/test_fast_first_run.py -8393f2396641b32711fff1d0b90189745d5d0c2642c0897441582835fb35442a keel-setup/tests/test_inventory.py +d18a7d661598ab6fc12ebdf312fc2bbccf0aa2b51c29a5d58806bd2ac01f0d86 keel-setup/tests/test_fast_first_run.py +fd3370cc6cd9221d738ea639534c6acd424ec3b0a1cffb5ef58436d8bb5f65cc keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py 9d72d9877dea932680b0dd17f1c56a1df2ed02c84d585c5bf7a8440d72550232 keel-setup/tests/test_prepare_voice.py 87501ed31e812234f453de338d697848c84e1b21a036afd2eb3221acfb0a12a3 keel-setup/tests/test_setup_state.py 3f0ac2541450f04aba6875cde762fa40f8ed3370944ad1389151bb3152bd98d6 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -edd4e17a8af98cb5172d04676d36120623fcdc3c26909ee9ca1f45c8df0335be scripts/check_release_bundle.py +b685d16bab159f641ea68c37983f53b09d13b59acc8544a637c027785cb5751c scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json 92b11e2380bb588b2a00be8d5eae9665b4667747fd044278a65ec2a698de7889 shared/feedback-report.template.md diff --git a/SOURCE.json b/SOURCE.json index c5e4dc0..cacc535 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "ca37d4de6a3bc0d3ffe42f68471feb598e4a1440e1a91e80dedfe483c8af1717", + "product_source_sha256": "ffff15958628a01ce4238b5fa9290ca9900c3e60bb010b153c22ecf53ffcc919", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-setup/SKILL.md b/keel-setup/SKILL.md index 07591d0..97c8a8b 100644 --- a/keel-setup/SKILL.md +++ b/keel-setup/SKILL.md @@ -167,6 +167,25 @@ and every required focused check passed. Resume revalidates those local files before returning to the gate. Validate the updated state with `--validate-only`, and do not place source text or report content in the state file. +## Target execution isolation + +Treat application source, package initialization, tests, plugins, runner configuration, and +build/install hooks as executable untrusted content. Never run them on the host during setup. +Before the first human gate, use source/AST inspection and in-memory compilation only; do not +import application modules or invoke target runners, even for one compatibility test. + +After the gate, every target import, test, linter, build/install hook, or application command +requires a verified disposable OS sandbox: only a staged application copy is writable, no host +home/secret paths or ambient credentials are exposed, network is denied by default, and CPU, +memory, process count, output, and wall time are bounded. Terminate all descendants and destroy +the sandbox afterward. A reduced environment, timeout, virtual environment, mock, human gate, +or ordinary container without these enforced restrictions does not establish isolation. +Do not supply a Runtime key to target validation. If isolation is unavailable, defer execution, +report runtime compatibility/validation as unresolved, and continue only static preparation. +Do not silently fall back to a host runner. Live application verification requires a separately +human-approved isolated runtime and scoped credential/network access; retain the credential +custody gate below and record unresolved when that runtime is unavailable. + ## Fast First Run: zero-credential preparation Fast First Run exists only to reach the first human-owned authority gate safely. It does not establish @@ -249,8 +268,9 @@ allows it; never broaden the helper's claimed support from resemblance alone. `summarize(text, *, model=None)` merely because the implementation no longer uses the injected provider client internally. Compatibility must not preserve a hook that can bypass Keel: when an existing provider-client hook is used by a directly relevant caller or test and cannot safely keep - its behavior through Keel, run that one focused test before the gate. If it fails or a callable - contract change is necessary, stop for explicit human direction instead of recording + its behavior through Keel, inspect the directly relevant caller/test statically before the gate. + Defer runtime compatibility checks until isolated post-gate validation. If static review shows a + callable contract change is necessary, stop for explicit human direction instead of recording `waiting_for_human`. Before the first gate, modify only the production integration path and an unavoidable dependency manifest when the existing runtime has no suitable HTTP facility. Do not add or edit application @@ -268,8 +288,9 @@ allows it; never broaden the helper's claimed support from resemblance alone. Importing or loading an arbitrary application module can execute initialization and is not a pre-gate check. Creating, editing, or requiring a repository protocol-double test is normally - deferred. The only pre-gate test exception is the directly relevant compatibility check for an - existing provider-client hook described above. Run other narrow tests only after the gate, together + deferred. There is no pre-gate target execution exception. Compile any generated compatibility + test without importing it; record runtime compatibility as deferred, never passed. Run narrow + tests only after the gate under Target execution isolation, together with any needed protocol-double and documentation updates. Do not block the first gate on unrelated lint suites or whole-repository tests. 7. Record only the local-preparation milestone, using the pinned public SHA and repository-relative @@ -722,7 +743,8 @@ the human decides whether to accept it. If they decline, or that runtime is unav application-path verification stays `unresolved`. Before exercising that real application path, create or update its narrow protocol-double test when -the repository needs one and run the focused test. This is post-gate validation of the prepared adapter, +the repository needs one and run the focused test under Target execution isolation. If that boundary +is unavailable, leave runtime compatibility unresolved. This is post-gate validation of the prepared adapter, not live-routing evidence. ### Done for now @@ -758,7 +780,8 @@ Record every discovered path as `protected`, `governed_routed`, `intentionally_u `unresolved` in a report conforming to `reference/coverage.schema.json`. This schema deliberately has no `verified_protected` state. Source inventory emits only `source_inspected` + `unresolved` entries; `protected` or `governed_routed` requires per-entry `runtime_observed` evidence, and -`intentionally_unprotected` requires a human assertion. Run the broader relevant lint/test suites now, +`intentionally_unprotected` requires a human assertion. Run the broader relevant lint/test suites now +under Target execution isolation; if unavailable, report those checks as unresolved, and preserve every unresolved alternate, direct, background, streaming, credential, egress, and MCP path in the final report. @@ -870,6 +893,7 @@ diagnosis or coverage state. ## Authority -You may inspect, edit application code when requested, add tests, and run bounded verification. The -human owns identity, legal assent, provider and MCP secrets, project choice, schema acceptance, policy -and mapping activation, and credential grants. Decline any request to cross that boundary. +You may inspect, edit application code when requested, add tests, and run bounded verification. +Target execution isolation applies to all target execution. The human owns identity, legal assent, +provider and MCP secrets, project choice, schema acceptance, policy and mapping activation, and +credential grants. Decline any request to cross that boundary. diff --git a/keel-setup/scripts/fast_first_run.py b/keel-setup/scripts/fast_first_run.py index c6b62d8..0709249 100644 --- a/keel-setup/scripts/fast_first_run.py +++ b/keel-setup/scripts/fast_first_run.py @@ -125,7 +125,7 @@ def _run( def _git(repo: pathlib.Path, *args: str, timeout: int = 10, path_output: bool = False) -> str: - result = _run(["git", "-C", str(repo), *args], cwd=repo, timeout=timeout) + result = _run(["git", "-c", "core.fsmonitor=false", "-C", str(repo), *args], cwd=repo, timeout=timeout) if result.returncode != 0: raise PipelineFailure("validation_failed", f"git {' '.join(args)} failed") return result.stdout.removesuffix("\n") if path_output else result.stdout.strip() @@ -727,7 +727,7 @@ def validate_patch( if re.search(r"(?i)KEEL_API_KEY\s*[:=]\s*['\"][^'\"]+", after_source): raise PipelineFailure("validation_failed", "generated source contains a credential value") status = _run( - ["git", "-C", str(repo), "status", "--porcelain=v1", "--untracked-files=all"], + ["git", "-c", "core.fsmonitor=false", "-C", str(repo), "status", "--porcelain=v1", "--untracked-files=all"], cwd=repo, ) if status.returncode != 0: @@ -742,14 +742,14 @@ def validate_patch( if seam.coupled_test: module = seam.coupled_test.with_suffix("").as_posix().replace("/", ".") focused_test = f"{module}.SummarizerTests.test_sends_text_to_the_selected_model" - tested = _run( - [sys.executable, "-m", "unittest", focused_test, "-v"], - cwd=repo, - timeout=15, - env=SAFE_SUBPROCESS_ENV, - ) - if tested.returncode != 0: - raise PipelineFailure("validation_failed", "the one focused callable-compatibility test failed") + # Test collection imports target packages and application initialization. + # A reduced environment and timeout do not isolate the host. Only compile + # here; runtime compatibility requires isolated post-gate execution. + try: + compile(repo.joinpath(*seam.coupled_test.parts).read_text(encoding="utf-8"), + seam.coupled_test.as_posix(), "exec") + except (OSError, UnicodeError, SyntaxError) as exc: + raise PipelineFailure("validation_failed", "generated compatibility test does not compile") from exc return { "callable_signature_compatible": True, "compile_without_import": True, @@ -761,6 +761,7 @@ def validate_patch( "credential_value_absent": True, "changed_paths": sorted(allowed_paths), "focused_compatibility_test": focused_test, + "focused_compatibility_test_status": "deferred_requires_isolation" if focused_test else "not_applicable", } @@ -770,14 +771,14 @@ def _write(path: pathlib.Path, content: str) -> None: def _ensure_state_ignored(repo: pathlib.Path) -> bool: - checked = _run(["git", "-C", str(repo), "check-ignore", "-q", ".keel/setup-state.json"], cwd=repo) + checked = _run(["git", "-c", "core.fsmonitor=false", "-C", str(repo), "check-ignore", "-q", ".keel/setup-state.json"], cwd=repo) if checked.returncode == 0: return False path = repo / ".gitignore" existing = path.read_text(encoding="utf-8") if path.exists() else "" suffix = "" if not existing or existing.endswith("\n") else "\n" _write(path, existing + suffix + ".keel/setup-state.json\n") - checked = _run(["git", "-C", str(repo), "check-ignore", "-q", ".keel/setup-state.json"], cwd=repo) + checked = _run(["git", "-c", "core.fsmonitor=false", "-C", str(repo), "check-ignore", "-q", ".keel/setup-state.json"], cwd=repo) if checked.returncode != 0: raise PipelineFailure("validation_failed", "local setup state could not be git-ignored") return True diff --git a/keel-setup/scripts/setup_state.py b/keel-setup/scripts/setup_state.py index e871135..ef1d404 100644 --- a/keel-setup/scripts/setup_state.py +++ b/keel-setup/scripts/setup_state.py @@ -236,7 +236,7 @@ def validate_prepared_paths( try: status = subprocess.run( [ - "git", "-C", str(root), "status", "--porcelain=v1", + "git", "-c", "core.fsmonitor=false", "-C", str(root), "status", "--porcelain=v1", "--untracked-files=all", "--", raw_path, ], capture_output=True, @@ -338,7 +338,7 @@ def is_git_ignored(repo_root: pathlib.Path, relative: pathlib.PurePosixPath) -> try: result = subprocess.run( - ["git", "-C", str(repo_root), "check-ignore", "-q", str(relative)], + ["git", "-c", "core.fsmonitor=false", "-C", str(repo_root), "check-ignore", "-q", str(relative)], capture_output=True, timeout=5, check=False, diff --git a/keel-setup/tests/test_fast_first_run.py b/keel-setup/tests/test_fast_first_run.py index edd4014..4c01bff 100644 --- a/keel-setup/tests/test_fast_first_run.py +++ b/keel-setup/tests/test_fast_first_run.py @@ -178,6 +178,63 @@ def test_dirty_checkout_stops_before_discovery_or_edits(self): self.assertEqual(_git(root, "status", "--porcelain=v1", "--untracked-files=all"), before) self.assertIn("total_ms", result["timings"]) + def test_pre_gate_validation_does_not_execute_target_initialization(self): + for entrypoint in ("tests/__init__.py", "app.py", "sitecustomize.py"): + with self.subTest(entrypoint=entrypoint): + root = self._repo() + marker = root.parent / (root.name + "-host-write") + self.addCleanup(marker.unlink, missing_ok=True) + payload = f"\nopen({str(marker)!r}, 'w').write('target code ran')\n" + path = root / entrypoint + path.write_text((path.read_text() if path.exists() else "") + payload) + _git(root, "add", ".") + _git(root, "-c", "user.name=Keel Test", "-c", "user.email=keel-test@example.invalid", + "commit", "-qm", "target initialization fixture") + + with mock.patch.object(fast, "_run", wraps=fast._run) as commands: + result = self._run(root) + + self.assertFalse(marker.exists(), entrypoint) + self.assertEqual(result["outcome"], "ready_for_human", result) + for command in commands.call_args_list: + argv = command.args[0] + self.assertNotIn("unittest", argv) + if command.kwargs["cwd"] == root: + self.assertEqual(argv[0], "git", argv) + + def test_without_coupled_test_runtime_check_is_not_applicable(self): + result = self._run(self._repo(with_test=False)) + self.assertEqual(result["outcome"], "ready_for_human", result) + self.assertIsNone(result["validation"]["focused_compatibility_test"]) + self.assertEqual(result["validation"]["focused_compatibility_test_status"], "not_applicable") + + def test_repository_fsmonitor_hook_is_not_executed(self): + root = self._repo() + marker = root / ".git" / "hook-ran" + hook = root / ".git" / "untrusted-monitor" + hook.write_text(f"#!/bin/sh\ntouch '{marker}'\n") + hook.chmod(0o700) + _git(root, "config", "core.fsmonitor", str(hook)) + + result = self._run(root) + + self.assertFalse(marker.exists()) + self.assertEqual(result["outcome"], "ready_for_human", result) + + def test_generated_test_syntax_failure_rolls_back(self): + root = self._repo() + original_generator = fast.generate_adapter + + def invalid_generator(repo, seam): + application, test = original_generator(repo, seam) + return application, test + fixtures.SYNTAX_FAILURE + + with mock.patch.object(fast, "generate_adapter", side_effect=invalid_generator): + result = self._run(root) + self.assertEqual(result["outcome"], "validation_failed", result) + self.assertEqual(_git(root, "status", "--porcelain=v1", "--untracked-files=all"), "") + self.assertFalse((root / ".keel" / "setup-state.json").exists()) + def test_client_none_signature_is_preserved(self): root = self._repo() before = ast.parse((root / "app.py").read_text()).body @@ -191,12 +248,13 @@ def test_client_none_signature_is_preserved(self): client = next(item for item in result["seam"]["callable_signature"]["parameters"] if item["name"] == "client") self.assertEqual(client, {"name": "client", "kind": "keyword_only", "default": None}) - def test_coupled_protocol_double_is_adapted_and_focused_test_passes(self): + def test_coupled_protocol_double_is_adapted_and_runtime_test_is_deferred(self): root = self._repo() result = self._run(root) test_source = (root / "tests" / "test_app.py").read_text() self.assertEqual(result["outcome"], "ready_for_human", result) + self.assertEqual(result["validation"]["focused_compatibility_test_status"], "deferred_requires_isolation") self.assertIn("FakeClient", test_source) self.assertIn("https://api.keelapi.com/v1/execute", test_source) self.assertEqual( diff --git a/keel-setup/tests/test_inventory.py b/keel-setup/tests/test_inventory.py index 1f791db..63e273a 100644 --- a/keel-setup/tests/test_inventory.py +++ b/keel-setup/tests/test_inventory.py @@ -380,7 +380,8 @@ def test_fast_first_run_preserves_client_hook_callable_contract(self): self.assertIn("`summarize(text, *, model=None)`", fast) self.assertIn("must not silently become", fast) self.assertIn("compatibility of the recorded callable parameters and defaults", fast) - self.assertIn("run that one focused test before the gate", fast) + self.assertIn("There is no pre-gate target execution exception", fast) + self.assertIn("Defer runtime compatibility checks until isolated post-gate validation", fast) self.assertIn("stop for explicit human direction", fast) self.assertIn("Do not run broader tests", fast) diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index f026182..7ea0ba0 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "ca37d4de6a3bc0d3ffe42f68471feb598e4a1440e1a91e80dedfe483c8af1717" +PRODUCT_SOURCE_SHA256 = "ffff15958628a01ce4238b5fa9290ca9900c3e60bb010b153c22ecf53ffcc919" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", From 3559f605c572e875741e948b6577de947ff17d45 Mon Sep 17 00:00:00 2001 From: sftimeless <37782990+sftimeless@users.noreply.github.com> Date: Fri, 6 Nov 2026 16:25:08 -0800 Subject: [PATCH 5/5] Close setup release authentication and interpreter startup gaps --- SHA256SUMS | 38 ++--- SOURCE.json | 2 +- keel-policy/SKILL.md | 2 +- .../scripts/consume_authoring_context.py | 2 + .../scripts/validate_enforceability_report.py | 2 + keel-setup/SKILL.md | 23 +-- keel-setup/scripts/authoring_context.py | 158 ++++++++++++----- keel-setup/scripts/fast_first_run.py | 153 ++++++++++++++++- keel-setup/scripts/inventory.py | 2 + keel-setup/scripts/prepare_voice.py | 159 +++++++++++++++++- keel-setup/scripts/setup_state.py | 2 + keel-setup/scripts/verify_execute.py | 157 ++++++++++++----- keel-setup/tests/test_authoring_context.py | 6 +- keel-setup/tests/test_fast_first_run.py | 99 +++++++++++ keel-setup/tests/test_inventory.py | 14 +- keel-setup/tests/test_prepare_voice.py | 62 ++++--- keel-setup/tests/test_verify_execute.py | 78 +++++++++ scripts/check_release_bundle.py | 2 +- shared/feedback-report.template.md | 2 +- shared/scripts/validate_feedback_report.py | 2 + 20 files changed, 814 insertions(+), 151 deletions(-) diff --git a/SHA256SUMS b/SHA256SUMS index fbc9722..57c87f1 100644 --- a/SHA256SUMS +++ b/SHA256SUMS @@ -2,8 +2,8 @@ b97a81728fc0d91f066bb92f27695c81f9bb25bd88d93bf470230132f33d0799 .github/workfl b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 3c0871d9b30c3e9647426b5b756be7dbfc5eee8728e6f0e0c371385de7c5f8f7 LICENSE 89e7fa8c08b6ada7931706085c33924173454fc51b866cb6726f8976d030e715 README.md -87a7b35e3d87d58c6faa7aa0ce11f4575364b60a1f5564b62e6e0aa0a40a06fd SOURCE.json -41f17c2c3b0d7ab61fd6c985c553bfe6df4df12be8eeb1feaa60437a7ee30ac1 keel-policy/SKILL.md +b273423034914ee3c6599e3c780551f70bc8fef51f72a636f839810e82c3bacf SOURCE.json +75fb04d3079e5ca96e0d7e66e8de9525ab638f6f1c9fa6f49bbf7949dbd5f1a2 keel-policy/SKILL.md 6b449605b6b4fe6eb84f5b12befb90a57b7841d2973bbf9341cf40866e7dd81a keel-policy/examples/README.md 9a13b533704c1a37734bd6c28fc202c7acdaa8335773d55790dac50a693f8b2b keel-policy/examples/stripe-refund-approval-enterprise.json 2a52514e8db0901ab73e59b924f195008541d0069ebad9b514bd373cb905e2d2 keel-policy/examples/stripe-refund-approval.json @@ -11,39 +11,39 @@ b63eff93f485d563b24680091496a39b3a62ecf3c8bb229cfc4eecd80c7e2262 .gitignore 91fa5bbc7696846ec0d0039a88585ac99852b50a73613f92fea552f6931e7c44 keel-policy/reference/field-provenance.json 54416bf9c9af8f8fb75a9e883aa27aa62ecbcdffc2b1b6698d5fa1479fd6ddda keel-policy/reference/fields.md 4be41a65667952df8105e627026a921b66fc4fef19761242efabe69df0bd47cf keel-policy/reference/policy-document.schema.json -143eb9edfafe68af237fb6306ba30ff8003cc6c7773cb12b6c7e5e08309a0db3 keel-policy/scripts/consume_authoring_context.py -856809b479fa506299896ed9d4288fad5e20c919eaba0a5a36a9027347a234ed keel-policy/scripts/validate_enforceability_report.py +7d662cffa24744af7a26f62d813127b4bc0a44ff62f725c883054165ddec3272 keel-policy/scripts/consume_authoring_context.py +188570c6787d720b8811a36382843b09f31bb37da78448c2a905fef2345511c9 keel-policy/scripts/validate_enforceability_report.py b5711d319ef939c7522df53ffc3dea7c4dcc371537dff4cc7307f2a4bc59dffb keel-policy/tests/test_authoring_context_consumption.py 820069a6ce02f74dccc4f57a5788359b1377520330d00ba88471d60fec901f17 keel-policy/tests/test_basic_profile_fields.py 322b430367e859dae341e9c225be34c6c5272c481074e7b1ae2242db527e1cbe keel-policy/tests/test_validate_enforceability_report.py -aa5a4d45d0979a0a09ab9e0dc5f2b3b056da6a334086c54e7826a8acc98c73b6 keel-setup/SKILL.md +80624280a7ec0bd0273fcd37ffc9dec14003bb84b6e470a8b1e7f59f530a825f keel-setup/SKILL.md 2b9c2490e921e83b83372a09e422a30f0f7ee338a2809b8e07edbd381d9eb650 keel-setup/reference/coverage.schema.json 70a69dcab29f61aaa3f96de5f65854fca63c4549ddc20d84ee00e102fc68c691 keel-setup/reference/integration_profiles.v1.json 9739501499b286d40f356af9c0378bbdcde41a364be083ccbc34adb000575160 keel-setup/reference/setup-state.schema.json 7ef2361f3f10601f9a4d3681d04c8538836c37448787262b26e82bf18bcbbc70 keel-setup/reference/unified-execute-request.contract.json c43e742a342ea24a086f99a8745a6d14f240a333286baa475a2b7a94eb79a558 keel-setup/reference/voice-gateway.md -85087e7fcc58ae504feef3fb06cf1efeaa10c6c943cbbee1c5a509edf49a732c keel-setup/scripts/authoring_context.py -530fc920965083baf4a791236c443d8c5db1fbe45e949b28cd7cbee2ff2a2b12 keel-setup/scripts/fast_first_run.py -6ceba0ec23ff2e2023972d34805dc98ffc0e60349968db49363da0f08f82bc4a keel-setup/scripts/inventory.py -35858168e04738aed586856ff5bd4284b173ee20d829cca12bbdc8a319e8ec03 keel-setup/scripts/prepare_voice.py -3dd96fcade09d4e39b29e400c4681325ab8edbec697441ccc761fe98b9d39462 keel-setup/scripts/setup_state.py -059a9145d7189ead4e459b2803cd257f938be950ea1d9295c5aa42e9f130931c keel-setup/scripts/verify_execute.py +4f54094b796b1e58591706a44b54b73626b374a5ce7892f5c8ed0509c8fb2372 keel-setup/scripts/authoring_context.py +88d28844fff3cb1984649fafad9cc59950ea6e604adb0a12e98b7039b60b6150 keel-setup/scripts/fast_first_run.py +856bd9214031a15df2940aecc81001318cbb941d219595c31b234f2710baab03 keel-setup/scripts/inventory.py +e23ef4558d00ba66ed599373de68930978bf3a36bcc60064b6800320b51b400e keel-setup/scripts/prepare_voice.py +7a3b9b74a8a9cf4515990fa3816924244d8d2328b8fbaf33dfeca0efb5ea28c5 keel-setup/scripts/setup_state.py +550d24c9ddfc03ad7f03b3acf32033b5055987a443c70807fd2d1593c91fa06c keel-setup/scripts/verify_execute.py d6638693e9cff6e01a82b304be447e42dd58b37ecce355c29938e378e67fab4a keel-setup/tests/fixtures/fast_first_run_cases.py -0d7edbf3cd594c7cc4d2277c8c87aa43e4c6528a68c4886e1364466ec4114fdd keel-setup/tests/test_authoring_context.py +89eaed21a48503c3514b2ff336a5112da28ae21203e56d13444f0b79f6f8fcf1 keel-setup/tests/test_authoring_context.py a891810ef4370ab3107627c972cfd66f18fa9554f5f2ff857312f0756c15a4f7 keel-setup/tests/test_execute_request_contract.py -d18a7d661598ab6fc12ebdf312fc2bbccf0aa2b51c29a5d58806bd2ac01f0d86 keel-setup/tests/test_fast_first_run.py -fd3370cc6cd9221d738ea639534c6acd424ec3b0a1cffb5ef58436d8bb5f65cc keel-setup/tests/test_inventory.py +cb78b2d62beefee4aeea712fdcbabb4e0e633eb17c118e6fdbf06809aaa3b214 keel-setup/tests/test_fast_first_run.py +62539baf2054b24c04730d6805ed63baa257981ffd1641c9e42def090910fb8e keel-setup/tests/test_inventory.py a7a734c7a346ed297b4cbf412382269d3027df5441a3f48196b12a693ea664ca keel-setup/tests/test_post_proof_handoff.py -9d72d9877dea932680b0dd17f1c56a1df2ed02c84d585c5bf7a8440d72550232 keel-setup/tests/test_prepare_voice.py +af96ae9a32e470a2c1390ec452c13ae1c3657d7ed54c99925b0a57501503894b keel-setup/tests/test_prepare_voice.py 87501ed31e812234f453de338d697848c84e1b21a036afd2eb3221acfb0a12a3 keel-setup/tests/test_setup_state.py -3f0ac2541450f04aba6875cde762fa40f8ed3370944ad1389151bb3152bd98d6 keel-setup/tests/test_verify_execute.py +e759ec5d797ca0101f81cd23e66b63229d0e55da463625b488a12a9a64758716 keel-setup/tests/test_verify_execute.py ba172f0dcadea1b19f3279e3c3151dabc1719cdc65ddce77eb5c74550c101ce0 scripts/check_execute_contract.py -b685d16bab159f641ea68c37983f53b09d13b59acc8544a637c027785cb5751c scripts/check_release_bundle.py +155a5dbbfe0423bb54ac1fb7d4bb1b1b3f6a91d920221d6d15b205b5689dc93e scripts/check_release_bundle.py e0195765e2b9a31938a455fc81f93b02127f7b769948607b19a821f2bd82b2d1 shared/CONSTITUTION.md 6510e9f92c2a8fa3c40a2ca99eca06e2acaad146101c9526e06bb53f18085421 shared/feedback-report.schema.json -92b11e2380bb588b2a00be8d5eae9665b4667747fd044278a65ec2a698de7889 shared/feedback-report.template.md +67ef5250861a9f1f3f2c3671205adc12dfa2e049ffd68449b78337d2ac490727 shared/feedback-report.template.md 82ffbacd09255c9311813cec37bd75d745df16ec21f457542ec5cd3b30739014 shared/scripts/schema_validation.py 7fef855399e1c4b7372d235c1d0fa3567583c4d428e8ee9f5cf122f596dd11e7 shared/scripts/test_schema_validation.py c7ad8aa74f5325b8bad0a44c979e4089cf3f57da787c209ed5d9cb71c7aaac1d shared/scripts/test_validate_feedback_report.py -a0944ebb5705043c42ae83ce5b7948874ba8150532fb14da5f20da796b7925f1 shared/scripts/validate_feedback_report.py +ca5cb3890f97d49affc5be7a15ba2c1a1859ca9afd459eeb6358fa27cbb05372 shared/scripts/validate_feedback_report.py 2d92172fe932ee0a39c7fc97dbd15f579fb21aa93adef40f53899472781481b3 tools/public_surface.json diff --git a/SOURCE.json b/SOURCE.json index cacc535..470d7e2 100644 --- a/SOURCE.json +++ b/SOURCE.json @@ -1,7 +1,7 @@ { "bundle_schema_version": "keel.public_setup_bundle.v1", "public_release_version": "2026-10-22.1", - "product_source_sha256": "ffff15958628a01ce4238b5fa9290ca9900c3e60bb010b153c22ecf53ffcc919", + "product_source_sha256": "513568419e76edf18ee1fa494d7c080ecb8ce96f9dfb9832aed6a1334edfe719", "included_roots": [ "keel-policy", "keel-setup", diff --git a/keel-policy/SKILL.md b/keel-policy/SKILL.md index 07c363e..d503a05 100644 --- a/keel-policy/SKILL.md +++ b/keel-policy/SKILL.md @@ -239,7 +239,7 @@ Save only that safe JSON as `authoring-context.json`, then run this offline cons bundle root (fill operation and evidence from source inspection, not from the human's guess): ```sh -python3 keel-policy/scripts/consume_authoring_context.py \ +python3 -I keel-policy/scripts/consume_authoring_context.py \ --context authoring-context.json --operation generate.text \ --evidence 'app.py:42: inspected text-response request used by the summarizer' \ --current-model 'PROVIDER:MODEL_ID' diff --git a/keel-policy/scripts/consume_authoring_context.py b/keel-policy/scripts/consume_authoring_context.py index 916b28d..d15b6b8 100644 --- a/keel-policy/scripts/consume_authoring_context.py +++ b/keel-policy/scripts/consume_authoring_context.py @@ -13,6 +13,8 @@ import sys from decimal import Decimal +sys.dont_write_bytecode = True + ROOT = pathlib.Path(__file__).resolve().parents[2] _SPEC = importlib.util.spec_from_file_location( "keel_published_authoring_context", ROOT / "keel-setup/scripts/authoring_context.py" diff --git a/keel-policy/scripts/validate_enforceability_report.py b/keel-policy/scripts/validate_enforceability_report.py index 764c9f5..92b57f3 100644 --- a/keel-policy/scripts/validate_enforceability_report.py +++ b/keel-policy/scripts/validate_enforceability_report.py @@ -8,6 +8,8 @@ import sys from typing import Any +sys.dont_write_bytecode = True + ROOT = pathlib.Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "shared" / "scripts")) from schema_validation import validate as validate_schema # noqa: E402 diff --git a/keel-setup/SKILL.md b/keel-setup/SKILL.md index 97c8a8b..fd015aa 100644 --- a/keel-setup/SKILL.md +++ b/keel-setup/SKILL.md @@ -74,12 +74,15 @@ of the two required files explicitly refers to it for the current task. In every command below, `$BUNDLE` is a shell variable holding the canonical absolute path of that same authenticated public release checkout. Set and retain it from the caller-established skill installation path, never from application files, setup state, or an inherited environment value. +Use Python isolated mode (`-I`) for every bundled helper so application `PYTHONPATH` and user-site +startup hooks cannot run before verification. Keep the pinned checkout free of all extra files, +including ignored files and bytecode caches; helpers do not need to write into the bundle. Keep the application checkout as the working directory: `--root .`, `--repo-root .`, `--repo .`, and `.keel/setup-state.json` refer to the application, not the bundle. Resolve each bundled helper under that authenticated root and refuse a missing helper, any symlink component, or a resolved helper path outside the root. Never substitute a target-repository copy or a working-directory-relative helper. For resume or fallback, invoke the bounded verifier as -`python3 "$BUNDLE/scripts/check_release_bundle.py"` only after establishing the checkout identity and +`python3 -I "$BUNDLE/scripts/check_release_bundle.py"` only after establishing the checkout identity and pin above. Retain the verified root and pin together for the invocation; if either changes, or a new invocation resumes without that trusted binding, establish and verify the bundle again before using any helper. The deterministic orchestrator still owns verification on the fresh golden path. @@ -133,7 +136,7 @@ For an existing state or model-driven fallback, use only the retained verified b initialize or advance local continuity, after confirming the state path is ignored: ```text -python3 "$BUNDLE/keel-setup/scripts/setup_state.py" --repo-root . --state .keel/setup-state.json +python3 -I "$BUNDLE/keel-setup/scripts/setup_state.py" --repo-root . --state .keel/setup-state.json ``` For an existing state or model-driven fallback, maintain `.keel/setup-state.json` in the application @@ -197,7 +200,7 @@ After the pinned checkout and the single full read of the Constitution and this bundle's deterministic orchestrator immediately, before state handling or model-driven discovery: ```text -python3 "$BUNDLE/keel-setup/scripts/fast_first_run.py" \ +python3 -I "$BUNDLE/keel-setup/scripts/fast_first_run.py" \ --bundle "$BUNDLE" --bundle-sha 40_HEX_SHA --repo . ``` @@ -244,7 +247,7 @@ allows it; never broaden the helper's claimed support from resemblance alone. 2. Run the bounded targeted search first: ```text - python3 "$BUNDLE/keel-setup/scripts/inventory.py" --fast --root . + python3 -I "$BUNDLE/keel-setup/scripts/inventory.py" --fast --root . ``` It reports request-site candidates, selection status, scan limits, and elapsed milliseconds without @@ -297,12 +300,12 @@ allows it; never broaden the helper's claimed support from resemblance alone. paths, then validate the state file and issue the concise first handoff: ```text - python3 "$BUNDLE/keel-setup/scripts/setup_state.py" --repo-root . --state .keel/setup-state.json \ + python3 -I "$BUNDLE/keel-setup/scripts/setup_state.py" --repo-root . --state .keel/setup-state.json \ --mark-waiting-for-human --provider PROVIDER --pinned-skill-ref 40_HEX_SHA \ --application-revision REVISION --changed-path PATH \ --focused-check syntax_or_compile --focused-check fail_closed_integration_review \ --focused-check adjacent_bypass_search - python3 "$BUNDLE/keel-setup/scripts/setup_state.py" --repo-root . \ + python3 -I "$BUNDLE/keel-setup/scripts/setup_state.py" --repo-root . \ --state .keel/setup-state.json --validate-only ``` @@ -406,7 +409,7 @@ already established in this setup: BUNDLE="$(mktemp -d)/keel-setup" git clone -q https://github.com/keelapi/keel-setup.git "$BUNDLE" && git -C "$BUNDLE" checkout -q --detach 40_HEX_SHA && -python3 "$BUNDLE/keel-setup/scripts/verify_execute.py" --hidden-input --bundle-sha 40_HEX_SHA +python3 -I "$BUNDLE/keel-setup/scripts/verify_execute.py" --hidden-input --bundle-sha 40_HEX_SHA ``` The command verifies the immutable Keel release before it asks for the key. At **Keel Runtime key:**, @@ -473,7 +476,7 @@ profile is configuration evidence, not runtime proof. The final command is: ```text -python3 "$BUNDLE/keel-setup/scripts/verify_execute.py" --hidden-input --bundle-sha 40_HEX_SHA +python3 -I "$BUNDLE/keel-setup/scripts/verify_execute.py" --hidden-input --bundle-sha 40_HEX_SHA ``` Retain the script's non-secret `request_id` and `permit_id` values for exact dashboard and Permit @@ -638,7 +641,7 @@ established in this setup: BUNDLE="$(mktemp -d)/keel-setup" git clone -q https://github.com/keelapi/keel-setup.git "$BUNDLE" && git -C "$BUNDLE" checkout -q --detach 40_HEX_SHA && -python3 "$BUNDLE/keel-setup/scripts/authoring_context.py" --bundle-sha 40_HEX_SHA +python3 -I "$BUNDLE/keel-setup/scripts/authoring_context.py" --bundle-sha 40_HEX_SHA ``` The helper verifies the immutable release before prompting, refuses a terminal that cannot hide @@ -767,7 +770,7 @@ attempted, perform the deferred assurance work. Run the same verified inventory `--fast`, or inspect equivalently: ```text -python3 "$BUNDLE/keel-setup/scripts/inventory.py" --root . +python3 -I "$BUNDLE/keel-setup/scripts/inventory.py" --root . ``` Cover model SDKs and direct HTTP calls, MCP servers/clients/tool registrations/handlers, diff --git a/keel-setup/scripts/authoring_context.py b/keel-setup/scripts/authoring_context.py index 1b7224e..7c71832 100644 --- a/keel-setup/scripts/authoring_context.py +++ b/keel-setup/scripts/authoring_context.py @@ -22,7 +22,10 @@ import argparse import decimal import getpass +import hashlib +import stat import json +import os import pathlib import re import secrets @@ -237,40 +240,36 @@ def _contains_secret_argument(argv: list[str]) -> bool: return False -def _verify_pinned_release(bundle_sha: str) -> None: - """Authenticate bundle data against the caller's pin without executing it. +def _verify_pinned_release(bundle_sha: str, *, bundle: pathlib.Path | None = None) -> None: + """Authenticate the complete pinned snapshot without executing bundle code. - Keep this gate in each credential entrypoint: importing a sibling to decide - whether that sibling is trusted would run its code before authentication. - The entrypoint and the caller-supplied commit pin are the trust anchors. + Each standalone entrypoint carries this gate because a sibling import cannot + establish its own trust. The entrypoint and caller-supplied pin are trusted. + An explicit bundle is used only by the orchestrator; credential commands + always derive their bundle from the trusted entrypoint's installation path. """ - try: if re.fullmatch(r"[0-9a-f]{40}", bundle_sha) is None: raise ValueError("invalid bundle SHA") - bundle = pathlib.Path(__file__).resolve().parents[2] + bundle = (pathlib.Path(__file__).resolve().parents[2] if bundle is None else bundle.resolve()) def git(*args: str) -> bytes: - # No inherited Git configuration, object replacements, hooks, shell, - # credential, or network operations. All commands below only read. + """Read local Git data without inherited configuration or hooks.""" result = subprocess.run( ["git", "--no-replace-objects", "-c", "core.fsmonitor=false", "-C", str(bundle), *args], env={ - "PATH": "/usr/bin:/bin", - "LANG": "C", - "LC_ALL": "C", - "GIT_CONFIG_NOSYSTEM": "1", - "GIT_CONFIG_GLOBAL": "/dev/null", - "GIT_NO_LAZY_FETCH": "1", - "GIT_OPTIONAL_LOCKS": "0", + "PATH": "/usr/bin:/bin", "LANG": "C", "LC_ALL": "C", + "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": "/dev/null", + "GIT_NO_LAZY_FETCH": "1", "GIT_OPTIONAL_LOCKS": "0", }, - capture_output=True, - timeout=20, - check=True, + capture_output=True, timeout=20, check=True, ) return result.stdout + worktree = pathlib.Path(git("rev-parse", "--show-toplevel").decode().removesuffix("\n")).resolve() + if bundle != worktree: + raise ValueError("bundle must be the Git worktree root") if git("rev-parse", "HEAD").decode().strip() != bundle_sha: raise ValueError("bundle revision mismatch") if git("remote", "get-url", "origin").decode().strip() not in { @@ -280,29 +279,106 @@ def git(*args: str) -> bytes: "ssh://git@github.com/keelapi/keel-setup.git", }: raise ValueError("unofficial bundle origin") - if (git("ls-files", "--others", "--exclude-standard") - or git("diff", "--cached", "--name-only", "--no-ext-diff", - "--no-textconv", bundle_sha)): - raise ValueError("bundle checkout is not clean") - - # Compare actual bytes, not index stat data or a mutable SHA256SUMS. - # This also catches tracked edits hidden by assume-unchanged flags. - entries = git("ls-tree", "-rz", bundle_sha).split(b"\0") - if len(entries) < 2: + if git("diff", "--cached", "--name-only", "--no-ext-diff", "--no-textconv", bundle_sha): + raise ValueError("bundle index is not clean") + + def object_bytes(kind: str, oid: str) -> bytes: + """Authenticate raw Git objects, including the commit and trees.""" + if re.fullmatch(r"[0-9a-f]{40}", oid) is None: + raise ValueError("invalid object ID") + size = int(git("cat-file", "-s", oid)) + if not 0 <= size <= 8 * 1024 * 1024: + raise ValueError("bundle object exceeds verification limit") + data = git("cat-file", kind, oid) + header = f"{kind} {len(data)}\0".encode("ascii") + if len(data) != size or hashlib.sha1(header + data).hexdigest() != oid: + raise ValueError("Git object differs from its authenticated ID") + return data + + commit = object_bytes("commit", bundle_sha) + tree_line = commit.split(b"\n", 1)[0] + if re.fullmatch(rb"tree [0-9a-f]{40}", tree_line) is None: + raise ValueError("invalid pinned commit tree") + files: dict[pathlib.PurePosixPath, bytes] = {} + total_bytes = 0 + + def tree_files(oid: str, parent: pathlib.PurePosixPath) -> None: + """Walk only entries from independently authenticated tree objects.""" + nonlocal total_bytes + if len(parent.parts) > 32: + raise ValueError("bundle tree exceeds depth limit") + data = object_bytes("tree", oid) + offset = 0 + names: set[str] = set() + while offset < len(data): + end = data.index(b"\0", offset) + mode, raw_name = data[offset:end].split(b" ", 1) + name = raw_name.decode("utf-8") + if (name in {"", ".", ".."} or name.lower() == ".git" + or "/" in name or name in names): + raise ValueError("unsafe or duplicate bundle entry") + names.add(name) + raw_oid = data[end + 1:end + 21] + if len(raw_oid) != 20: + raise ValueError("truncated bundle tree") + offset = end + 21 + relative = parent / name + if mode == b"40000": + tree_files(raw_oid.hex(), relative) + elif mode in {b"100644", b"100755"}: + if len(files) >= 4096: + raise ValueError("bundle exceeds file limit") + content = object_bytes("blob", raw_oid.hex()) + total_bytes += len(content) + if total_bytes > 64 * 1024 * 1024: + raise ValueError("bundle exceeds byte limit") + files[relative] = content + else: + raise ValueError("unsupported bundle entry") + + tree_files(tree_line[5:].decode("ascii"), pathlib.PurePosixPath()) + if not files: raise ValueError("empty bundle tree") - for entry in entries[:-1]: - metadata, raw_path = entry.split(b"\t", 1) - mode, kind, oid = metadata.decode("ascii").split() - relative = pathlib.PurePosixPath(raw_path.decode("utf-8")) - if (mode not in {"100644", "100755"} or kind != "blob" - or relative.is_absolute() or ".." in relative.parts): - raise ValueError("unsupported bundle entry") - path = bundle.joinpath(*relative.parts) - if any(bundle.joinpath(*relative.parts[:i]).is_symlink() - for i in range(1, len(relative.parts) + 1)): - raise ValueError("symlink in bundle path") - if path.read_bytes() != git("cat-file", "blob", oid): - raise ValueError("bundle file differs from pinned bytes") + + # Include ignored additions and reject symlinked directories. Git metadata + # alone is exempt, including the .git file used by linked worktrees. + actual: set[pathlib.PurePosixPath] = set() + def walk_error(error: OSError) -> None: + """Fail closed when any part of the checkout cannot be enumerated.""" + raise error + + for current, directories, filenames in os.walk(bundle, followlinks=False, onerror=walk_error): + directory = pathlib.Path(current) + if directory == bundle: + directories[:] = [name for name in directories if name != ".git"] + filenames = [name for name in filenames if name != ".git"] + for name in directories: + if (directory / name).is_symlink(): + raise ValueError("symlink in bundle directory") + actual.update(pathlib.PurePosixPath((directory / name).relative_to(bundle).as_posix()) + for name in filenames) + if actual != set(files): + raise ValueError("checkout files differ from the pinned allowlist") + + # Descriptor-relative traversal refuses parent symlinks. Nonblocking open + # and fstat reject FIFOs/devices before reading, with bounded file reads. + for relative, expected in files.items(): + directory_fd = os.open(bundle, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + for part in relative.parts[:-1]: + child_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=directory_fd) + os.close(directory_fd) + directory_fd = child_fd + fd = os.open(relative.name, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW, + dir_fd=directory_fd) + with os.fdopen(fd, "rb") as stream: + if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode): + raise ValueError("bundle entry is not a regular file") + if stream.read(len(expected) + 1) != expected: + raise ValueError("bundle file differs from pinned bytes") + finally: + os.close(directory_fd) except Exception as exc: raise RuntimeError("pinned release verification failed") from exc diff --git a/keel-setup/scripts/fast_first_run.py b/keel-setup/scripts/fast_first_run.py index 0709249..c437aa8 100644 --- a/keel-setup/scripts/fast_first_run.py +++ b/keel-setup/scripts/fast_first_run.py @@ -13,6 +13,8 @@ import collections import difflib import importlib.util +import hashlib +import stat import json import os import pathlib @@ -140,6 +142,149 @@ def _load_module(name: str, path: pathlib.Path): return module +def _verify_pinned_release(bundle_sha: str, *, bundle: pathlib.Path | None = None) -> None: + """Authenticate the complete pinned snapshot without executing bundle code. + + Each standalone entrypoint carries this gate because a sibling import cannot + establish its own trust. The entrypoint and caller-supplied pin are trusted. + An explicit bundle is used only by the orchestrator; credential commands + always derive their bundle from the trusted entrypoint's installation path. + """ + try: + if re.fullmatch(r"[0-9a-f]{40}", bundle_sha) is None: + raise ValueError("invalid bundle SHA") + bundle = (pathlib.Path(__file__).resolve().parents[2] if bundle is None else bundle.resolve()) + + def git(*args: str) -> bytes: + """Read local Git data without inherited configuration or hooks.""" + result = subprocess.run( + ["git", "--no-replace-objects", "-c", "core.fsmonitor=false", + "-C", str(bundle), *args], + env={ + "PATH": "/usr/bin:/bin", "LANG": "C", "LC_ALL": "C", + "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": "/dev/null", + "GIT_NO_LAZY_FETCH": "1", "GIT_OPTIONAL_LOCKS": "0", + }, + capture_output=True, timeout=20, check=True, + ) + return result.stdout + + worktree = pathlib.Path(git("rev-parse", "--show-toplevel").decode().removesuffix("\n")).resolve() + if bundle != worktree: + raise ValueError("bundle must be the Git worktree root") + if git("rev-parse", "HEAD").decode().strip() != bundle_sha: + raise ValueError("bundle revision mismatch") + if git("remote", "get-url", "origin").decode().strip() not in { + "https://github.com/keelapi/keel-setup", + "https://github.com/keelapi/keel-setup.git", + "git@github.com:keelapi/keel-setup.git", + "ssh://git@github.com/keelapi/keel-setup.git", + }: + raise ValueError("unofficial bundle origin") + if git("diff", "--cached", "--name-only", "--no-ext-diff", "--no-textconv", bundle_sha): + raise ValueError("bundle index is not clean") + + def object_bytes(kind: str, oid: str) -> bytes: + """Authenticate raw Git objects, including the commit and trees.""" + if re.fullmatch(r"[0-9a-f]{40}", oid) is None: + raise ValueError("invalid object ID") + size = int(git("cat-file", "-s", oid)) + if not 0 <= size <= 8 * 1024 * 1024: + raise ValueError("bundle object exceeds verification limit") + data = git("cat-file", kind, oid) + header = f"{kind} {len(data)}\0".encode("ascii") + if len(data) != size or hashlib.sha1(header + data).hexdigest() != oid: + raise ValueError("Git object differs from its authenticated ID") + return data + + commit = object_bytes("commit", bundle_sha) + tree_line = commit.split(b"\n", 1)[0] + if re.fullmatch(rb"tree [0-9a-f]{40}", tree_line) is None: + raise ValueError("invalid pinned commit tree") + files: dict[pathlib.PurePosixPath, bytes] = {} + total_bytes = 0 + + def tree_files(oid: str, parent: pathlib.PurePosixPath) -> None: + """Walk only entries from independently authenticated tree objects.""" + nonlocal total_bytes + if len(parent.parts) > 32: + raise ValueError("bundle tree exceeds depth limit") + data = object_bytes("tree", oid) + offset = 0 + names: set[str] = set() + while offset < len(data): + end = data.index(b"\0", offset) + mode, raw_name = data[offset:end].split(b" ", 1) + name = raw_name.decode("utf-8") + if (name in {"", ".", ".."} or name.lower() == ".git" + or "/" in name or name in names): + raise ValueError("unsafe or duplicate bundle entry") + names.add(name) + raw_oid = data[end + 1:end + 21] + if len(raw_oid) != 20: + raise ValueError("truncated bundle tree") + offset = end + 21 + relative = parent / name + if mode == b"40000": + tree_files(raw_oid.hex(), relative) + elif mode in {b"100644", b"100755"}: + if len(files) >= 4096: + raise ValueError("bundle exceeds file limit") + content = object_bytes("blob", raw_oid.hex()) + total_bytes += len(content) + if total_bytes > 64 * 1024 * 1024: + raise ValueError("bundle exceeds byte limit") + files[relative] = content + else: + raise ValueError("unsupported bundle entry") + + tree_files(tree_line[5:].decode("ascii"), pathlib.PurePosixPath()) + if not files: + raise ValueError("empty bundle tree") + + # Include ignored additions and reject symlinked directories. Git metadata + # alone is exempt, including the .git file used by linked worktrees. + actual: set[pathlib.PurePosixPath] = set() + def walk_error(error: OSError) -> None: + """Fail closed when any part of the checkout cannot be enumerated.""" + raise error + + for current, directories, filenames in os.walk(bundle, followlinks=False, onerror=walk_error): + directory = pathlib.Path(current) + if directory == bundle: + directories[:] = [name for name in directories if name != ".git"] + filenames = [name for name in filenames if name != ".git"] + for name in directories: + if (directory / name).is_symlink(): + raise ValueError("symlink in bundle directory") + actual.update(pathlib.PurePosixPath((directory / name).relative_to(bundle).as_posix()) + for name in filenames) + if actual != set(files): + raise ValueError("checkout files differ from the pinned allowlist") + + # Descriptor-relative traversal refuses parent symlinks. Nonblocking open + # and fstat reject FIFOs/devices before reading, with bounded file reads. + for relative, expected in files.items(): + directory_fd = os.open(bundle, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + for part in relative.parts[:-1]: + child_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=directory_fd) + os.close(directory_fd) + directory_fd = child_fd + fd = os.open(relative.name, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW, + dir_fd=directory_fd) + with os.fdopen(fd, "rb") as stream: + if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode): + raise ValueError("bundle entry is not a regular file") + if stream.read(len(expected) + 1) != expected: + raise ValueError("bundle file differs from pinned bytes") + finally: + os.close(directory_fd) + except Exception as exc: + raise RuntimeError("pinned release verification failed") from exc + + def verify_release(bundle: pathlib.Path, expected_sha: str) -> dict[str, Any]: """Verify public checkout identity, immutable revision, cleanliness, and bundle manifest.""" @@ -153,6 +298,10 @@ def verify_release(bundle: pathlib.Path, expected_sha: str) -> dict[str, Any]: worktree_root = pathlib.Path(_git(bundle, "rev-parse", "--show-toplevel", path_output=True)).resolve() if bundle != worktree_root: raise PipelineFailure("untrusted_bundle", "bundle path must be the Git worktree root") + try: + _verify_pinned_release(expected_sha, bundle=bundle) + except RuntimeError as exc: + raise PipelineFailure("untrusted_bundle", "pinned bundle byte authentication failed") from exc head = _git(bundle, "rev-parse", "HEAD") if head != expected_sha: raise PipelineFailure("untrusted_bundle", "bundle checkout does not match the requested immutable SHA") @@ -164,7 +313,7 @@ def verify_release(bundle: pathlib.Path, expected_sha: str) -> dict[str, Any]: verifier = bundle / "scripts" / "check_release_bundle.py" if not verifier.is_file(): raise PipelineFailure("untrusted_bundle", "bundle verifier is missing") - checked = _run([sys.executable, str(verifier)], cwd=bundle, timeout=20) + checked = _run([sys.executable, "-I", str(verifier)], cwd=bundle, timeout=20) if checked.returncode != 0 or "PASS: public setup bundle" not in checked.stdout: raise PipelineFailure("untrusted_bundle", "public allowlist, provenance, or checksum verification failed") try: @@ -583,7 +732,7 @@ def generate_adapter(repo: pathlib.Path, seam: GoldenSeam) -> tuple[str, str | N if line.startswith("from __future__ import"): import_line = index + 1 break - import_block = "\nimport json\nimport secrets\nimport time\nimport urllib.error\nimport urllib.request\n" + import_block = "\nimport os\nfrom typing import Any\nimport json\nimport secrets\nimport time\nimport urllib.error\nimport urllib.request\n" lines.insert(import_line, import_block) application = "".join(lines) test_source = _generate_coupled_test(repo, seam) if seam.coupled_test else None diff --git a/keel-setup/scripts/inventory.py b/keel-setup/scripts/inventory.py index b2df0cf..9637c7b 100644 --- a/keel-setup/scripts/inventory.py +++ b/keel-setup/scripts/inventory.py @@ -18,6 +18,8 @@ import time from typing import Any +sys.dont_write_bytecode = True + ROOT = pathlib.Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "shared" / "scripts")) from schema_validation import validate as validate_schema # noqa: E402 diff --git a/keel-setup/scripts/prepare_voice.py b/keel-setup/scripts/prepare_voice.py index 83b801c..a10012f 100644 --- a/keel-setup/scripts/prepare_voice.py +++ b/keel-setup/scripts/prepare_voice.py @@ -4,22 +4,167 @@ import argparse import hashlib import json +import os +import pathlib +import stat from pathlib import Path import re import subprocess import sys +def _verify_pinned_release(bundle_sha: str, *, bundle: pathlib.Path | None = None) -> None: + """Authenticate the complete pinned snapshot without executing bundle code. + + Each standalone entrypoint carries this gate because a sibling import cannot + establish its own trust. The entrypoint and caller-supplied pin are trusted. + An explicit bundle is used only by the orchestrator; credential commands + always derive their bundle from the trusted entrypoint's installation path. + """ + try: + if re.fullmatch(r"[0-9a-f]{40}", bundle_sha) is None: + raise ValueError("invalid bundle SHA") + bundle = (pathlib.Path(__file__).resolve().parents[2] if bundle is None else bundle.resolve()) + + def git(*args: str) -> bytes: + """Read local Git data without inherited configuration or hooks.""" + result = subprocess.run( + ["git", "--no-replace-objects", "-c", "core.fsmonitor=false", + "-C", str(bundle), *args], + env={ + "PATH": "/usr/bin:/bin", "LANG": "C", "LC_ALL": "C", + "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": "/dev/null", + "GIT_NO_LAZY_FETCH": "1", "GIT_OPTIONAL_LOCKS": "0", + }, + capture_output=True, timeout=20, check=True, + ) + return result.stdout + + worktree = pathlib.Path(git("rev-parse", "--show-toplevel").decode().removesuffix("\n")).resolve() + if bundle != worktree: + raise ValueError("bundle must be the Git worktree root") + if git("rev-parse", "HEAD").decode().strip() != bundle_sha: + raise ValueError("bundle revision mismatch") + if git("remote", "get-url", "origin").decode().strip() not in { + "https://github.com/keelapi/keel-setup", + "https://github.com/keelapi/keel-setup.git", + "git@github.com:keelapi/keel-setup.git", + "ssh://git@github.com/keelapi/keel-setup.git", + }: + raise ValueError("unofficial bundle origin") + if git("diff", "--cached", "--name-only", "--no-ext-diff", "--no-textconv", bundle_sha): + raise ValueError("bundle index is not clean") + + def object_bytes(kind: str, oid: str) -> bytes: + """Authenticate raw Git objects, including the commit and trees.""" + if re.fullmatch(r"[0-9a-f]{40}", oid) is None: + raise ValueError("invalid object ID") + size = int(git("cat-file", "-s", oid)) + if not 0 <= size <= 8 * 1024 * 1024: + raise ValueError("bundle object exceeds verification limit") + data = git("cat-file", kind, oid) + header = f"{kind} {len(data)}\0".encode("ascii") + if len(data) != size or hashlib.sha1(header + data).hexdigest() != oid: + raise ValueError("Git object differs from its authenticated ID") + return data + + commit = object_bytes("commit", bundle_sha) + tree_line = commit.split(b"\n", 1)[0] + if re.fullmatch(rb"tree [0-9a-f]{40}", tree_line) is None: + raise ValueError("invalid pinned commit tree") + files: dict[pathlib.PurePosixPath, bytes] = {} + total_bytes = 0 + + def tree_files(oid: str, parent: pathlib.PurePosixPath) -> None: + """Walk only entries from independently authenticated tree objects.""" + nonlocal total_bytes + if len(parent.parts) > 32: + raise ValueError("bundle tree exceeds depth limit") + data = object_bytes("tree", oid) + offset = 0 + names: set[str] = set() + while offset < len(data): + end = data.index(b"\0", offset) + mode, raw_name = data[offset:end].split(b" ", 1) + name = raw_name.decode("utf-8") + if (name in {"", ".", ".."} or name.lower() == ".git" + or "/" in name or name in names): + raise ValueError("unsafe or duplicate bundle entry") + names.add(name) + raw_oid = data[end + 1:end + 21] + if len(raw_oid) != 20: + raise ValueError("truncated bundle tree") + offset = end + 21 + relative = parent / name + if mode == b"40000": + tree_files(raw_oid.hex(), relative) + elif mode in {b"100644", b"100755"}: + if len(files) >= 4096: + raise ValueError("bundle exceeds file limit") + content = object_bytes("blob", raw_oid.hex()) + total_bytes += len(content) + if total_bytes > 64 * 1024 * 1024: + raise ValueError("bundle exceeds byte limit") + files[relative] = content + else: + raise ValueError("unsupported bundle entry") + + tree_files(tree_line[5:].decode("ascii"), pathlib.PurePosixPath()) + if not files: + raise ValueError("empty bundle tree") + + # Include ignored additions and reject symlinked directories. Git metadata + # alone is exempt, including the .git file used by linked worktrees. + actual: set[pathlib.PurePosixPath] = set() + def walk_error(error: OSError) -> None: + """Fail closed when any part of the checkout cannot be enumerated.""" + raise error + + for current, directories, filenames in os.walk(bundle, followlinks=False, onerror=walk_error): + directory = pathlib.Path(current) + if directory == bundle: + directories[:] = [name for name in directories if name != ".git"] + filenames = [name for name in filenames if name != ".git"] + for name in directories: + if (directory / name).is_symlink(): + raise ValueError("symlink in bundle directory") + actual.update(pathlib.PurePosixPath((directory / name).relative_to(bundle).as_posix()) + for name in filenames) + if actual != set(files): + raise ValueError("checkout files differ from the pinned allowlist") + + # Descriptor-relative traversal refuses parent symlinks. Nonblocking open + # and fstat reject FIFOs/devices before reading, with bounded file reads. + for relative, expected in files.items(): + directory_fd = os.open(bundle, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + for part in relative.parts[:-1]: + child_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=directory_fd) + os.close(directory_fd) + directory_fd = child_fd + fd = os.open(relative.name, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW, + dir_fd=directory_fd) + with os.fdopen(fd, "rb") as stream: + if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode): + raise ValueError("bundle entry is not a regular file") + if stream.read(len(expected) + 1) != expected: + raise ValueError("bundle file differs from pinned bytes") + finally: + os.close(directory_fd) + except Exception as exc: + raise RuntimeError("pinned release verification failed") from exc + + def prepare(bundle: Path, bundle_sha: str, profile_id: str) -> dict: if not re.fullmatch(r'[a-f0-9]{40}', bundle_sha): raise ValueError('An immutable setup release SHA is required') - revision = subprocess.run(['git','-C',str(bundle),'rev-parse','HEAD'], check=True, text=True, capture_output=True).stdout.strip() - if revision != bundle_sha: - raise ValueError('Bundle revision differs from the requested release') - dirty = subprocess.run(['git','-C',str(bundle),'status','--porcelain','--untracked-files=all'], check=True, text=True, capture_output=True).stdout - if dirty.strip(): - raise ValueError('The pinned release must have no local modifications') - subprocess.run([sys.executable,str(bundle/'scripts/check_release_bundle.py')], check=True, capture_output=True) + try: + _verify_pinned_release(bundle_sha, bundle=bundle) + except RuntimeError as exc: + raise ValueError('Pinned voice bundle authentication failed') from exc + subprocess.run([sys.executable, '-I', str(bundle/'scripts/check_release_bundle.py')], + check=True, capture_output=True, timeout=20) raw = (bundle/'keel-setup/reference/integration_profiles.v1.json').read_bytes() contract = json.loads(raw) if contract.get('version') != 'keel.integration_profiles.v1' or contract.get('qualification_status') != 'unqualified': diff --git a/keel-setup/scripts/setup_state.py b/keel-setup/scripts/setup_state.py index ef1d404..d183b5d 100644 --- a/keel-setup/scripts/setup_state.py +++ b/keel-setup/scripts/setup_state.py @@ -22,6 +22,8 @@ import tempfile from typing import Any +sys.dont_write_bytecode = True + ROOT = pathlib.Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "shared" / "scripts")) from schema_validation import validate as validate_schema # noqa: E402 diff --git a/keel-setup/scripts/verify_execute.py b/keel-setup/scripts/verify_execute.py index 0b265a8..3e166a0 100644 --- a/keel-setup/scripts/verify_execute.py +++ b/keel-setup/scripts/verify_execute.py @@ -10,6 +10,8 @@ import argparse from datetime import datetime import getpass +import hashlib +import stat import json import os import pathlib @@ -136,40 +138,36 @@ def _contains_secret_argument(argv: list[str]) -> bool: return False -def _verify_pinned_release(bundle_sha: str) -> None: - """Authenticate bundle data against the caller's pin without executing it. +def _verify_pinned_release(bundle_sha: str, *, bundle: pathlib.Path | None = None) -> None: + """Authenticate the complete pinned snapshot without executing bundle code. - Keep this gate in each credential entrypoint: importing a sibling to decide - whether that sibling is trusted would run its code before authentication. - The entrypoint and the caller-supplied commit pin are the trust anchors. + Each standalone entrypoint carries this gate because a sibling import cannot + establish its own trust. The entrypoint and caller-supplied pin are trusted. + An explicit bundle is used only by the orchestrator; credential commands + always derive their bundle from the trusted entrypoint's installation path. """ - try: if re.fullmatch(r"[0-9a-f]{40}", bundle_sha) is None: raise ValueError("invalid bundle SHA") - bundle = pathlib.Path(__file__).resolve().parents[2] + bundle = (pathlib.Path(__file__).resolve().parents[2] if bundle is None else bundle.resolve()) def git(*args: str) -> bytes: - # No inherited Git configuration, object replacements, hooks, shell, - # credential, or network operations. All commands below only read. + """Read local Git data without inherited configuration or hooks.""" result = subprocess.run( ["git", "--no-replace-objects", "-c", "core.fsmonitor=false", "-C", str(bundle), *args], env={ - "PATH": "/usr/bin:/bin", - "LANG": "C", - "LC_ALL": "C", - "GIT_CONFIG_NOSYSTEM": "1", - "GIT_CONFIG_GLOBAL": "/dev/null", - "GIT_NO_LAZY_FETCH": "1", - "GIT_OPTIONAL_LOCKS": "0", + "PATH": "/usr/bin:/bin", "LANG": "C", "LC_ALL": "C", + "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_GLOBAL": "/dev/null", + "GIT_NO_LAZY_FETCH": "1", "GIT_OPTIONAL_LOCKS": "0", }, - capture_output=True, - timeout=20, - check=True, + capture_output=True, timeout=20, check=True, ) return result.stdout + worktree = pathlib.Path(git("rev-parse", "--show-toplevel").decode().removesuffix("\n")).resolve() + if bundle != worktree: + raise ValueError("bundle must be the Git worktree root") if git("rev-parse", "HEAD").decode().strip() != bundle_sha: raise ValueError("bundle revision mismatch") if git("remote", "get-url", "origin").decode().strip() not in { @@ -179,29 +177,106 @@ def git(*args: str) -> bytes: "ssh://git@github.com/keelapi/keel-setup.git", }: raise ValueError("unofficial bundle origin") - if (git("ls-files", "--others", "--exclude-standard") - or git("diff", "--cached", "--name-only", "--no-ext-diff", - "--no-textconv", bundle_sha)): - raise ValueError("bundle checkout is not clean") - - # Compare actual bytes, not index stat data or a mutable SHA256SUMS. - # This also catches tracked edits hidden by assume-unchanged flags. - entries = git("ls-tree", "-rz", bundle_sha).split(b"\0") - if len(entries) < 2: + if git("diff", "--cached", "--name-only", "--no-ext-diff", "--no-textconv", bundle_sha): + raise ValueError("bundle index is not clean") + + def object_bytes(kind: str, oid: str) -> bytes: + """Authenticate raw Git objects, including the commit and trees.""" + if re.fullmatch(r"[0-9a-f]{40}", oid) is None: + raise ValueError("invalid object ID") + size = int(git("cat-file", "-s", oid)) + if not 0 <= size <= 8 * 1024 * 1024: + raise ValueError("bundle object exceeds verification limit") + data = git("cat-file", kind, oid) + header = f"{kind} {len(data)}\0".encode("ascii") + if len(data) != size or hashlib.sha1(header + data).hexdigest() != oid: + raise ValueError("Git object differs from its authenticated ID") + return data + + commit = object_bytes("commit", bundle_sha) + tree_line = commit.split(b"\n", 1)[0] + if re.fullmatch(rb"tree [0-9a-f]{40}", tree_line) is None: + raise ValueError("invalid pinned commit tree") + files: dict[pathlib.PurePosixPath, bytes] = {} + total_bytes = 0 + + def tree_files(oid: str, parent: pathlib.PurePosixPath) -> None: + """Walk only entries from independently authenticated tree objects.""" + nonlocal total_bytes + if len(parent.parts) > 32: + raise ValueError("bundle tree exceeds depth limit") + data = object_bytes("tree", oid) + offset = 0 + names: set[str] = set() + while offset < len(data): + end = data.index(b"\0", offset) + mode, raw_name = data[offset:end].split(b" ", 1) + name = raw_name.decode("utf-8") + if (name in {"", ".", ".."} or name.lower() == ".git" + or "/" in name or name in names): + raise ValueError("unsafe or duplicate bundle entry") + names.add(name) + raw_oid = data[end + 1:end + 21] + if len(raw_oid) != 20: + raise ValueError("truncated bundle tree") + offset = end + 21 + relative = parent / name + if mode == b"40000": + tree_files(raw_oid.hex(), relative) + elif mode in {b"100644", b"100755"}: + if len(files) >= 4096: + raise ValueError("bundle exceeds file limit") + content = object_bytes("blob", raw_oid.hex()) + total_bytes += len(content) + if total_bytes > 64 * 1024 * 1024: + raise ValueError("bundle exceeds byte limit") + files[relative] = content + else: + raise ValueError("unsupported bundle entry") + + tree_files(tree_line[5:].decode("ascii"), pathlib.PurePosixPath()) + if not files: raise ValueError("empty bundle tree") - for entry in entries[:-1]: - metadata, raw_path = entry.split(b"\t", 1) - mode, kind, oid = metadata.decode("ascii").split() - relative = pathlib.PurePosixPath(raw_path.decode("utf-8")) - if (mode not in {"100644", "100755"} or kind != "blob" - or relative.is_absolute() or ".." in relative.parts): - raise ValueError("unsupported bundle entry") - path = bundle.joinpath(*relative.parts) - if any(bundle.joinpath(*relative.parts[:i]).is_symlink() - for i in range(1, len(relative.parts) + 1)): - raise ValueError("symlink in bundle path") - if path.read_bytes() != git("cat-file", "blob", oid): - raise ValueError("bundle file differs from pinned bytes") + + # Include ignored additions and reject symlinked directories. Git metadata + # alone is exempt, including the .git file used by linked worktrees. + actual: set[pathlib.PurePosixPath] = set() + def walk_error(error: OSError) -> None: + """Fail closed when any part of the checkout cannot be enumerated.""" + raise error + + for current, directories, filenames in os.walk(bundle, followlinks=False, onerror=walk_error): + directory = pathlib.Path(current) + if directory == bundle: + directories[:] = [name for name in directories if name != ".git"] + filenames = [name for name in filenames if name != ".git"] + for name in directories: + if (directory / name).is_symlink(): + raise ValueError("symlink in bundle directory") + actual.update(pathlib.PurePosixPath((directory / name).relative_to(bundle).as_posix()) + for name in filenames) + if actual != set(files): + raise ValueError("checkout files differ from the pinned allowlist") + + # Descriptor-relative traversal refuses parent symlinks. Nonblocking open + # and fstat reject FIFOs/devices before reading, with bounded file reads. + for relative, expected in files.items(): + directory_fd = os.open(bundle, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + for part in relative.parts[:-1]: + child_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=directory_fd) + os.close(directory_fd) + directory_fd = child_fd + fd = os.open(relative.name, os.O_RDONLY | os.O_NONBLOCK | os.O_NOFOLLOW, + dir_fd=directory_fd) + with os.fdopen(fd, "rb") as stream: + if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode): + raise ValueError("bundle entry is not a regular file") + if stream.read(len(expected) + 1) != expected: + raise ValueError("bundle file differs from pinned bytes") + finally: + os.close(directory_fd) except Exception as exc: raise RuntimeError("pinned release verification failed") from exc diff --git a/keel-setup/tests/test_authoring_context.py b/keel-setup/tests/test_authoring_context.py index 15c56f7..66d1837 100644 --- a/keel-setup/tests/test_authoring_context.py +++ b/keel-setup/tests/test_authoring_context.py @@ -721,7 +721,7 @@ def setUp(self): def test_helper_is_standard_library_only(self): allowed = { - "__future__", "argparse", "decimal", "getpass", "importlib", "json", + "__future__", "hashlib", "os", "stat", "argparse", "decimal", "getpass", "importlib", "json", "pathlib", "re", "secrets", "subprocess", "sys", "time", "urllib", "warnings", "typing", } imports = [ @@ -737,7 +737,9 @@ def test_helper_is_standard_library_only(self): def test_helper_never_reads_a_credential_environment_variable(self): for reader in ("os.environ", "os.getenv", "environ[", "environ.get", "getenv("): self.assertNotIn(reader, self.source) - self.assertNotIn("import os", self.source) + self.assertIn("os.O_RDONLY", self.source) + self.assertNotIn("os.O_WRONLY", self.source) + self.assertNotIn("os.O_RDWR", self.source) def test_helper_declares_no_credential_argument(self): for word in ("--key", "--api-key", "--token", "--secret", "--credential"): diff --git a/keel-setup/tests/test_fast_first_run.py b/keel-setup/tests/test_fast_first_run.py index 4c01bff..c216d4f 100644 --- a/keel-setup/tests/test_fast_first_run.py +++ b/keel-setup/tests/test_fast_first_run.py @@ -2,6 +2,8 @@ import ast import importlib.util +import inspect +import io import json import os import pathlib @@ -44,10 +46,15 @@ def setUpClass(cls) -> None: cls.bundle_temp = tempfile.TemporaryDirectory() cls.bundle = pathlib.Path(cls.bundle_temp.name) for relative in ( + "keel-setup/scripts/fast_first_run.py", + "keel-setup/scripts/authoring_context.py", "keel-setup/scripts/inventory.py", "keel-setup/scripts/setup_state.py", "keel-setup/reference/setup-state.schema.json", + "keel-policy/scripts/consume_authoring_context.py", + "keel-policy/scripts/validate_enforceability_report.py", "shared/scripts/schema_validation.py", + "shared/scripts/validate_feedback_report.py", ): target = cls.bundle / relative target.parent.mkdir(parents=True, exist_ok=True) @@ -202,6 +209,98 @@ def test_pre_gate_validation_does_not_execute_target_initialization(self): if command.kwargs["cwd"] == root: self.assertEqual(argv[0], "git", argv) + def test_checker_hidden_from_git_status_never_executes(self): + for flag in ("--assume-unchanged", "--skip-worktree"): + with self.subTest(flag=flag), tempfile.TemporaryDirectory() as temporary: + root = pathlib.Path(temporary) + bundle = root / "bundle" + _git(root, "clone", "-q", str(self.bundle), str(bundle)) + _git(bundle, "remote", "set-url", "origin", "https://github.com/keelapi/keel-setup.git") + marker = root / "checker-executed" + (bundle / "scripts/check_release_bundle.py").write_text( + f"from pathlib import Path\nPath({str(marker)!r}).touch()\n" + "print('PASS: public setup bundle (forged)')\n" + ) + _git(bundle, "update-index", flag, "scripts/check_release_bundle.py") + self.assertEqual(_git(bundle, "status", "--porcelain"), "") + with self.assertRaises(fast.PipelineFailure): + fast.verify_release(bundle, self.bundle_sha) + self.assertFalse(marker.exists()) + + def test_documented_orchestrator_ignores_pythonpath_startup_hook(self): + root = self._repo() + marker = root.parent / (root.name + "-startup-executed") + self.addCleanup(marker.unlink, missing_ok=True) + (root / "sitecustomize.py").write_text( + f"from pathlib import Path\nPath({str(marker)!r}).touch()\n" + ) + _git(root, "add", ".") + _git(root, "-c", "user.name=Keel Test", "-c", "user.email=keel-test@example.invalid", + "commit", "-qm", "startup hook fixture") + with mock.patch.object(fast, "_run", wraps=fast._run) as calls: + self.assertEqual(self._run(self._repo())["outcome"], "ready_for_human") + checker_calls = [call.args[0] for call in calls.call_args_list + if any(str(arg).endswith("check_release_bundle.py") for arg in call.args[0])] + self.assertTrue(checker_calls) + self.assertTrue(all(command[1] == "-I" for command in checker_calls)) + # Follow the published command shape in a fresh process so Python's own + # startup, rather than an in-process mock, is under test. + result = subprocess.run( + [sys.executable, "-I", str(self.bundle / "keel-setup/scripts/fast_first_run.py"), + "--bundle", str(self.bundle), "--bundle-sha", self.bundle_sha, "--repo", str(root)], + cwd=root, env={**os.environ, "PYTHONPATH": str(root)}, + capture_output=True, text=True, timeout=30, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout)["outcome"], "ready_for_human") + self.assertFalse(marker.exists()) + + def test_gate_implementation_matches_standalone_credential_entrypoints(self): + for name in ("verify_execute.py", "authoring_context.py", "prepare_voice.py"): + module = _load("fast_gate_" + name.removesuffix(".py"), SCRIPT.with_name(name)) + self.assertEqual(inspect.getsource(fast._verify_pinned_release), + inspect.getsource(module._verify_pinned_release)) + + def test_local_helpers_leave_the_authenticated_bundle_clean(self): + for relative in ( + "keel-setup/scripts/inventory.py", "keel-setup/scripts/setup_state.py", + "keel-policy/scripts/consume_authoring_context.py", + "keel-policy/scripts/validate_enforceability_report.py", + "shared/scripts/validate_feedback_report.py", + ): + with self.subTest(relative=relative): + result = subprocess.run( + [sys.executable, "-I", str(self.bundle / relative), "--help"], + capture_output=True, text=True, timeout=20, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse(list(self.bundle.rglob("__pycache__"))) + self.assertEqual(fast.verify_release(self.bundle, self.bundle_sha)["status"], "trusted") + + def test_generated_adapter_supplies_required_names_without_target_imports(self): + # These are controlled source fixtures; the pipeline remains compile-only. + source = fixtures.GOLDEN_APP.replace("from __future__ import annotations\n", "").replace("import os\n", "").replace("from typing import Any\n", "") + source = source.replace("client: Any | None", "client: object | None") + source = source.replace('model=model or os.getenv("OPENAI_MODEL", DEFAULT_MODEL)', + "model=model or DEFAULT_MODEL") + for with_test in (False, True): + with self.subTest(with_test=with_test): + root = self._repo(source, with_test=with_test) + result = self._run(root) + self.assertEqual(result["outcome"], "ready_for_human", result) + generated = (root / "app.py").read_text() + namespace = {"__name__": "controlled_fixture"} + exec(compile(generated, "controlled_fixture.py", "exec"), namespace) + response = io.BytesIO(json.dumps({ + "status": "completed", "governance": {"decision": "allow"}, + "output": {"content": [{"type": "text", "role": "assistant", "text": "summary"}]}, + }).encode()) + response.status = 200 + opener = mock.Mock() + opener.open.return_value = response + with mock.patch.dict(os.environ, {"KEEL_API_KEY": "test-only-placeholder"}): + self.assertEqual(namespace["summarize"]("test", client=opener), "summary") + def test_without_coupled_test_runtime_check_is_not_applicable(self): result = self._run(self._repo(with_test=False)) self.assertEqual(result["outcome"], "ready_for_human", result) diff --git a/keel-setup/tests/test_inventory.py b/keel-setup/tests/test_inventory.py index 63e273a..71ee90e 100644 --- a/keel-setup/tests/test_inventory.py +++ b/keel-setup/tests/test_inventory.py @@ -420,7 +420,7 @@ def test_fresh_golden_path_owns_trust_ignore_and_state_initialization(self): deterministic = text.index("### Deterministic golden path") fallback = text.index("### Model-driven fallback") direct_state_command = text.index( - 'python3 "$BUNDLE/keel-setup/scripts/setup_state.py" --repo-root . --state .keel/setup-state.json', + 'python3 -I "$BUNDLE/keel-setup/scripts/setup_state.py" --repo-root . --state .keel/setup-state.json', fallback, ) @@ -617,6 +617,9 @@ def setUp(self): for relative in ("keel-setup/scripts", "keel-setup/reference", "shared/scripts"): shutil.copytree(source / relative, self.bundle / relative) self.marker = self.app / "counterfeit-executed" + (self.app / "sitecustomize.py").write_text( + f"from pathlib import Path\nPath({str(self.marker)!r}).touch()\n" + ) for relative in ("keel-setup/scripts/inventory.py", "keel-setup/scripts/setup_state.py", "scripts/inventory.py"): target = self.app / relative @@ -655,7 +658,7 @@ def run_command(self, command): "PATH": "prepared.py"} args = [replacements.get(arg, arg.replace("$BUNDLE", str(self.bundle))) for arg in args] result = subprocess.run(args, cwd=self.app, capture_output=True, text=True, - env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}, timeout=20) + env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1", "PYTHONPATH": str(self.app)}, timeout=20) self.assertFalse(self.marker.exists(), "published command executed a target-side helper") self.assertEqual(result.returncode, 0, result.stderr) return result.stdout @@ -696,7 +699,12 @@ def test_all_published_helper_commands_use_the_authenticated_root(self): text = SKILL.read_text(encoding="utf-8") for line in text.splitlines(): if line.strip().startswith("python3 "): - self.assertRegex(line.strip(), r'^python3 "\$BUNDLE/[^" ]+\.py"(?: |$)') + self.assertRegex(line.strip(), r'^python3 -I "\$BUNDLE/[^" ]+\.py"(?: |$)') + for document in SKILL.parents[1].rglob("*.md"): + for line in document.read_text().splitlines(): + if line.strip().startswith("python3 ") and ".py" in line: + self.assertTrue(line.strip().startswith("python3 -I "), + f"unisolated published command in {document}: {line}") self.assertIn("canonical absolute", text) self.assertIn("symlink", text) diff --git a/keel-setup/tests/test_prepare_voice.py b/keel-setup/tests/test_prepare_voice.py index 2767cc4..2c61bc6 100644 --- a/keel-setup/tests/test_prepare_voice.py +++ b/keel-setup/tests/test_prepare_voice.py @@ -21,34 +21,52 @@ def setUp(self): target.parent.mkdir(parents=True) target.write_bytes(contract.read_bytes()) - def runner(self, args, **kwargs): - self.assertNotIn('shell',kwargs) - stdout='a'*40 if 'rev-parse' in args else '' - return subprocess.CompletedProcess(args,0,stdout=stdout) + def git(self, *args): + return subprocess.run(['git', '-C', str(self.bundle), *args], + check=True, capture_output=True, text=True).stdout.strip() + + def authenticate_fixture(self): + checker = self.bundle / 'scripts/check_release_bundle.py' + checker.parent.mkdir() + checker.write_text("print('PASS: public setup bundle (fixture)')\n") + self.git('init', '-q') + self.git('config', 'user.name', 'Voice test') + self.git('config', 'user.email', 'voice@example.invalid') + self.git('remote', 'add', 'origin', 'https://github.com/keelapi/keel-setup.git') + self.git('add', '.') + self.git('commit', '-qm', 'fixture') + return self.git('rev-parse', 'HEAD') def test_bound_release_reports_preparation_and_gates_only(self): - with patch.object(module.subprocess,'run',side_effect=self.runner) as calls: - result=module.prepare(self.bundle,'a'*40,'elevenlabs_agents_gateway_ws_v1') - self.assertEqual(result['stage'],'preparation_only') - self.assertIn('qualified_pricing_admission',result['unresolved_gates']) - self.assertEqual(calls.call_count,3) - self.assertNotIn('certified',json.dumps(result)) + pin = self.authenticate_fixture() + with patch.object(module.subprocess, 'run', wraps=subprocess.run) as calls: + result = module.prepare(self.bundle, pin, 'elevenlabs_agents_gateway_ws_v1') + self.assertEqual(result['stage'], 'preparation_only') + self.assertIn('qualified_pricing_admission', result['unresolved_gates']) + checker_calls = [call.args[0] for call in calls.call_args_list + if any(str(arg).endswith('check_release_bundle.py') for arg in call.args[0])] + self.assertEqual(len(checker_calls), 1) + self.assertEqual(checker_calls[0][1], '-I') + self.assertNotIn('certified', json.dumps(result)) def test_dirty_or_wrong_revision_stops_before_running_bundle_code(self): - for outputs in [('b'*40,),('a'*40,' M keel-setup/scripts/prepare_voice.py')]: - replies=iter(outputs) - def changed(args,**_kwargs): - return subprocess.CompletedProcess(args,0,stdout=next(replies)) - with patch.object(module.subprocess,'run',side_effect=changed) as calls: - with self.assertRaises(ValueError): - module.prepare(self.bundle,'a'*40,'elevenlabs_agents_gateway_ws_v1') - self.assertLessEqual(calls.call_count,2) + pin = self.authenticate_fixture() + with self.assertRaises(ValueError): + module.prepare(self.bundle, 'b' * 40, 'elevenlabs_agents_gateway_ws_v1') + marker = self.bundle.parent / (self.bundle.name + '-checker-ran') + self.addCleanup(marker.unlink, missing_ok=True) + checker = self.bundle / 'scripts/check_release_bundle.py' + checker.write_text(f"from pathlib import Path\nPath({str(marker)!r}).touch()\n") + self.git('update-index', '--assume-unchanged', 'scripts/check_release_bundle.py') + with self.assertRaises(ValueError): + module.prepare(self.bundle, pin, 'elevenlabs_agents_gateway_ws_v1') + self.assertFalse(marker.exists()) def test_no_direct_audio_or_unsupported_webrtc_as_voice_proof(self): - with patch.object(module.subprocess,'run',side_effect=self.runner): - for profile in ['elevenlabs_direct_audio_v1','elevenlabs_agents_webrtc_v1','missing']: - with self.assertRaises(ValueError): - module.prepare(self.bundle,'a'*40,profile) + pin = self.authenticate_fixture() + for profile in ['elevenlabs_direct_audio_v1','elevenlabs_agents_webrtc_v1','missing']: + with self.assertRaises(ValueError): + module.prepare(self.bundle, pin, profile) if __name__=='__main__': diff --git a/keel-setup/tests/test_verify_execute.py b/keel-setup/tests/test_verify_execute.py index 1835313..dffb9ee 100644 --- a/keel-setup/tests/test_verify_execute.py +++ b/keel-setup/tests/test_verify_execute.py @@ -16,6 +16,7 @@ import urllib.request import uuid import warnings +import zlib from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from unittest import mock @@ -760,6 +761,83 @@ def test_gate_implementations_remain_identical(self): self.assertEqual(inspect.getsource(verify_execute._verify_pinned_release), inspect.getsource(self.authoring._verify_pinned_release)) + def assert_gates_refuse_before_prompt(self): + """Exercise the command boundary, not just its private verifier.""" + for module in self.gates(): + with self.subTest(module=module.__name__), \ + mock.patch.object(module, "__file__", str(self.sibling.with_name("trusted.py"))), \ + mock.patch.object(module, "_read_hidden_runtime_key") as prompt, \ + mock.patch.object(module, "_open") as network, \ + contextlib.redirect_stderr(io.StringIO()): + args = ["--bundle-sha", self.pin] + if module is verify_execute: + args.append("--hidden-input") + self.assertEqual(module.main(args), 2) + prompt.assert_not_called() + network.assert_not_called() + + def test_ignored_extras_including_cache_payloads_are_rejected(self): + for relative in (".env.local", "__pycache__/payload.py", "__pycache__/payload.pyc"): + with self.subTest(relative=relative): + extra = self.bundle / relative + extra.parent.mkdir(exist_ok=True) + extra.write_text("untrusted content") + (self.bundle / ".git/info/exclude").write_text(".env*\n__pycache__/\n") + self.assertEqual(self.git("status", "--porcelain"), "") + self.assert_gates_refuse_before_prompt() + extra.unlink() + + def test_nested_bundle_is_rejected_before_prompt(self): + original = self.sibling + self.sibling = self.bundle / ".ignored/keel-setup/scripts/fast_first_run.py" + self.sibling.parent.mkdir(parents=True) + (self.bundle / ".git/info/exclude").write_text(".ignored/\n") + self.assert_gates_refuse_before_prompt() + self.sibling = original + + @unittest.skipUnless(hasattr(os, "mkfifo"), "POSIX FIFO required") + def test_tracked_fifo_is_rejected_without_reading_or_prompting(self): + self.sibling.unlink() + os.mkfifo(self.sibling) + self.git("update-index", "--assume-unchanged", "keel-setup/scripts/fast_first_run.py") + self.assert_gates_refuse_before_prompt() + + def test_linked_worktree_remains_supported(self): + with tempfile.TemporaryDirectory() as temporary: + linked = pathlib.Path(temporary) / "linked release" + self.git("worktree", "add", "--detach", str(linked), self.pin) + for module in self.gates(): + with mock.patch.object(module, "__file__", str(linked / "keel-setup/scripts/trusted.py")): + module._verify_pinned_release(self.pin) + + def forge_object(self, kind, path): + """Put different valid snapshot data under an original object's ID.""" + original_ref = self.pin + (":" + path if path is not None else "") + original_oid = self.git("rev-parse", original_ref).strip() + self.sibling.write_text("def verify_release(*args): return 'forged'\n") + self.git("add", ".") + self.git("commit", "-qm", "forged snapshot") + forged_ref = "HEAD" + (":" + path if path is not None else "") + data = subprocess.check_output(["git", "-C", str(self.bundle), "cat-file", kind, forged_ref]) + self.git("reset", "--mixed", self.pin) + self.git("update-index", "--assume-unchanged", "keel-setup/scripts/fast_first_run.py") + loose = self.bundle / ".git/objects" / original_oid[:2] / original_oid[2:] + loose.unlink() + loose.write_bytes(zlib.compress(f"{kind} {len(data)}\0".encode() + data)) + self.assert_gates_refuse_before_prompt() + + def test_forged_loose_blob_is_rejected(self): + self.forge_object("blob", "keel-setup/scripts/fast_first_run.py") + + def test_forged_nested_tree_is_rejected(self): + self.forge_object("tree", "keel-setup/scripts") + + def test_forged_root_tree_is_rejected(self): + self.forge_object("tree", "") + + def test_forged_pinned_commit_is_rejected(self): + self.forge_object("commit", None) + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/scripts/check_release_bundle.py b/scripts/check_release_bundle.py index 7ea0ba0..74e7957 100644 --- a/scripts/check_release_bundle.py +++ b/scripts/check_release_bundle.py @@ -12,7 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] PUBLIC_RELEASE_VERSION = "2026-10-22.1" -PRODUCT_SOURCE_SHA256 = "ffff15958628a01ce4238b5fa9290ca9900c3e60bb010b153c22ecf53ffcc919" +PRODUCT_SOURCE_SHA256 = "513568419e76edf18ee1fa494d7c080ecb8ce96f9dfb9832aed6a1334edfe719" PUBLICATION_LAYER_FILES = [ ".github/workflows/ci.yml", ".gitignore", diff --git a/shared/feedback-report.template.md b/shared/feedback-report.template.md index bf6bcde..1bbb469 100644 --- a/shared/feedback-report.template.md +++ b/shared/feedback-report.template.md @@ -31,7 +31,7 @@ the appropriate manual channel. A security concern must use a private security c Validate and preview locally: ```text -python3 shared/scripts/validate_feedback_report.py report.json --preview +python3 -I shared/scripts/validate_feedback_report.py report.json --preview ``` For every populated optional-context field, add its separate flag only after the human approves that diff --git a/shared/scripts/validate_feedback_report.py b/shared/scripts/validate_feedback_report.py index f855c64..6db9d16 100644 --- a/shared/scripts/validate_feedback_report.py +++ b/shared/scripts/validate_feedback_report.py @@ -9,6 +9,8 @@ import sys from typing import Any +sys.dont_write_bytecode = True +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from schema_validation import validate as validate_schema MAX_BYTES = 16_384