diff --git a/loopx/control_plane/effect_runtime_snapshot.ts b/loopx/control_plane/effect_runtime_snapshot.ts index e5f662bf00..3141791a60 100644 --- a/loopx/control_plane/effect_runtime_snapshot.ts +++ b/loopx/control_plane/effect_runtime_snapshot.ts @@ -24,6 +24,8 @@ async function privateFile(path: string, flags: number): Promise { } const entry = await lstat(path); if (entry.isSymbolicLink()) throw new Error("private snapshot is a symlink"); + // isFile() is true for a hard link. nlink === 1 is this inode's only name. + if (!entry.isFile() || entry.nlink !== 1) throw new Error("invalid private snapshot file"); if (process.platform === "win32") { const python = process.env.LOOPX_EFFECT_RUNTIME_PYTHON_BIN; if (!python || !isAbsolute(python)) throw new Error("private snapshot ACL helper unavailable"); @@ -38,8 +40,8 @@ async function privateFile(path: string, flags: number): Promise { const file = await open(path, flags | (constants.O_NOFOLLOW ?? 0)); try { const stat = await file.stat(); - if (!stat.isFile() || stat.dev !== entry.dev || stat.ino !== entry.ino || (process.getuid && - (stat.uid !== process.getuid() || (stat.mode & 0o077) !== 0))) { + if (!stat.isFile() || stat.nlink !== 1 || stat.dev !== entry.dev || stat.ino !== entry.ino || + (process.getuid && (stat.uid !== process.getuid() || (stat.mode & 0o077) !== 0))) { throw new Error("invalid private snapshot file"); } return file; diff --git a/loopx/control_plane/runtime/private_permissions.py b/loopx/control_plane/runtime/private_permissions.py index e7b4f57c1d..67de78786a 100644 --- a/loopx/control_plane/runtime/private_permissions.py +++ b/loopx/control_plane/runtime/private_permissions.py @@ -86,14 +86,19 @@ def _protect_windows_path(path: Path, *, directory: bool) -> None: def require_private_path(path: Path, *, directory: bool = False, descriptor: int | None = None) -> None: """Read OS access facts without repairing an untrusted caller's file.""" info = path.lstat() + # A hard link is a regular file. Directories keep their ordinary link + # count; a leaf is private only when this entry is its only name. if (stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & 0x400 - or (not stat.S_ISDIR(info.st_mode) if directory else not stat.S_ISREG(info.st_mode))): + or (not stat.S_ISDIR(info.st_mode) if directory else not stat.S_ISREG(info.st_mode)) + or (not directory and info.st_nlink != 1)): raise OSError("private IO path is not a regular owned leaf") if descriptor is not None: opened = os.fstat(descriptor) if (opened.st_dev, opened.st_ino) != (info.st_dev, info.st_ino): raise OSError("private IO path changed after open") + if not directory and (not stat.S_ISREG(opened.st_mode) or opened.st_nlink != 1): + raise OSError("private IO path is not a regular owned leaf") info = opened if sys.platform != "win32": if info.st_uid != os.getuid() or info.st_mode & 0o077: diff --git a/tests/control_plane/test_private_snapshot_exclusive_file.py b/tests/control_plane/test_private_snapshot_exclusive_file.py new file mode 100644 index 0000000000..558d1ba087 --- /dev/null +++ b/tests/control_plane/test_private_snapshot_exclusive_file.py @@ -0,0 +1,127 @@ +"""Private snapshot leaves must be exclusive regular files. + +A hard link is still a regular file, so rejecting a symlink does not stop a +second name outside the private directory from sharing the inode. +""" + +from __future__ import annotations + +import errno +import hashlib +import os +import stat +import tempfile +from pathlib import Path + +import pytest + +from loopx.control_plane import effect_runtime +from loopx.control_plane.runtime.private_permissions import ( + protect_private_path, + require_private_path, +) + +_HARDLINK_UNSUPPORTED = { + errno.EPERM, + errno.EOPNOTSUPP, + errno.ENOTSUP, + errno.EXDEV, + errno.ENOSYS, +} + + +def _private_directory(tmp_path: Path) -> Path: + directory = Path(tempfile.mkdtemp(prefix="loopx-effect-", dir=tmp_path)) + directory.chmod(0o700) + protect_private_path(directory, directory=True) + return directory + + +def _exclusive_leaf(tmp_path: Path, name: str = "response.json") -> tuple[Path, Path, bytes]: + directory = _private_directory(tmp_path) + leaf = directory / name + payload = b'{"sentinel":"keep"}' + leaf.write_bytes(payload) + protect_private_path(leaf) + return directory, leaf, payload + + +def _hard_linked_leaf(tmp_path: Path) -> tuple[Path, Path, bytes]: + sentinel = tmp_path / "sentinel.json" + original = b'{"sentinel":"keep"}' + sentinel.write_bytes(original) + directory = _private_directory(tmp_path) + link = directory / "response.json" + try: + os.link(sentinel, link) + except OSError as exc: + if exc.errno in _HARDLINK_UNSUPPORTED: + pytest.skip("this host cannot create a hard link") + raise + protect_private_path(link) + info = link.lstat() + external = sentinel.lstat() + assert not stat.S_ISLNK(info.st_mode) + assert stat.S_ISREG(info.st_mode) + assert info.st_ino == external.st_ino and info.st_dev == external.st_dev + assert info.st_nlink == 2 + assert sentinel.read_bytes() == original + return sentinel, link, original + + +def test_exclusive_private_leaf_is_admitted(tmp_path: Path) -> None: + _directory, leaf, payload = _exclusive_leaf(tmp_path) + require_private_path(leaf) + descriptor = os.open(leaf, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) + try: + require_private_path(leaf, descriptor=descriptor) + finally: + os.close(descriptor) + assert leaf.read_bytes() == payload + assert leaf.stat().st_nlink == 1 + + +def test_private_directory_keeps_its_ordinary_link_count(tmp_path: Path) -> None: + directory = _private_directory(tmp_path) + (directory / "nested").mkdir() + info = directory.lstat() + assert stat.S_ISDIR(info.st_mode) + if os.name == "posix": + assert info.st_nlink > 1 + require_private_path(directory, directory=True) + + +def test_require_private_path_rejects_a_hard_linked_leaf(tmp_path: Path) -> None: + sentinel, link, original = _hard_linked_leaf(tmp_path) + with pytest.raises(OSError, match="private IO path is not a regular owned leaf"): + require_private_path(link) + descriptor = os.open(link, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) + try: + with pytest.raises(OSError, match="private IO path is not a regular owned leaf"): + require_private_path(link, descriptor=descriptor) + finally: + os.close(descriptor) + assert sentinel.read_bytes() == original + + +def test_snapshot_read_rejects_a_hard_linked_leaf_without_changing_it(tmp_path: Path) -> None: + sentinel, link, original = _hard_linked_leaf(tmp_path) + envelope = { + "schema_version": effect_runtime.EFFECT_RUNTIME_RESPONSE_SCHEMA_VERSION, + "request_id": "owned-request", + "ok": True, + "result_ref": { + "byte_count": len(original), + "sha256": hashlib.sha256(original).hexdigest(), + }, + } + with pytest.raises(effect_runtime.EffectRuntimeResponseAmbiguous): + effect_runtime._read_local_snapshot_response( + envelope, + link, + method="goal.checkpoint_read_context.commit", + request_id="owned-request", + timeout=10, + ) + assert sentinel.read_bytes() == original + assert link.stat().st_nlink == 2 diff --git a/tests/control_plane_ts/effect_runtime_snapshot.test.ts b/tests/control_plane_ts/effect_runtime_snapshot.test.ts index 50583f3b95..0480b1ad36 100644 --- a/tests/control_plane_ts/effect_runtime_snapshot.test.ts +++ b/tests/control_plane_ts/effect_runtime_snapshot.test.ts @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import {execFile} from "node:child_process"; import {createHash} from "node:crypto"; -import {mkdir, mkdtemp, writeFile, chmod, symlink, rm} from "node:fs/promises"; +import {mkdir, mkdtemp, writeFile, chmod, symlink, rm, link, readFile, lstat} from "node:fs/promises"; import {join} from "node:path"; import {test} from "node:test"; import {promisify} from "node:util"; @@ -37,6 +37,49 @@ async function removeFixture(directory: string) { await rm(directory, {recursive: true, force: true, maxRetries: 10, retryDelay: 100}); } +function hardLinkUnsupported(error: unknown): boolean { + const code = typeof error === "object" && error && "code" in error ? String(error.code) : ""; + return ["EPERM", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "ENOSYS"].includes(code); +} + +/** Same-uid hard link of an outside sentinel into a private effect directory. */ +async function hardLinkedPrivateLeaf(name: string): Promise<{ + directory: string; outside: string; path: string; sentinel: string; bytes: Buffer; +} | null> { + const directory = await createFixtureDirectory(); + const outside = await mkdtemp(join(process.cwd(), ".local", "loopx-sentinel-")); + try { + const sentinel = join(outside, "sentinel.json"); + const bytes = Buffer.from(JSON.stringify({sentinel: "keep", leaf: name})); + await writeFile(sentinel, bytes, {mode: 0o600}); + await chmod(sentinel, 0o600); + await chmod(directory, 0o700); + const path = join(directory, name); + try { + await link(sentinel, path); + } catch (error) { + if (!hardLinkUnsupported(error)) throw error; + await removeFixture(directory); + await removeFixture(outside); + return null; + } + await protectWindowsFixture(directory, path); + const entry = await lstat(path); + const external = await lstat(sentinel); + assert.equal(entry.isSymbolicLink(), false); + assert.equal(entry.isFile(), true); + assert.equal(entry.dev, external.dev); + assert.equal(entry.ino, external.ino); + assert.equal(entry.nlink, 2); + assert.deepEqual(await readFile(sentinel), bytes); + return {directory, outside, path, sentinel, bytes}; + } catch (error) { + await removeFixture(directory); + await removeFixture(outside); + throw error; + } +} + test("local snapshot accepts exact private bytes and rejects altered or unsafe references", async () => { const directory = await createFixtureDirectory(); try { @@ -91,3 +134,59 @@ test("large response sink is private and digest-bound", async () => { await removeFixture(directory); } }); + +test("hard-linked private snapshot is rejected and the external file stays unchanged", async (t) => { + const fixture = await hardLinkedPrivateLeaf("params.json"); + if (fixture === null) { + t.skip("this host cannot create a hard link"); + return; + } + const {directory, outside, path, sentinel, bytes} = fixture; + try { + const ref = {path, byte_count: bytes.length, + sha256: createHash("sha256").update(bytes).digest("hex")}; + let value: unknown; + let error: unknown; + try { + value = await readPrivateJsonSnapshot(ref); + } catch (caught) { + error = caught; + } + assert.deepEqual(await readFile(sentinel), bytes); + assert.equal(value, undefined); + assert.match(error instanceof Error ? error.message : "", + /private snapshot unavailable or invalid/); + } finally { + await removeFixture(directory); + await removeFixture(outside); + } +}); + +test("hard-linked response sink is rejected without clobbering the external file", async (t) => { + const fixture = await hardLinkedPrivateLeaf("response.json"); + if (fixture === null) { + t.skip("this host cannot create a hard link"); + return; + } + const {directory, outside, path, sentinel, bytes} = fixture; + try { + const payload = Buffer.from(JSON.stringify({clobber: true})); + let error: unknown; + try { + const file = await openPrivateResponseSink(path); + try { + await writePrivateResponse(file, payload); + } finally { + await file.close(); + } + } catch (caught) { + error = caught; + } + assert.deepEqual(await readFile(sentinel), bytes); + assert.match(error instanceof Error ? error.message : "", + /private response sink unavailable or invalid/); + } finally { + await removeFixture(directory); + await removeFixture(outside); + } +});