mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 10:07:24 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The native Runner starts each agent harness and owns its lifecycle, credentials and recovery > - Google Antigravity is Google's only first-party coding harness, and it is the harness for Gemini 4 Neon > - The Runner had an Antigravity integration, but only as a pending candidate: ACP server 1.4.3, macOS ARM64 only, Google sign-in only, closed unless an operator opened it for one company and one model > - Cloud sandboxes run Linux and use API keys, so the candidate could not run there, and it had one attended test cell > - This pull request moves the integration to ACP server 1.5.2, makes it run on Linux and with a Gemini API key, adds the tests the other ACPX harnesses have, and removes the code paths that would block recovery after release > - The benefit is that the release of Antigravity becomes a small declaration change after the live suites pass. The profile stays `pending` in this pull request. ## Linked Issues or Issue Description Refs #98 Refs #6559 Refs #8523 Refs #21121 (a separate legacy-style `agy_local` adapter that uses the CLI print protocol; this pull request does not replace or include it) ## What Changed **Runtime** - Pin Antigravity ACP server 1.5.2 (was 1.4.3). Owned admission patch is `1.5.2-paperclip.2`. - Verified patched closures for `darwin-arm64`, `linux-x64` and `linux-arm64`. `darwin-x64` stays inventory-only. - The patcher reads Mach-O and ELF builds. It signs macOS output only. One admission source serves all platforms. - Platform gates in TypeScript, Rust, the sidecar schema and the server admit each host that has a verified closure. **Auth and models** - Gemini API-key auth reaches an exact-model session receipt. Admission accepts a model only when the base model and the thinking level both match the requested ID. - API-key connections get a model list on local and cloud environments. The list is generated at build time from the pinned runtime. The server starts no process to read it. - Gemini 4 Neon, Carbon, Argon and Hydrogen are selectable. The picker marks them "needs a paid Gemini API plan" for API-key connections. - One shared module maps model ID to family and thinking level. - `google/gemini-4-neon` is added to the OpenCode model list. A new model audit is in `doc/adapter-model-audit-2026-11-22.md`. **Lifecycle and failures** - A provider error no longer completes the turn. The driver classifies it: overloaded, rate limit, quota, auth rejected, model unavailable. - Overload retries are bounded (3 attempts, about 14 seconds). - A refused session reload maps to incompatible saved state, so the automatic replacement conversation applies. - Server gates that refused restart recovery, remote targets and shared state for Antigravity now apply only while the profile is pending. - A Google sign-in connection with a cloud environment is refused at save and at Test, with a plain message. - A released profile rejects candidate grants in TypeScript and in Rust. **Launch cost and integrity (all native ACPX providers)** - Each closure is verified one time into a sealed read-only store. Later launches check file identities and hash the exact executable they start. - Remote provider-pack verification is recorded per sandbox lease. Later runs check kernel identity and fall back to the full hash on any difference. - Superseded stores are removed in the background after a launch. **Provider pack and image** - The provider pack carries Antigravity for `linux-x64` as a candidate provider. It becomes an ordinary provider from the profile status alone. - The Daytona image build accepts the candidate. A credential-free smoke runs in the build. **Tests and CI** - New `antigravity-qualification` suite: 24 cells, local and Daytona. - New model lineup suites: 14 API-key cells and 14 Gemini 4 cells. Each cell requires the exact model in the Runner receipt. - Antigravity can run the `chat-features` cases with `--profile runner-acpx-antigravity`. - `runner-full-stack-e2e.yml` passes `GEMINI_API_KEY` for the new profile and derives candidate providers from the selected Daytona cells. **Docs** - `doc/plans/2026-11-22-antigravity-qualification.md` is the current release contract, acceptance ledger and operator recipe. ## Verification Commands that passed on the final revision: - `pnpm build` - Typecheck for all packages, including the runner-e2e test projects - `pnpm test:e2e:runner:unit`: 11,665 Vitest tests passed, 25 skipped; 386 node tests passed - `cargo test -p paperclip-runner-core -- --test-threads=4`: 1,199 passed, 2 failed. The 2 failures are Codex transport timing tests that pass alone and on `master`. - `cargo fmt --check`, `check:acpx-profiles`, `check:protocol-types`, `node scripts/check-maps.mjs` - Native patch tests: 9 of 9 on `darwin-arm64` and 9 of 9 on `linux-x64` - UI picker tests: 397 of 397 Known failures that also fail on `master`: - 11 runner package script tests (browser, Pi and package-boundary checks) - 6 `runtime-selection` tests that read an untracked local skill file Live evidence, without a prompt: - Clean provisioning on `darwin-arm64` and on `linux-x64` in a Daytona sandbox. The closure digests reproduce. A changed or missing file is rejected. - `initialize` reports 1.5.2. An API-key session returns a receipt for exactly `gemini-3.8-flash-low` and the exact instruction bytes, on both platforms. - All 28 model IDs (14 Gemini 3, 14 Gemini 4) return an exact receipt under an API key. - A session survives a process kill and resumes in a new process with exact receipts, on both platforms. - The server's remote path verifies the provider pack in a Daytona sandbox. - Run start to native `initialize`: 3.45 s to 1.46 s on macOS, 3.65 s to 1.74 s on Linux x64, before the per-launch executable hash was restored (about 60 ms on macOS; not measured on Linux). - Remote pack verification on a reused sandbox lease: about 4.3 s to about 0.25 s. Live evidence, with a prompt, on an already-released harness: - Pi native, `pi-native.runner-acpx-pi.local.agent-files-fresh-run`, on `darwin-arm64` at `427e9b088b`: 1 of 1 passed, 14 of 14 checks, both native runs succeeded (25.5 s and 25.7 s). The process started from the new launch store with no fallback warning. - The same cell and `native-pending-controller-restart` failed in the paid workflow on this branch and on `master` in the same way, before any native start. The workflow does not install the Pi runtime for local cells, so the agent setup check fails. That is a workflow gap, not part of this change. **Not run.** No Antigravity prompt completed on 1.5.2 on any platform. The only Gemini key available is on the free tier, and Google returned 503 or 429 for each attempt on two days. These gates are open: - All 24 `antigravity-qualification` cells - Both model lineup suites, including inference on Gemini 4 Neon - The attended Google sign-in journey on 1.5.2 - The chat cases under Antigravity - Image pull time and startup time on a published image - A native start on `linux-arm64` - A live provider-death cell for Kimi, Pi or Copilot on the new launch store (one ordinary Pi cell passed live; see above) ## Risks - **The launch store changes how every native ACPX provider starts** (Kimi, Copilot, Cursor, Pi), not only Antigravity. A review found two defects in the first version (an executable swap was possible, and Pi launches broke). Both are fixed with tests. One live Pi cell passed on this branch on macOS. No live provider-death cell and no Linux cell ran for those providers. - The profile digest changes. Saved Antigravity candidate sessions and existing candidate grants stop working. The new release refuses old state by name and starts a replacement conversation. - The Linux provider pack and the Daytona image grow by about 834 MB (about 274 MB compressed) when Antigravity is included. - The pack verification record is in server memory. The first run after a server restart pays the full hash again. - Antigravity 1.5.2 reads the workspace `GEMINI.md` and `AGENTS.md` as user rules. This is deliberate and matches Codex. Any other rule file is refused. - Orchestrator mode is not available. ACP server 1.5.2 does not expose it. - Antigravity stays `pending`. Normal users cannot run it until a later change removes the pending status. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) planned, briefed and integrated the work, with tool use. - Claude Opus 5.5 (`claude-opus-5-5`) subagents wrote the code and ran the tests, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
450 lines
29 KiB
Python
450 lines
29 KiB
Python
import importlib.util
|
|
from contextlib import contextmanager
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import select
|
|
import shutil
|
|
import signal
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
from types import SimpleNamespace
|
|
import unittest
|
|
from unittest.mock import patch, Mock, call
|
|
|
|
spec = importlib.util.spec_from_file_location('kimi_fault', Path(__file__).with_name('kimi-provider-fault.py'))
|
|
fault = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(fault)
|
|
BOOT = '12345678-1234-1234-1234-123456789abc'
|
|
ROOT = {'pid': 21, 'ppid': 1, 'startTicks': '100', 'bootId': BOOT}
|
|
PARENT = {'pid': 22, 'ppid': 21, 'startTicks': '101', 'bootId': BOOT}
|
|
TARGET = {'pid': 23, 'ppid': 22, 'startTicks': '102', 'bootId': BOOT}
|
|
LAUNCH = '/tmp/paperclip-acpx-native-fixture/launch'
|
|
STORE = '/tmp/paperclip-verified-native-501'
|
|
RUNTIME = '/workspace/.paperclip-runtime/paperclip-runner'
|
|
HOST_NODE = fault.PACK + '/node_modules/node/bin/node'
|
|
LOADER = 'admitted guarded loader'
|
|
CANCELLED = False
|
|
|
|
|
|
def check_cancelled():
|
|
if CANCELLED:
|
|
raise KeyboardInterrupt('calibration cancelled')
|
|
|
|
|
|
class IdentityTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.entries = [{'path': name, 'sha256': fault.digest(name.encode()), 'size': len(name), 'executable': name == fault.NODE} for name in sorted([fault.NODE, fault.ENTRY])]
|
|
self.config = {'root': ROOT, 'binding': {'remoteCwd': '/workspace', 'runId': 'run'}, 'runtimeEnvironmentLeaseId': 'workspace-id',
|
|
'runnerdSha256': 'sha256:' + fault.digest(b'runner'), 'nodeSha256': 'sha256:' + fault.digest(fault.NODE.encode()),
|
|
'guardLoaderSha256': 'sha256:' + fault.digest(LOADER.encode()), 'closureSha256': fault.digest(json.dumps(self.entries, separators=(',', ':')).encode()),
|
|
'bootstrapTemplate': 'bootstrap ' + fault.PLACEHOLDER + ' ' + fault.LAUNCH_PLACEHOLDER, 'guardTemplate': 'const digests={};'}
|
|
self.dist = STORE + '/' + self.config['closureSha256'] + '/distribution'
|
|
bootstrap, guard = fault.expected_sources(self.config, LAUNCH, self.dist, self.entries)
|
|
self.paths = {fault.NODE: self.dist + '/' + fault.NODE, fault.ENTRY: self.dist + '/' + fault.ENTRY, fault.BOOTSTRAP: LAUNCH + '/' + fault.BOOTSTRAP, fault.GUARD: LAUNCH + '/' + fault.GUARD}
|
|
self.files = {self.paths[fault.NODE]: (fault.NODE.encode(), (1, 100)), self.paths[fault.ENTRY]: (fault.ENTRY.encode(), (1, 101)),
|
|
self.paths[fault.BOOTSTRAP]: (bootstrap, (1, 102)), self.paths[fault.GUARD]: (guard, (1, 103)),
|
|
RUNTIME + '/bin/paperclip-runnerd': (b'runner', (1, 90)), HOST_NODE: (fault.NODE.encode(), (1, 110)),
|
|
fault.PACK + '/provider-assets/kimi/linux-x64/native-closure.json': (json.dumps({'entries': self.entries}, indent=2).encode(), (1, 80))}
|
|
self.table = {21: ROOT, 22: PARENT, 23: TARGET}
|
|
self.args = {21: [RUNTIME + '/bin/paperclip-runnerd', '--run-id', 'run', '--environment-lease-id', 'workspace-id', '--lifecycle-mode', 'per_turn', '--state-dir', RUNTIME + '/sessions/' + 'a' * 64 + '/runner'],
|
|
22: [HOST_NODE, '--eval', LOADER, LAUNCH, fault.BOOTSTRAP, '0', '0', 'commonjs', '[]', '0'], 23: ['kimi-code']}
|
|
self.links = {'/proc/22/exe': HOST_NODE, '/proc/23/exe': self.paths[fault.NODE], '/proc/24/exe': self.paths[fault.NODE]}
|
|
self.stats = {'/proc/21/exe': (90, stat.S_IFREG), '/proc/23/exe': (100, stat.S_IFREG), '/proc/23/fd/7': (100, stat.S_IFREG),
|
|
'/proc/24/exe': (100, stat.S_IFREG), '/proc/24/fd/7': (100, stat.S_IFREG),
|
|
'/proc/22/exe': (110, stat.S_IFREG), '/proc/22/fd/10': (110, stat.S_IFREG), '/proc/22/fd/4': (2, stat.S_IFDIR), '/proc/22/fd/3': (3, stat.S_IFIFO)}
|
|
def checked_fixture_file(name, *args):
|
|
if name.startswith('/memfd:'):
|
|
raise FileNotFoundError(2, 'deleted executable fixture')
|
|
return self.files[name]
|
|
patches = [patch.object(fault, 'proc', side_effect=lambda pid, boot: self.table[pid]), patch.object(fault, 'argv', side_effect=lambda pid: self.args[pid]),
|
|
patch.object(fault, 'checked_runner', side_effect=lambda name: self.files[name]), patch.object(fault, 'checked_file', side_effect=checked_fixture_file),
|
|
patch.object(Path, 'read_text', return_value=BOOT), patch.object(os, 'listdir', side_effect=lambda name: [str(pid) for pid in self.table]),
|
|
patch.object(os, 'getpgid', return_value=21), patch.object(os, 'lstat', return_value=SimpleNamespace(st_mode=stat.S_IFDIR | 0o500, st_dev=1, st_ino=2)),
|
|
patch.object(os.path, 'realpath', side_effect=lambda name: self.links.get(name, name)),
|
|
patch.object(os, 'readlink', return_value='/workspace'), patch.object(os, 'stat', side_effect=lambda name: SimpleNamespace(st_dev=1, st_ino=self.stats[name][0], st_mode=self.stats[name][1]))]
|
|
for mocked in patches:
|
|
mocked.start()
|
|
self.addCleanup(mocked.stop)
|
|
|
|
@contextmanager
|
|
def parent_descriptor(self, anonymous=False, content=None):
|
|
content = fault.NODE.encode() if content is None else content
|
|
def metadata(inode=110):
|
|
return SimpleNamespace(st_mode=stat.S_IFREG | 0o500, st_dev=1, st_ino=inode, st_size=len(content), st_mtime_ns=3, st_ctime_ns=4, st_nlink=0 if anonymous else 1)
|
|
original_stat = os.stat
|
|
def proc_stat(path):
|
|
if path in ('/proc/22/exe', '/proc/22/fd/10'):
|
|
return metadata(self.stats[path][0])
|
|
return original_stat(path)
|
|
kernel = SimpleNamespace(F_GET_SEALS=1034, F_SEAL_SEAL=1, F_SEAL_SHRINK=2, F_SEAL_GROW=4, F_SEAL_WRITE=8, fcntl=lambda fd, op: 15)
|
|
with patch.object(os, 'open', return_value=42), patch.object(os, 'close'), patch.object(os, 'fstat', side_effect=lambda fd: metadata()), patch.object(os, 'read', side_effect=[content, b'']), patch.object(os, 'stat', side_effect=proc_stat), patch.object(os, 'readlink', side_effect=lambda path: '/memfd:paperclip-verified-launch (deleted)' if path == '/proc/self/fd/42' else '/workspace'), patch.object(fault, 'fcntl', kernel, create=True):
|
|
yield
|
|
|
|
def test_memfd_parent_uses_the_live_descriptor_without_reopening_deleted_alias(self):
|
|
self.args[22][0] = '/proc/self/fd/10'
|
|
self.links['/proc/22/exe'] = '/memfd:paperclip-verified-launch (deleted)'
|
|
with self.parent_descriptor(True):
|
|
receipt = fault.inspect(self.config)
|
|
self.assertEqual(receipt['target'], TARGET)
|
|
self.assertFalse(any('/memfd:' in str(call) for call in fault.checked_file.call_args_list))
|
|
|
|
def test_matching_memfd_inode_and_seals_do_not_replace_the_full_node_digest(self):
|
|
self.args[22][0] = '/proc/self/fd/10'
|
|
with self.parent_descriptor(True, b'x' * len(fault.NODE.encode())), self.assertRaisesRegex(RuntimeError, 'parent_node'):
|
|
fault.inspect(self.config)
|
|
|
|
def test_exact_pinned_parent_attests_title_overwritten_child(self):
|
|
receipt = fault.inspect(self.config)
|
|
self.assertEqual(receipt['target'], TARGET)
|
|
self.assertEqual(receipt['ancestry'], [TARGET, PARENT, ROOT])
|
|
self.assertEqual(receipt['entrypointAttribution'], 'pinned_native_bootstrap_parent')
|
|
self.assertFalse(receipt['originalChildArgvAvailable'])
|
|
|
|
def test_held_host_node_descriptor_requires_the_same_inode(self):
|
|
self.args[22][0] = '/proc/self/fd/10'
|
|
with self.parent_descriptor():
|
|
self.assertEqual(fault.inspect(self.config)['target'], TARGET)
|
|
self.stats['/proc/22/fd/10'] = (999, stat.S_IFREG)
|
|
with self.parent_descriptor(), self.assertRaisesRegex(RuntimeError, 'parent_node_descriptor'):
|
|
fault.inspect(self.config)
|
|
|
|
def test_title_alone_and_root_loss_never_select(self):
|
|
self.args[22][4] = 'foreign.cjs'
|
|
with self.assertRaisesRegex(RuntimeError, 'unique_native_child'):
|
|
fault.inspect(self.config)
|
|
self.args[22][4] = fault.BOOTSTRAP
|
|
self.args[23] = ['node']
|
|
with self.assertRaisesRegex(RuntimeError, 'native_title'):
|
|
fault.inspect(self.config)
|
|
|
|
def test_wrong_run_lease_birth_boot_and_root_executable_fail(self):
|
|
for field, value in [('runtimeEnvironmentLeaseId', 'foreign'), ('runnerdSha256', 'sha256:' + '0' * 64), ('nodeSha256', 'sha256:' + '0' * 64), ('closureSha256', '0' * 64), ('guardLoaderSha256', 'sha256:' + '0' * 64)]:
|
|
with self.subTest(field=field), self.assertRaises(RuntimeError):
|
|
fault.inspect({**self.config, field: value})
|
|
for changed in [{'startTicks': '999'}, {'bootId': 'foreign'}, {'ppid': 99}]:
|
|
with self.subTest(changed=changed), self.assertRaises(RuntimeError):
|
|
fault.inspect({**self.config, 'root': {**ROOT, **changed}})
|
|
self.args[21][2] = 'foreign'
|
|
with self.assertRaisesRegex(RuntimeError, 'root_binding'):
|
|
fault.inspect(self.config)
|
|
|
|
def test_native_main_node_guard_bootstrap_and_parent_code_are_exact(self):
|
|
for name in [fault.NODE, fault.ENTRY, fault.GUARD, fault.BOOTSTRAP]:
|
|
original = self.files[self.paths[name]]
|
|
self.files[self.paths[name]] = (b'changed', original[1])
|
|
with self.subTest(name=name), self.assertRaises(RuntimeError):
|
|
fault.inspect(self.config)
|
|
self.files[self.paths[name]] = original
|
|
for index, value in [(2, 'foreign loader'), (5, '1'), (8, '["module"]'), (0, '/foreign/node')]:
|
|
original = self.args[22][index]
|
|
self.args[22][index] = value
|
|
with self.subTest(index=index), self.assertRaises(RuntimeError):
|
|
fault.inspect(self.config)
|
|
self.args[22][index] = original
|
|
|
|
def test_native_child_must_run_from_the_sealed_store_of_the_pinned_closure(self):
|
|
for executable in ['/tmp/paperclip-verified-native-501/' + '0' * 64 + '/distribution/' + fault.NODE,
|
|
'/tmp/paperclip-acpx-native-fixture/distribution/' + fault.NODE,
|
|
'/home/user/paperclip-verified-native-501/' + self.config['closureSha256'] + '/distribution/' + fault.NODE,
|
|
self.dist + '/node/bin/other']:
|
|
with self.subTest(executable=executable), self.assertRaisesRegex(RuntimeError, 'snapshot_path'):
|
|
self.links['/proc/23/exe'] = executable
|
|
fault.inspect(self.config)
|
|
self.links['/proc/23/exe'] = self.paths[fault.NODE]
|
|
self.args[22][3] = '/tmp/paperclip-acpx-native-fixture/distribution'
|
|
with self.assertRaisesRegex(RuntimeError, 'snapshot_path'):
|
|
fault.inspect(self.config)
|
|
|
|
def test_bootstrap_naming_another_store_or_launch_is_refused(self):
|
|
for launch, distribution in [(LAUNCH, STORE + '/' + 'f' * 64 + '/distribution'), ('/tmp/paperclip-acpx-native-other/launch', self.dist)]:
|
|
bootstrap, _ = fault.expected_sources(self.config, launch, distribution, self.entries)
|
|
original = self.files[self.paths[fault.BOOTSTRAP]]
|
|
self.files[self.paths[fault.BOOTSTRAP]] = (bootstrap, original[1])
|
|
with self.subTest(launch=launch), self.assertRaisesRegex(RuntimeError, 'native_bootstrap_bytes'):
|
|
fault.inspect(self.config)
|
|
self.files[self.paths[fault.BOOTSTRAP]] = original
|
|
|
|
def test_live_executable_and_retained_descriptors_must_match(self):
|
|
for name in ['/proc/23/exe', '/proc/23/fd/7', '/proc/22/fd/4']:
|
|
original = self.stats[name]
|
|
self.stats[name] = (999, original[1])
|
|
with self.subTest(name=name), self.assertRaises(RuntimeError):
|
|
fault.inspect(self.config)
|
|
self.stats[name] = original
|
|
self.stats['/proc/22/fd/3'] = (3, stat.S_IFREG)
|
|
with self.assertRaisesRegex(RuntimeError, 'parent_source_pipe'):
|
|
fault.inspect(self.config)
|
|
|
|
def test_cwd_ancestry_birth_and_ambiguity_fail_closed(self):
|
|
with patch.object(os, 'readlink', return_value='/foreign'), self.assertRaisesRegex(RuntimeError, 'cwd'):
|
|
fault.inspect(self.config)
|
|
self.table[23] = {**TARGET, 'startTicks': '99'}
|
|
with self.assertRaisesRegex(RuntimeError, 'unique_native_child'):
|
|
fault.inspect(self.config)
|
|
self.table[23] = TARGET
|
|
self.table[24] = {**TARGET, 'pid': 24}
|
|
self.args[24] = ['kimi-code']
|
|
with self.assertRaisesRegex(RuntimeError, 'unique_native_child'):
|
|
fault.inspect(self.config)
|
|
|
|
def test_canonical_closure_metadata_rejects_replaced_unsorted_or_open_entries(self):
|
|
for changed in [list(reversed(self.entries)), [*self.entries, self.entries[-1]], [{**self.entries[0], 'path': '../escape'}, self.entries[1]], [{**self.entries[0], 'extra': True}, self.entries[1]]]:
|
|
with self.subTest(changed=changed), self.assertRaises(RuntimeError):
|
|
fault.parse_closure(json.dumps({'entries': changed}).encode(), self.config['closureSha256'])
|
|
|
|
|
|
class ParentDescriptorTests(unittest.TestCase):
|
|
def setUp(self):
|
|
self.content = b'pinned node bytes'
|
|
self.before = SimpleNamespace(st_mode=stat.S_IFREG | 0o500, st_dev=1, st_ino=110, st_size=len(self.content), st_mtime_ns=3, st_ctime_ns=4, st_nlink=0)
|
|
self.stats = {'/proc/22/fd/10': self.before, '/proc/22/exe': self.before}
|
|
self.opened = Mock(return_value=42)
|
|
self.closed = Mock()
|
|
self.fstat = Mock(side_effect=lambda fd: self.before)
|
|
self.read = Mock(side_effect=[self.content, b''])
|
|
self.readlink = Mock(return_value='/memfd:paperclip-verified-launch (deleted)')
|
|
self.kernel = SimpleNamespace(F_GET_SEALS=1034, F_SEAL_SEAL=1, F_SEAL_SHRINK=2, F_SEAL_GROW=4, F_SEAL_WRITE=8, fcntl=Mock(return_value=15))
|
|
patches = [patch.object(os, 'open', self.opened), patch.object(os, 'close', self.closed), patch.object(os, 'fstat', self.fstat), patch.object(os, 'read', self.read), patch.object(os, 'stat', side_effect=lambda path: self.stats[path]), patch.object(os, 'readlink', self.readlink), patch.object(fault, 'fcntl', self.kernel, create=True)]
|
|
for mocked in patches:
|
|
mocked.start()
|
|
self.addCleanup(mocked.stop)
|
|
|
|
def test_sealed_memfd_requires_complete_bytes_and_same_kernel_executable(self):
|
|
self.assertEqual(fault.checked_parent_descriptor(22), (self.content, (1, 110)))
|
|
self.opened.assert_called_once_with('/proc/22/fd/10', os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC)
|
|
self.kernel.fcntl.assert_has_calls([call(42, 1034), call(42, 1034)])
|
|
self.closed.assert_called_once_with(42)
|
|
|
|
def test_linked_descriptor_keeps_regular_single_link_checks_without_memfd_claim(self):
|
|
self.before.st_nlink = 1
|
|
self.assertEqual(fault.checked_parent_descriptor(22), (self.content, (1, 110)))
|
|
self.kernel.fcntl.assert_not_called()
|
|
self.readlink.assert_not_called()
|
|
|
|
def test_every_missing_kernel_seal_fails_before_read(self):
|
|
for bit in (1, 2, 4, 8):
|
|
with self.subTest(bit=bit):
|
|
self.kernel.fcntl.return_value = 15 ^ bit
|
|
with self.assertRaisesRegex(RuntimeError, 'parent_memfd_seals'):
|
|
fault.checked_parent_descriptor(22)
|
|
self.read.assert_not_called()
|
|
self.assertEqual(self.closed.call_count, 4)
|
|
|
|
def test_an_unlinked_regular_file_cannot_impersonate_the_authenticated_memfd(self):
|
|
self.readlink.return_value = '/tmp/node (deleted)'
|
|
with self.assertRaisesRegex(RuntimeError, 'parent_memfd_required'):
|
|
fault.checked_parent_descriptor(22)
|
|
self.read.assert_not_called()
|
|
self.kernel.fcntl.assert_not_called()
|
|
|
|
def test_memfd_write_mode_and_missing_seal_api_fail_closed(self):
|
|
self.before.st_mode = stat.S_IFREG | 0o700
|
|
with self.assertRaisesRegex(RuntimeError, 'parent_memfd_required'):
|
|
fault.checked_parent_descriptor(22)
|
|
self.before.st_mode = stat.S_IFREG | 0o500
|
|
del self.kernel.F_GET_SEALS
|
|
with self.assertRaisesRegex(RuntimeError, 'parent_memfd_required'):
|
|
fault.checked_parent_descriptor(22)
|
|
self.read.assert_not_called()
|
|
|
|
def test_different_held_descriptor_or_executable_never_attests(self):
|
|
for path in ('/proc/22/fd/10', '/proc/22/exe'):
|
|
with self.subTest(path=path):
|
|
self.stats[path] = SimpleNamespace(**{**vars(self.before), 'st_ino': 999})
|
|
with self.assertRaisesRegex(RuntimeError, 'parent_node_descriptor'):
|
|
fault.checked_parent_descriptor(22)
|
|
self.stats[path] = self.before
|
|
self.read.assert_not_called()
|
|
|
|
def test_descriptor_metadata_change_during_read_is_rejected(self):
|
|
changed = SimpleNamespace(**{**vars(self.before), 'st_ctime_ns': 99})
|
|
self.fstat.side_effect = [self.before, changed]
|
|
with self.assertRaisesRegex(RuntimeError, 'parent_descriptor_changed'):
|
|
fault.checked_parent_descriptor(22)
|
|
self.closed.assert_called_once_with(42)
|
|
|
|
def test_short_read_or_changed_seals_cannot_attest(self):
|
|
self.read.side_effect = [b'short', b'']
|
|
with self.assertRaisesRegex(RuntimeError, 'parent_descriptor_changed'):
|
|
fault.checked_parent_descriptor(22)
|
|
self.read.side_effect = [self.content, b'']
|
|
self.kernel.fcntl.side_effect = [15, 7]
|
|
with self.assertRaisesRegex(RuntimeError, 'parent_memfd_seals'):
|
|
fault.checked_parent_descriptor(22)
|
|
|
|
def test_nonregular_oversized_or_multilink_handles_fail_before_read(self):
|
|
for field, value in [('st_mode', stat.S_IFIFO), ('st_nlink', 2), ('st_size', 256 * 1024 * 1024 + 1)]:
|
|
with self.subTest(field=field):
|
|
before = getattr(self.before, field)
|
|
setattr(self.before, field, value)
|
|
with self.assertRaisesRegex(RuntimeError, 'parent_descriptor_shape'):
|
|
fault.checked_parent_descriptor(22)
|
|
setattr(self.before, field, before)
|
|
self.read.assert_not_called()
|
|
|
|
|
|
class PidfdTests(unittest.TestCase):
|
|
def test_changed_retired_or_reused_pidfd_never_signals(self):
|
|
before = {'target': TARGET}
|
|
for second, fdinfo in [({'target': {**TARGET, 'startTicks': '999'}}, 'Pid:\t23\n'), (before, 'Pid:\t-1\n')]:
|
|
with patch.object(sys, 'platform', 'linux'), patch.object(fault, 'inspect', side_effect=[before, second]), patch.object(os, 'pidfd_open', return_value=42, create=True), patch.object(signal, 'pidfd_send_signal', create=True) as sent, patch.object(os, 'close') as closed, patch.object(Path, 'read_text', return_value=fdinfo):
|
|
with self.assertRaises(RuntimeError):
|
|
fault.terminate({'root': ROOT})
|
|
sent.assert_not_called()
|
|
closed.assert_called_once_with(42)
|
|
|
|
def test_only_held_native_child_pidfd_receives_sigkill(self):
|
|
before = {'target': TARGET}
|
|
with patch.object(sys, 'platform', 'linux'), patch.object(fault, 'inspect', return_value=before), patch.object(os, 'pidfd_open', return_value=42, create=True) as opened, patch.object(signal, 'pidfd_send_signal', create=True) as sent, patch.object(os, 'close') as closed, patch.object(Path, 'read_text', return_value='Pid:\t23\n'):
|
|
receipt = fault.terminate({'root': ROOT, 'binding': {}, 'runtimeEnvironmentLeaseId': 'lease'})
|
|
opened.assert_called_once_with(23)
|
|
sent.assert_called_once_with(42, signal.SIGKILL, None, 0)
|
|
closed.assert_called_once_with(42)
|
|
self.assertFalse(receipt['workerSignalled'])
|
|
|
|
def test_worker_or_current_process_never_opens_a_pidfd(self):
|
|
for pid in [ROOT['pid'], os.getpid()]:
|
|
with patch.object(sys, 'platform', 'linux'), patch.object(fault, 'inspect', return_value={'target': {**TARGET, 'pid': pid}}), patch.object(os, 'pidfd_open', create=True) as opened, patch.object(signal, 'pidfd_send_signal', create=True):
|
|
with self.assertRaisesRegex(RuntimeError, 'not_worker'):
|
|
fault.terminate({'root': ROOT})
|
|
opened.assert_not_called()
|
|
|
|
def test_sealed_files_reject_links_mutability_and_extra_hardlinks(self):
|
|
with tempfile.TemporaryDirectory() as temporary:
|
|
path = Path(temporary).resolve() / 'pinned'
|
|
path.write_bytes(b'pinned')
|
|
with self.assertRaisesRegex(RuntimeError, 'file_writable'):
|
|
fault.checked_file(str(path), 100, True)
|
|
path.chmod(0o400)
|
|
self.assertEqual(fault.checked_file(str(path), 100, True)[0], b'pinned')
|
|
link = path.with_name('link')
|
|
link.symlink_to(path)
|
|
with self.assertRaisesRegex(RuntimeError, 'file_realpath'):
|
|
fault.checked_file(str(link), 100, True)
|
|
os.link(path, path.with_name('hardlink'))
|
|
with self.assertRaisesRegex(RuntimeError, 'file_shape'):
|
|
fault.checked_file(str(path), 100, True)
|
|
|
|
def test_preinstalled_runner_link_is_bound_to_its_resolved_inode(self):
|
|
with tempfile.TemporaryDirectory() as temporary:
|
|
binary = Path(temporary).resolve() / 'installed-runner'
|
|
binary.write_bytes(b'pinned runner')
|
|
link = binary.with_name('runtime-runner')
|
|
link.symlink_to(binary)
|
|
self.assertEqual(fault.checked_runner(str(link)), fault.checked_runner(str(binary)))
|
|
|
|
@unittest.skipUnless(sys.platform == 'linux' and hasattr(os, 'pidfd_open') and hasattr(signal, 'pidfd_send_signal'), 'Native Linux pidfd calibration required')
|
|
def test_real_title_overwritten_native_child_uses_pidfd_and_leaves_worker_alive(self):
|
|
node = shutil.which('node')
|
|
self.assertIsNotNone(node)
|
|
base = Path(tempfile.mkdtemp(prefix='kimi-fault-calibration-', dir='/tmp'))
|
|
snapshot = Path(tempfile.mkdtemp(prefix='paperclip-acpx-native-', dir='/tmp'))
|
|
launch = snapshot / 'launch'
|
|
store = Path(tempfile.mkdtemp(prefix='paperclip-verified-native-', dir='/tmp'))
|
|
staged = store / 'staged' / 'distribution'
|
|
distribution = staged
|
|
workspace = base / 'workspace'
|
|
runtime = workspace / '.paperclip-runtime/paperclip-runner'
|
|
pack = base / 'pack'
|
|
host_node = pack / 'node_modules/node/bin/node'
|
|
root_child = None
|
|
owned = []
|
|
try:
|
|
for path in [distribution / fault.NODE, distribution / fault.ENTRY, runtime / 'bin/paperclip-runnerd', host_node]:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
for path in [distribution / fault.NODE, runtime / 'bin/paperclip-runnerd', host_node]:
|
|
shutil.copyfile(node, path)
|
|
path.chmod(0o500)
|
|
ready = workspace / 'ready.json'
|
|
(distribution / fault.ENTRY).write_text('import fs from "node:fs";process.title="kimi-code";fs.writeFileSync(' + json.dumps(str(ready)) + ',JSON.stringify({pid:process.pid}));setInterval(()=>{},1000);')
|
|
entries = [{'path': name, 'sha256': fault.digest((distribution / name).read_bytes()), 'size': (distribution / name).stat().st_size, 'executable': name == fault.NODE} for name in sorted([fault.NODE, fault.ENTRY])]
|
|
closure = pack / 'provider-assets/kimi/linux-x64/native-closure.json'
|
|
closure.parent.mkdir(parents=True)
|
|
closure.write_text(json.dumps({'entries': entries}))
|
|
closure_sha256 = fault.digest(json.dumps(entries, separators=(',', ':'), ensure_ascii=False).encode())
|
|
# Publish the store under its closure digest, as the runner does.
|
|
(store / 'staged').rename(store / closure_sha256)
|
|
distribution = store / closure_sha256 / 'distribution'
|
|
launch.mkdir()
|
|
loader = 'const source=require("node:fs").readFileSync(3,"utf8");require("node:vm").runInThisContext(source);'
|
|
template = 'const fs=require("node:fs"),cp=require("node:child_process");const fd=fs.openSync(' + json.dumps(fault.PLACEHOLDER + '/' + fault.NODE) + ',"r");const child=cp.spawn("/proc/self/fd/7",["--require",' + json.dumps(fault.LAUNCH_PLACEHOLDER + '/' + fault.GUARD) + ',' + json.dumps(fault.PLACEHOLDER + '/' + fault.ENTRY) + ',"acp"],{stdio:["ignore","ignore","ignore","ignore","ignore","ignore","ignore",fd]});fs.closeSync(fd);child.on("exit",()=>process.exit(0));process.on("SIGTERM",()=>child.kill("SIGTERM"));'
|
|
config = {'binding': {'remoteCwd': str(workspace), 'runId': 'fixture'}, 'runtimeEnvironmentLeaseId': 'workspace-id', 'runnerdSha256': 'sha256:' + fault.digest((runtime / 'bin/paperclip-runnerd').read_bytes()),
|
|
'closureSha256': closure_sha256, 'nodeSha256': 'sha256:' + fault.digest((distribution / fault.NODE).read_bytes()),
|
|
'guardLoaderSha256': 'sha256:' + fault.digest(loader.encode()), 'bootstrapTemplate': template, 'guardTemplate': 'const digests={};'}
|
|
bootstrap, guard = fault.expected_sources(config, str(launch), str(distribution), entries)
|
|
(launch / fault.BOOTSTRAP).write_bytes(bootstrap)
|
|
(launch / fault.GUARD).write_bytes(guard)
|
|
script = base / 'root.cjs'
|
|
script.write_text('const fs=require("node:fs"),cp=require("node:child_process");const directory=fs.openSync(' + json.dumps(str(launch)) + ',"r");const child=cp.spawn(' + json.dumps(str(host_node)) + ',["--eval",' + json.dumps(loader) + ',' + json.dumps(str(launch)) + ',' + json.dumps(fault.BOOTSTRAP) + ',"0","0","commonjs","[]","0"],{detached:true,stdio:["ignore","ignore","ignore","pipe",directory]});fs.closeSync(directory);child.stdio[3].end(fs.readFileSync(' + json.dumps(str(launch / fault.BOOTSTRAP)) + '));process.on("SIGTERM",()=>{if(child.exitCode!==null||child.signalCode!==null)process.exit(0);child.once("exit",()=>process.exit(0));child.kill("SIGTERM")});setInterval(()=>{},1000);')
|
|
for sealed in (snapshot, store / closure_sha256):
|
|
for directory, _, files in os.walk(sealed):
|
|
for name in files:
|
|
path = Path(directory) / name
|
|
path.chmod(0o500 if path == distribution / fault.NODE else 0o400)
|
|
Path(directory).chmod(0o500)
|
|
check_cancelled()
|
|
root_child = subprocess.Popen([str(runtime / 'bin/paperclip-runnerd'), str(script), '--run-id', 'fixture', '--environment-lease-id', 'workspace-id', '--lifecycle-mode', 'per_turn', '--state-dir', str(runtime / 'sessions' / ('a' * 64) / 'runner')], cwd=workspace, env={'PATH': '/usr/bin:/bin'}, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
owned.append(os.pidfd_open(root_child.pid))
|
|
deadline = time.monotonic() + 5
|
|
while not ready.exists() and time.monotonic() < deadline:
|
|
check_cancelled()
|
|
time.sleep(.02)
|
|
self.assertTrue(ready.exists())
|
|
target = json.loads(ready.read_text())['pid']
|
|
self.assertEqual(fault.argv(target), ['kimi-code'])
|
|
boot = Path('/proc/sys/kernel/random/boot_id').read_text().strip()
|
|
config['root'] = fault.proc(root_child.pid, boot)
|
|
with patch.object(fault, 'PACK', str(pack)):
|
|
before = fault.inspect(config)
|
|
for identity in before['ancestry'][:-1]:
|
|
fd = os.pidfd_open(identity['pid'])
|
|
owned.append(fd)
|
|
self.assertEqual(fault.proc(identity['pid'], boot), identity)
|
|
check_cancelled()
|
|
receipt = fault.terminate(config)
|
|
self.assertEqual(receipt['target']['pid'], target)
|
|
self.assertFalse(receipt['workerSignalled'])
|
|
self.assertEqual(select.select([owned[0]], [], [], 0)[0], [])
|
|
self.assertTrue(select.select([owned[1]], [], [], 3)[0])
|
|
finally:
|
|
if root_child is not None:
|
|
if owned:
|
|
try:
|
|
signal.pidfd_send_signal(owned[0], signal.SIGTERM, None, 0)
|
|
except ProcessLookupError:
|
|
pass
|
|
elif root_child.poll() is None:
|
|
root_child.terminate()
|
|
try:
|
|
root_child.wait(timeout=3)
|
|
except subprocess.TimeoutExpired:
|
|
if owned:
|
|
signal.pidfd_send_signal(owned[0], signal.SIGKILL, None, 0)
|
|
root_child.wait(timeout=3)
|
|
for fd in reversed(owned[1:]):
|
|
if not select.select([fd], [], [], 0)[0]:
|
|
try:
|
|
signal.pidfd_send_signal(fd, signal.SIGKILL, None, 0)
|
|
except ProcessLookupError:
|
|
pass
|
|
for fd in owned:
|
|
os.close(fd)
|
|
for sealed in (snapshot, store):
|
|
for directory, _, _ in os.walk(sealed):
|
|
os.chmod(directory, 0o700)
|
|
shutil.rmtree(sealed)
|
|
shutil.rmtree(base)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
def cancelled(_signum, _frame):
|
|
global CANCELLED
|
|
CANCELLED = True
|
|
signal.signal(signal.SIGTERM, cancelled)
|
|
signal.signal(signal.SIGINT, cancelled)
|
|
unittest.main()
|