From 7e53d02e2778afffa5d96dfeb5abcc3001ddcb90 Mon Sep 17 00:00:00 2001 From: Duang777 Date: Thu, 26 Nov 2026 02:53:36 +0000 Subject: [PATCH] fix(quota): reject hard-linked quota artifacts inside the runs directory A quota artifact that is a hard link to an outside zero-slot file still passes the symlink checks from #9420. Require one exclusive regular file before the Python ledger or the TypeScript spend reader treats it as a debit, and reject the same alias when a receipt is replayed. Signed-off-by: Duang777 --- .../quota/accounting_artifact_transaction.ts | 40 +++- loopx/control_plane/quota/ledger_readback.py | 46 +++-- .../test_quota_ledger_relocated_runtime.py | 187 ++++++++++++++++++ .../quota_spend_commit.test.ts | 145 ++++++++++++++ 4 files changed, 391 insertions(+), 27 deletions(-) diff --git a/loopx/control_plane/quota/accounting_artifact_transaction.ts b/loopx/control_plane/quota/accounting_artifact_transaction.ts index 2a7400f0cd..9972bd1c65 100644 --- a/loopx/control_plane/quota/accounting_artifact_transaction.ts +++ b/loopx/control_plane/quota/accounting_artifact_transaction.ts @@ -219,6 +219,12 @@ function isNodeErrorCode(error: unknown, code: string): boolean { return error instanceof Error && "code" in error && error.code === code; } +function isExclusiveRegularFile(stats: { isFile(): boolean; nlink: number }): boolean { + // lstat().isFile() is true for a hard link, and realpath stays on the + // in-directory name. nlink === 1 is the exclusive runs-directory entry. + return stats.isFile() && stats.nlink === 1; +} + async function pathExists(path: string): Promise { try { await access(path); @@ -584,7 +590,7 @@ async function relocatedRunArtifactPath( } const candidate = join(runsDirReal, fileName); try { - if (!(await lstat(candidate)).isFile()) return null; + if (!isExclusiveRegularFile(await lstat(candidate))) return null; const targetPath = await realpath(candidate); if (relative(runsDirReal, targetPath) !== fileName) return null; } catch (error) { @@ -718,13 +724,18 @@ export async function readQuotaSpendEventFromRun( const candidatePath = staysInsideInitial || relocatedCandidate === null ? resolve(rawPath) : relocatedCandidate; + let candidateStat; + try { + candidateStat = await lstat(candidatePath); + } catch (error) { + if (isNodeErrorCode(error, "ENOENT")) return null; + throw error; + } let targetPath: string; try { targetPath = await realpath(candidatePath); } catch (error) { - if (error instanceof Error && "code" in error && error.code === "ENOENT") { - return null; - } + if (isNodeErrorCode(error, "ENOENT")) return null; throw error; } const relativePath = relative(runsDirReal, targetPath); @@ -738,6 +749,7 @@ export async function readQuotaSpendEventFromRun( "quota spend json_path must stay inside the goal runs directory", ); } + if (!isExclusiveRegularFile(candidateStat)) return null; let content: string; try { content = await readFile(targetPath, "utf8"); @@ -958,17 +970,25 @@ function validateReceiptPaths( } async function rejectSymlinkPath(path: string, label: string): Promise { + let stats; try { - if ((await lstat(path)).isSymbolicLink()) { - throw new EffectRuntimeRequestError( - `${label} must not be a symbolic link`, - "malformed_transaction_receipt", - ); - } + stats = await lstat(path); } catch (error) { if (isNodeErrorCode(error, "ENOENT")) return; throw error; } + if (stats.isSymbolicLink()) { + throw new EffectRuntimeRequestError( + `${label} must not be a symbolic link`, + "malformed_transaction_receipt", + ); + } + if (stats.isFile() && !isExclusiveRegularFile(stats)) { + throw new EffectRuntimeRequestError( + `${label} must not be a hard link`, + "malformed_transaction_receipt", + ); + } } async function readReceipt( diff --git a/loopx/control_plane/quota/ledger_readback.py b/loopx/control_plane/quota/ledger_readback.py index 27122cf807..3921d27e0b 100644 --- a/loopx/control_plane/quota/ledger_readback.py +++ b/loopx/control_plane/quota/ledger_readback.py @@ -180,16 +180,28 @@ def _stays_inside_runs_dir(runs_dir: Path, stored_path: str) -> bool: ) +def _exclusive_regular_file(path: Path) -> bool: + """True when ``path`` is one regular file with no other directory entry. + + ``lstat`` does not follow a symlink. A hard link is still a regular file, + and ``resolve`` stays on the in-directory name, so ``st_nlink == 1`` is + the exclusive artifact the quota reader can open. + """ + + info = path.lstat() + return stat.S_ISREG(info.st_mode) and info.st_nlink == 1 + + def _relocated_run_artifact_path( runs_dir: Path, goal_id: str, stored_path: str, extension: str, ) -> Path | None: - """Same-named regular file in the current runs directory, or None. + """Same-named exclusive regular file in the current runs directory, or None. - Symlinks, directories, and files whose real path leaves the runs directory - are not substitutes for the stored artifact. + Symlinks, hard links, directories, and files whose real path leaves the + runs directory are not substitutes for the stored artifact. """ file_name = _copied_goal_run_file_name(stored_path, goal_id, extension) @@ -203,7 +215,7 @@ def _relocated_run_artifact_path( return None candidate = runs_real / file_name try: - if not stat.S_ISREG(candidate.lstat().st_mode): + if not _exclusive_regular_file(candidate): return None target = candidate.resolve(strict=True) except OSError: @@ -220,24 +232,24 @@ def relocated_run_artifact_path( stored_path: str, extension: str, ) -> Path | None: - """Same-named regular ``.json`` or ``.md`` file inside ``runs_dir``. + """Same-named exclusive regular ``.json`` or ``.md`` file inside ``runs_dir``. - Symlinks, directories, and files whose real path leaves the runs directory - are not substitutes. A stored path that is already inside ``runs_dir``, or - that does not name this goal's runs file, returns None so the caller keeps - the stored path. + Symlinks, hard links, directories, and files whose real path leaves the + runs directory are not substitutes. A stored path that is already inside + ``runs_dir``, or that does not name this goal's runs file, returns None so + the caller keeps the stored path. """ return _relocated_run_artifact_path(runs_dir, goal_id, stored_path, extension) def _regular_artifact_inside_runs_dir(runs_dir: Path, stored_path: str) -> str | None: - """Real path of a regular file that stays inside ``runs_dir``. + """Real path of an exclusive regular file that stays inside ``runs_dir``. Lexical containment is not enough. ``Path.read_bytes`` follows a symlink, - so a runs-directory path can still name an outside quota event. Symlinks, - directories, and files whose real path leaves the runs directory are not - the stored artifact. + and a hard link is a regular file whose real path stays inside the runs + directory. Symlinks, hard links, directories, and files whose real path + leaves the runs directory are not the stored artifact. """ try: @@ -248,7 +260,7 @@ def _regular_artifact_inside_runs_dir(runs_dir: Path, stored_path: str) -> str | if expanded is None: return None try: - if not stat.S_ISREG(expanded.lstat().st_mode): + if not _exclusive_regular_file(expanded): return None target = expanded.resolve(strict=True) except OSError: @@ -274,9 +286,9 @@ def _quota_event_artifact_path( """Path to open, or None when a known runs directory must not leave itself. Callers that do not know the current runs directory keep the stored path. - Callers that do open a regular file already inside that directory, or the - same-named regular file copied into it, only when its real path stays - there. Every other absolute location stays unread. + Callers that do open an exclusive regular file already inside that + directory, or the same-named exclusive regular file copied into it, only + when its real path stays there. Every other absolute location stays unread. """ if runs_dir is None: diff --git a/tests/control_plane/test_quota_ledger_relocated_runtime.py b/tests/control_plane/test_quota_ledger_relocated_runtime.py index d09ad146f1..f5e8b5a7ba 100644 --- a/tests/control_plane/test_quota_ledger_relocated_runtime.py +++ b/tests/control_plane/test_quota_ledger_relocated_runtime.py @@ -10,6 +10,7 @@ from __future__ import annotations import json +import os import shutil from datetime import datetime, timedelta, timezone from pathlib import Path @@ -409,6 +410,192 @@ def test_in_directory_symlink_cannot_zero_a_quota_debit(tmp_path: Path) -> None: assert outside.read_bytes() == outside_bytes +def test_in_directory_hard_link_cannot_zero_a_quota_debit(tmp_path: Path) -> None: + """A path already inside the runs directory is still not a hard-link alias. + + The stored path names this goal's runs file, so the lexical containment + check keeps it. Replacing that file with a hard link to an outside + artifact that repeats the commit identity and says the debit was zero + must not read as a readable zero spend. The outside bytes stay untouched. + """ + + now = datetime.now(timezone.utc) + spend_at = now - timedelta(minutes=5) + runtime = tmp_path / "runtime" + runs = runtime / "goals" / GOAL_ID / "runs" + artifact = runs / "spend.json" + commit = _commit( + "quota_spend_commit_receipt_v0", + "effect-spend", + REQUEST_DIGEST, + ) + event = { + "event_type": "quota_slot_spent", + "slots": 2, + "run_generated_at": spend_at.isoformat(), + } + record = { + "generated_at": spend_at.isoformat(), + "goal_id": GOAL_ID, + "classification": "quota_slot_spent", + "quota_event": event, + "quota_spend_commit": commit, + } + _write_record(artifact, record) + row = _row( + artifact, + generated_at=spend_at, + classification="quota_slot_spent", + commit_field="quota_spend_commit", + commit=commit, + ) + goal = _goal() + counted, counted_reason = quota_slot_observation( + row, + runs_dir=runs, + goal_id=GOAL_ID, + ) + assert counted_reason is None + assert counted == ("spent", spend_at.isoformat(), 2) + + outside = tmp_path / "outside-zero.json" + zero_record = { + **record, + "quota_event": {**event, "slots": 0}, + } + outside_bytes = json.dumps(zero_record).encode() + outside.write_bytes(outside_bytes) + artifact.unlink() + os.link(outside, artifact) + + contribution, reason = quota_slot_observation( + row, + runs_dir=runs, + goal_id=GOAL_ID, + ) + assert contribution is None + assert reason == QUOTA_EVENT_UNREADABLE_ARTIFACT_MISSING + ledger = goal_quota_with_spend_ledger(goal, [row], now=now, runs_dir=runs) + assert ledger["spent_slots"] == 0 + assert ledger["unreadable_event_count"] == 1 + assert ledger["unreadable_event_reasons"] == [QUOTA_EVENT_UNREADABLE_ARTIFACT_MISSING] + status = quota_status( + {**goal, "quota": {**goal["quota"], **ledger}}, + waiting_on="codex", + ) + assert status["state"] == "blocked_health" + summary = build_usage_summary( + {"runs": [row]}, + parse_timestamp=_parse_timestamp, + runtime_root=runtime, + ) + assert summary["totals"]["quota_spend_slots_24h"] == 0 + assert summary["totals"]["unreadable_event_count_24h"] == 1 + assert not artifact.is_symlink() + assert artifact.stat().st_ino == outside.stat().st_ino + assert artifact.stat().st_nlink == 2 + assert outside.read_bytes() == outside_bytes + + +def test_relocated_hard_link_cannot_zero_a_quota_debit(tmp_path: Path) -> None: + """A copied runs file that shares an outside inode is not the spend artifact. + + The index still names the old runtime. The same-named file in the new + runs directory is a hard link to an outside zero-slot artifact that + repeats the commit identity. That alias must not read as a zero spend, + and the reader must not fall back to the old tree. + """ + + now = datetime.now(timezone.utc) + spend_at = now - timedelta(minutes=5) + runtime_a = tmp_path / "runtime-a" + runtime_b = tmp_path / "runtime-b" + artifact = runtime_a / "goals" / GOAL_ID / "runs" / "spend.json" + commit = _commit( + "quota_spend_commit_receipt_v0", + "effect-spend", + REQUEST_DIGEST, + ) + event = { + "event_type": "quota_slot_spent", + "slots": 2, + "run_generated_at": spend_at.isoformat(), + } + record = { + "generated_at": spend_at.isoformat(), + "goal_id": GOAL_ID, + "classification": "quota_slot_spent", + "quota_event": event, + "quota_spend_commit": commit, + } + _write_record(artifact, record) + row = _row( + artifact, + generated_at=spend_at, + classification="quota_slot_spent", + commit_field="quota_spend_commit", + commit=commit, + ) + index_path = artifact.parent / "index.jsonl" + index_path.write_text(json.dumps(row) + "\n", encoding="utf-8") + original_bytes = artifact.read_bytes() + runs_b, index_bytes = _copy_runs(runtime_a, runtime_b) + copied_row = json.loads((runs_b / "index.jsonl").read_text(encoding="utf-8")) + counted, counted_reason = quota_slot_observation( + copied_row, + runs_dir=runs_b, + goal_id=GOAL_ID, + ) + assert counted_reason is None + assert counted == ("spent", spend_at.isoformat(), 2) + + outside = tmp_path / "outside-zero.json" + zero_record = { + **record, + "quota_event": {**event, "slots": 0}, + } + outside_bytes = json.dumps(zero_record).encode() + outside.write_bytes(outside_bytes) + copied = runs_b / artifact.name + copied.unlink() + os.link(outside, copied) + + contribution, reason = quota_slot_observation( + copied_row, + runs_dir=runs_b, + goal_id=GOAL_ID, + ) + assert contribution is None + assert reason == QUOTA_EVENT_UNREADABLE_ARTIFACT_MISSING + ledger = goal_quota_with_spend_ledger( + _goal(), + [copied_row], + now=now, + runs_dir=runs_b, + ) + assert ledger["spent_slots"] == 0 + assert ledger["unreadable_event_count"] == 1 + assert ledger["unreadable_event_reasons"] == [QUOTA_EVENT_UNREADABLE_ARTIFACT_MISSING] + status = quota_status( + {**_goal(), "quota": {**_goal()["quota"], **ledger}}, + waiting_on="codex", + ) + assert status["state"] == "blocked_health" + summary = build_usage_summary( + {"runs": [copied_row]}, + parse_timestamp=_parse_timestamp, + runtime_root=runtime_b, + ) + assert summary["totals"]["quota_spend_slots_24h"] == 0 + assert summary["totals"]["unreadable_event_count_24h"] == 1 + assert not copied.is_symlink() + assert copied.stat().st_ino == outside.stat().st_ino + assert copied.stat().st_nlink == 2 + assert outside.read_bytes() == outside_bytes + assert artifact.read_bytes() == original_bytes + assert (runs_b / "index.jsonl").read_bytes() == index_bytes + + def test_copied_commit_digest_must_match_before_the_slots_count(tmp_path: Path) -> None: now = datetime.now(timezone.utc) spend_at = now - timedelta(minutes=15) diff --git a/tests/control_plane_ts/quota_spend_commit.test.ts b/tests/control_plane_ts/quota_spend_commit.test.ts index 625cbaf3ad..1d7f3dbd18 100644 --- a/tests/control_plane_ts/quota_spend_commit.test.ts +++ b/tests/control_plane_ts/quota_spend_commit.test.ts @@ -2,6 +2,8 @@ import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { cp, + link, + lstat, readFile, mkdir, mkdtemp, @@ -1418,3 +1420,146 @@ test("copied spend receipts still reject other goals, outside paths, symlinks, a ); assert.deepEqual(await readFile(originalJson), originalJsonBytes); }); + +const spendCommit = { + schema_version: "quota_spend_commit_receipt_v0", + effect_id: "effect-spend", + request_digest: "digest-spend-original", +}; + +function quotaSpendRecord(slots: number): Record { + return { + generated_at: "2026-08-25T12:00:00Z", + goal_id: goalId, + classification: "quota_slot_spent", + quota_event: { + event_type: "quota_slot_spent", + slots, + run_generated_at: "2026-08-25T12:00:00Z", + }, + quota_spend_commit: spendCommit, + }; +} + +function quotaSpendIndexRow(jsonPath: string): Record { + return { + generated_at: "2026-08-25T12:00:00Z", + goal_id: goalId, + classification: "quota_slot_spent", + json_path: jsonPath, + quota_spend_commit: spendCommit, + }; +} + +async function assertSharedHardLink(artifact: string, outside: string): Promise { + const linked = await lstat(artifact); + const target = await lstat(outside); + assert.equal(linked.isSymbolicLink(), false); + assert.equal(linked.isFile(), true); + assert.equal(linked.nlink, 2); + assert.equal(linked.ino, target.ino); +} + +test("readQuotaSpendEventFromRun does not accept an in-directory hard link as a zero spend", async (t) => { + const runtimeRoot = await tempRuntime(t); + const runsDir = join(runtimeRoot, "goals", goalId, "runs"); + await mkdir(runsDir, { recursive: true }); + const artifact = join(runsDir, "spend.json"); + const record = quotaSpendRecord(2); + await writeFile(artifact, JSON.stringify(record), "utf8"); + const row = quotaSpendIndexRow(artifact); + + const counted = await readQuotaSpendEventFromRun(runsDir, row, goalId); + assert.equal(counted?.slots, 2); + + const outside = join(runtimeRoot, "outside-zero.json"); + const outsideBytes = Buffer.from(JSON.stringify(quotaSpendRecord(0))); + await writeFile(outside, outsideBytes); + await unlink(artifact); + await link(outside, artifact); + + assert.equal(await readQuotaSpendEventFromRun(runsDir, row, goalId), null); + assert.deepEqual(await readFile(outside), outsideBytes); + await assertSharedHardLink(artifact, outside); +}); + +test("readQuotaSpendEventFromRun does not accept a relocated hard link as a zero spend", async (t) => { + const originalRoot = await tempRuntime(t); + const relocatedRoot = await tempRuntime(t); + const fileName = "spend.json"; + const originalRunsDir = join(originalRoot, "goals", goalId, "runs"); + const relocatedRunsDir = join(relocatedRoot, "goals", goalId, "runs"); + await mkdir(originalRunsDir, { recursive: true }); + await mkdir(relocatedRunsDir, { recursive: true }); + const originalJson = join(originalRunsDir, fileName); + const originalBytes = Buffer.from(JSON.stringify(quotaSpendRecord(2))); + await writeFile(originalJson, originalBytes); + const outside = join(relocatedRoot, "outside-zero.json"); + const outsideBytes = Buffer.from(JSON.stringify(quotaSpendRecord(0))); + await writeFile(outside, outsideBytes); + const relocatedJson = join(relocatedRunsDir, fileName); + await link(outside, relocatedJson); + + assert.equal( + await readQuotaSpendEventFromRun(relocatedRunsDir, quotaSpendIndexRow(originalJson), goalId), + null, + ); + assert.deepEqual(await readFile(outside), outsideBytes); + assert.deepEqual(await readFile(originalJson), originalBytes); + await assertSharedHardLink(relocatedJson, outside); +}); + +test("spend receipt replay rejects an in-directory hard link to an outside alias", async (t) => { + const runtimeRoot = await tempRuntime(t); + const params = request(runtimeRoot, { effect_id: "quota-spend-effect-hardlink" }); + const written = await evaluateQuotaSpendCommit(params); + assert.equal(written.status, "written"); + const artifact = String(written.payload.json_path); + const artifactBytes = await readFile(artifact); + const outside = join(runtimeRoot, "outside-quota-spend.json"); + await writeFile(outside, artifactBytes); + await unlink(artifact); + await link(outside, artifact); + + await assert.rejects( + () => evaluateQuotaSpendCommit(params), + (error: unknown) => { + assert.ok(error instanceof EffectRuntimeRequestError); + assert.equal(error.code, "malformed_transaction_receipt"); + assert.match(error.message, /must not be a hard link/); + return true; + }, + ); + assert.deepEqual(await readFile(outside), artifactBytes); + await assertSharedHardLink(artifact, outside); +}); + +test("spend receipt replay does not adopt a relocated hard link to an outside alias", async (t) => { + const originalRoot = await tempRuntime(t); + const copiedRoot = await tempRuntime(t); + const params = request(originalRoot, { effect_id: "quota-spend-effect-relocated-hardlink" }); + const written = await evaluateQuotaSpendCommit(params); + assert.equal(written.status, "written"); + const originalJson = String(written.payload.json_path); + const originalBytes = await readFile(originalJson); + const copiedRuns = spendRunsDir(copiedRoot); + await cp(spendRunsDir(originalRoot), copiedRuns, { recursive: true }); + const copiedJson = join(copiedRuns, basename(originalJson)); + const outside = join(copiedRoot, "outside-quota-spend.json"); + await writeFile(outside, originalBytes); + await unlink(copiedJson); + await link(outside, copiedJson); + + await assert.rejects( + () => evaluateQuotaSpendCommit(request(copiedRoot, { effect_id: params.effect_id })), + (error: unknown) => { + assert.ok(error instanceof EffectRuntimeRequestError); + assert.equal(error.code, "malformed_transaction_receipt"); + assert.match(error.message, /outside its run directory/); + return true; + }, + ); + assert.deepEqual(await readFile(outside), originalBytes); + assert.deepEqual(await readFile(originalJson), originalBytes); + await assertSharedHardLink(copiedJson, outside); +});