mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 18:07:00 +01:00
Merge qualified provider-pack layout prerequisite
Co-Authored-By: Paperclip <noreply@paperclip.ing> * commit 'b64d6309693e7c10ee783dbd3313ae3a007cf5c1': Materialize independent files in new provider packs Report bounded metadata for module link-count rejections # Conflicts: # server/src/services/native-runtime/native-session-executor.ts
This commit is contained in:
commit
f647f2101c
15 files changed
+427
-10
No files matched your search
@@ -168,6 +168,15 @@ are unavailable. Accepting a native plan ends the planning run successfully whil
|
||||
the task waits for the next instruction. See the
|
||||
[Cursor release report](../../doc/plans/2026-10-03-cursor-production-readiness.md).
|
||||
|
||||
New provider packs declare `payload.fileLayout: "independent-regular-files-v1"`.
|
||||
The builder separates hardlinked regular files in its unpublished temporary tree,
|
||||
preserving file bytes, modes, and symlinks. The policy participates in the manifest
|
||||
digest, so a new layout cannot reuse a legacy cache identity. Controller and guest
|
||||
verification reject unknown policies and hardlinked files under this policy.
|
||||
Existing manifests without the field retain their original immutable contract;
|
||||
they are not rewritten or repaired during session reuse. Runtime module and
|
||||
executable integrity guards remain unchanged.
|
||||
|
||||
A release includes all three platform daemons and the Linux provider-pack identity
|
||||
from its matching Daytona image. Run `stage:release-binaries` with a manifest that
|
||||
binds each daemon path and SHA-256, plus `remoteProviderPack: {path, sha256}` for
|
||||
|
||||
@@ -458,11 +458,12 @@ impl AcpxSidecarTransport {
|
||||
let error = response.error.expect("failed response has validated error");
|
||||
return Ok(CommandOutcome::Rejected(LocalRunnerError::invalid(
|
||||
format!(
|
||||
"ACPX sidecar command {} was rejected (retryable={}, classification={}){}{}",
|
||||
"ACPX sidecar command {} was rejected (retryable={}, classification={}){}{}{}",
|
||||
command.as_str(),
|
||||
error.retryable,
|
||||
response_error_classification(&error),
|
||||
response_error_module_fence(&error).map(|fence| format!(" moduleFence={fence}")).unwrap_or_default(),
|
||||
response_error_module_read(&error).unwrap_or_default(),
|
||||
self.diagnostic_suffix(),
|
||||
),
|
||||
)));
|
||||
@@ -926,6 +927,9 @@ fn stderr_diagnostic_categories(value: &str) -> BTreeSet<&'static str> {
|
||||
|
||||
// Only fixed loader fence codes may cross the private provider-stderr boundary.
|
||||
fn response_error_module_fence(error: &ResponseError) -> Option<&'static str> {
|
||||
if response_error_module_read(error).is_some() {
|
||||
return Some("link_count");
|
||||
}
|
||||
match error.code.as_str() {
|
||||
"AGENT_STARTUP_FAILED.UNVERIFIED_MODULE.RESOLUTION" => Some("resolution"),
|
||||
"AGENT_STARTUP_FAILED.UNVERIFIED_MODULE.OPEN" => Some("open"),
|
||||
@@ -948,6 +952,59 @@ fn response_error_module_fence(error: &ResponseError) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
// Independently validate the compact failure-only metadata from the sidecar.
|
||||
fn response_error_module_read(error: &ResponseError) -> Option<String> {
|
||||
let suffix = error
|
||||
.code
|
||||
.strip_prefix("AGENT_STARTUP_FAILED.UNVERIFIED_MODULE.LINK_COUNT.READ.")?;
|
||||
let fields: Vec<&str> = suffix.split('.').collect();
|
||||
if fields.len() != 5 || !matches!(fields[0], "1" | "2") {
|
||||
return None;
|
||||
}
|
||||
let number = |text: &str| -> Option<u64> {
|
||||
if text.is_empty()
|
||||
|| text.len() > 20
|
||||
|| !text.bytes().all(|b| b.is_ascii_digit())
|
||||
|| (text.len() > 1 && text.starts_with('0'))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
text.parse().ok()
|
||||
};
|
||||
let before = number(fields[1])?;
|
||||
let after = number(fields[2])?;
|
||||
if before == after || fields[3] != if after > before { "I" } else { "D" } {
|
||||
return None;
|
||||
}
|
||||
let flags = fields[4];
|
||||
if flags.len() != 8
|
||||
|| !flags.starts_with("111111")
|
||||
|| !flags.bytes().all(|b| matches!(b, b'0' | b'1'))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut diagnostic = format!(
|
||||
" moduleReadAttempt={} moduleNlinkBefore={} moduleNlinkAfter={} moduleNlinkDirection={}",
|
||||
fields[0],
|
||||
before,
|
||||
after,
|
||||
if after > before {
|
||||
"increase"
|
||||
} else {
|
||||
"decrease"
|
||||
}
|
||||
);
|
||||
for (field, equal) in [
|
||||
"Dev", "Inode", "Mode", "Uid", "Gid", "Size", "Mtime", "Ctime",
|
||||
]
|
||||
.into_iter()
|
||||
.zip(flags.bytes())
|
||||
{
|
||||
diagnostic.push_str(&format!(" module{field}Equal={}", equal == b'1'));
|
||||
}
|
||||
Some(diagnostic)
|
||||
}
|
||||
|
||||
fn response_error_classification(error: &ResponseError) -> &'static str {
|
||||
if response_error_module_fence(error).is_some() {
|
||||
return "agent_startup_unverified_module";
|
||||
@@ -1207,7 +1264,7 @@ mod tests {
|
||||
})
|
||||
.collect();
|
||||
let response = json!({ "protocolVersion": GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION,
|
||||
"id": 1, "ok": false, "error": { "code": "AGENT_STARTUP_FAILED.UNVERIFIED_MODULE.REPEATED_CTIME",
|
||||
"id": 1, "ok": false, "error": { "code": "AGENT_STARTUP_FAILED.UNVERIFIED_MODULE.LINK_COUNT.READ.1.2.1.D.11111110",
|
||||
"message": "/private/token-canary", "retryable": false } });
|
||||
let lines = frames
|
||||
.iter()
|
||||
@@ -1236,7 +1293,12 @@ mod tests {
|
||||
),
|
||||
"{error}"
|
||||
);
|
||||
assert!(error.contains("moduleFence=repeated_ctime"), "{error}");
|
||||
assert!(error.contains("moduleFence=link_count"), "{error}");
|
||||
assert!(error.contains("moduleReadAttempt=1 moduleNlinkBefore=2 moduleNlinkAfter=1 moduleNlinkDirection=decrease"), "{error}");
|
||||
assert!(
|
||||
error.contains("moduleMtimeEqual=true moduleCtimeEqual=false"),
|
||||
"{error}"
|
||||
);
|
||||
assert!(
|
||||
error.contains("admissionStage=handshake admissionElapsedMs=24"),
|
||||
"{error}"
|
||||
@@ -1434,6 +1496,48 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn link_count_failure_details_are_bounded_and_keep_the_fence() {
|
||||
for (suffix, valid) in [
|
||||
("1.1.2.I.11111110", true),
|
||||
("2.2.1.D.11111101", true),
|
||||
("1.0.18446744073709551615.I.11111111", true),
|
||||
("0.1.2.I.11111110", false),
|
||||
("3.1.2.I.11111110", false),
|
||||
("1.-1.2.I.11111110", false),
|
||||
("1.01.2.I.11111110", false),
|
||||
("1.1.18446744073709551616.I.11111110", false),
|
||||
("1.1.2.D.11111110", false),
|
||||
("1.1.1.I.11111110", false),
|
||||
("1.1.2.I.01111110", false),
|
||||
("1.1.2.I.111111100", false),
|
||||
("1.1.2.I.11111110.PRIVATE_CANARY", false),
|
||||
] {
|
||||
let error = ResponseError {
|
||||
code: format!("AGENT_STARTUP_FAILED.UNVERIFIED_MODULE.LINK_COUNT.READ.{suffix}"),
|
||||
message: "/private/token-canary".to_owned(),
|
||||
retryable: false,
|
||||
};
|
||||
let detail = response_error_module_read(&error);
|
||||
assert_eq!(detail.is_some(), valid, "{suffix}");
|
||||
assert_eq!(
|
||||
response_error_module_fence(&error),
|
||||
if valid { Some("link_count") } else { None }
|
||||
);
|
||||
assert_eq!(
|
||||
response_error_classification(&error),
|
||||
if valid {
|
||||
"agent_startup_unverified_module"
|
||||
} else {
|
||||
"unclassified"
|
||||
}
|
||||
);
|
||||
if let Some(detail) = detail {
|
||||
assert!(!detail.contains("private") && !detail.contains("CANARY"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn candidate_auth_diagnostics_use_only_closed_codes_and_never_provider_text() {
|
||||
for (code, expected) in [
|
||||
|
||||
@@ -20,6 +20,7 @@ import { dirname, join, relative, resolve } from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { parseProviderPackArguments, materializeCandidateProviderPack, providerPackProviders, providerPackManifestFields } from "./candidate-provider-pack.mjs";
|
||||
import { materializeIndependentProviderPackFiles, PROVIDER_PACK_FILE_LAYOUT } from "./provider-pack-file-layout.mjs";
|
||||
import { buildNodeStartupTimeout } from "./build-node-startup-timeout.mjs";
|
||||
import { writePortableExecutableShim, writePortableCopilotShims } from "./provider-pack-executable-shims.mjs";
|
||||
|
||||
@@ -277,6 +278,8 @@ try {
|
||||
}
|
||||
}
|
||||
|
||||
materializeIndependentProviderPackFiles(temporaryRoot);
|
||||
|
||||
const opencodeProxySha = sha256File(join(temporaryRoot, opencodeProxyPath));
|
||||
const acpxSidecarSha = sha256File(join(temporaryRoot, acpxSidecarPath));
|
||||
const distDigest = sha256Tree(join(temporaryRoot, "dist"));
|
||||
@@ -297,6 +300,7 @@ try {
|
||||
cwd: workspaceRoot,
|
||||
}).status !== 0;
|
||||
const payload = {
|
||||
fileLayout: PROVIDER_PACK_FILE_LAYOUT,
|
||||
pins: {
|
||||
nodeMinimum: minimumNodeVersion.join("."),
|
||||
codex: profiles.profiles.codex.agentRuntimeVersion,
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { chmodSync, constants, copyFileSync, lstatSync, mkdtempSync, readdirSync, renameSync, rmSync, utimesSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const PROVIDER_PACK_FILE_LAYOUT = "independent-regular-files-v1";
|
||||
|
||||
/** Only call on the unpublished build tree, never on a retained provider cache. */
|
||||
export function materializeIndependentProviderPackFiles(root) {
|
||||
const visit = directory => {
|
||||
for (const name of readdirSync(directory)) {
|
||||
const file = join(directory, name);
|
||||
const stat = lstatSync(file);
|
||||
if (stat.isDirectory()) visit(file);
|
||||
else if (stat.isSymbolicLink()) continue;
|
||||
else if (!stat.isFile()) throw new Error("Unsupported provider pack file layout entry");
|
||||
else if (stat.nlink > 1) {
|
||||
// Copy to a new inode before changing metadata: the source may also be
|
||||
// linked into pnpm's store outside this unpublished tree.
|
||||
const temporary = mkdtempSync(join(directory, ".paperclip-independent-"));
|
||||
try {
|
||||
const replacement = join(temporary, "file");
|
||||
copyFileSync(file, replacement, constants.COPYFILE_EXCL);
|
||||
chmodSync(replacement, stat.mode & 0o7777);
|
||||
utimesSync(replacement, stat.atimeMs / 1000, stat.mtimeMs / 1000);
|
||||
renameSync(replacement, file);
|
||||
} finally {
|
||||
rmSync(temporary, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if (!lstatSync(root).isDirectory()) throw new Error("Invalid provider pack build root");
|
||||
visit(root);
|
||||
const verify = directory => {
|
||||
for (const name of readdirSync(directory)) {
|
||||
const file = join(directory, name);
|
||||
const stat = lstatSync(file);
|
||||
if (stat.isDirectory()) verify(file);
|
||||
else if (stat.isFile() && stat.nlink !== 1) throw new Error("Provider pack files are not independent");
|
||||
else if (!stat.isFile() && !stat.isSymbolicLink()) throw new Error("Unsupported provider pack file layout entry");
|
||||
}
|
||||
};
|
||||
verify(root);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { chmodSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import test from "node:test";
|
||||
import { materializeIndependentProviderPackFiles } from "./provider-pack-file-layout.mjs";
|
||||
|
||||
test("new pack files remain independent after a real tar round trip without changing source bytes, modes or symlinks", () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "provider-pack-layout-"));
|
||||
try {
|
||||
const pack = join(root, "pack"); mkdirSync(pack);
|
||||
const outside = join(root, "store"); mkdirSync(outside);
|
||||
const source = join(outside, "source"); writeFileSync(source, "identical module bytes\n"); chmodSync(source, 0o755);
|
||||
linkSync(source, join(pack, "a")); linkSync(source, join(pack, "b"));
|
||||
writeFileSync(join(pack, "c"), "identical module bytes\n");
|
||||
symlinkSync("a", join(pack, "relative-link"));
|
||||
symlinkSync(outside, join(pack, "external-directory-link"));
|
||||
writeFileSync(join(outside, "untouched-a"), "outside");
|
||||
linkSync(join(outside, "untouched-a"), join(outside, "untouched-b"));
|
||||
const outsideInode = lstatSync(join(outside, "untouched-a")).ino;
|
||||
const original = lstatSync(source);
|
||||
// Prove plain tar preserves the old hardlink topology.
|
||||
execFileSync("tar", ["-czf", join(root, "legacy.tgz"), "-C", pack, "."]);
|
||||
const legacy = join(root, "legacy"); mkdirSync(legacy);
|
||||
execFileSync("tar", ["-xzf", join(root, "legacy.tgz"), "-C", legacy]);
|
||||
assert.equal(lstatSync(join(legacy, "a")).ino, lstatSync(join(legacy, "b")).ino);
|
||||
assert.equal(lstatSync(join(legacy, "a")).nlink, 2);
|
||||
materializeIndependentProviderPackFiles(pack);
|
||||
const once = ["a", "b", "c"].map(name => lstatSync(join(pack, name)).ino);
|
||||
materializeIndependentProviderPackFiles(pack);
|
||||
assert.deepEqual(["a", "b", "c"].map(name => lstatSync(join(pack, name)).ino), once);
|
||||
execFileSync("tar", ["-czf", join(root, "independent.tgz"), "-C", pack, "."]);
|
||||
const unpacked = join(root, "unpacked"); mkdirSync(unpacked);
|
||||
execFileSync("tar", ["-xzf", join(root, "independent.tgz"), "-C", unpacked]);
|
||||
const stats = ["a", "b", "c"].map(name => lstatSync(join(unpacked, name)));
|
||||
assert.equal(new Set(stats.map(stat => stat.ino)).size, 3);
|
||||
assert.ok(stats.every(stat => stat.nlink === 1));
|
||||
for (const name of ["a", "b", "c"]) assert.equal(readFileSync(join(unpacked, name), "utf8"), "identical module bytes\n");
|
||||
assert.equal(stats[0].mode & 0o7777, 0o755);
|
||||
assert.equal(stats[1].mode & 0o7777, 0o755);
|
||||
assert.equal(readlinkSync(join(unpacked, "relative-link")), "a");
|
||||
assert.equal(readlinkSync(join(unpacked, "external-directory-link")), outside);
|
||||
const after = lstatSync(source);
|
||||
assert.equal(after.ino, original.ino); assert.equal(after.mode, original.mode);
|
||||
assert.equal(after.mtimeMs, original.mtimeMs); assert.equal(after.nlink, 1);
|
||||
assert.equal(readFileSync(source, "utf8"), "identical module bytes\n");
|
||||
for (const name of ["untouched-a", "untouched-b"]) {
|
||||
assert.equal(lstatSync(join(outside, name)).ino, outsideInode);
|
||||
assert.equal(lstatSync(join(outside, name)).nlink, 2);
|
||||
}
|
||||
} finally { rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test("does not accept a symlink as the unpublished root", () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "provider-pack-layout-root-"));
|
||||
try {
|
||||
mkdirSync(join(root, "tree")); symlinkSync(join(root, "tree"), join(root, "link"));
|
||||
assert.throws(() => materializeIndependentProviderPackFiles(join(root, "link")), /build root/);
|
||||
} finally { rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
@@ -12,6 +12,9 @@ export function verifyReleaseProviderPack(identity, sourceRevision) {
|
||||
if (identity?.schema !== "paperclip-runner/remote-provider-pack/v1" || !payload
|
||||
|| payload.target?.platform !== "linux" || payload.target?.architecture !== "x64"
|
||||
|| payload.runnerSourceRevision !== sourceRevision) throw new Error("Remote provider pack must match the release source and Linux x64 target");
|
||||
if (payload.fileLayout !== undefined && payload.fileLayout !== "independent-regular-files-v1") {
|
||||
throw new Error("Remote provider-pack file layout is unsupported");
|
||||
}
|
||||
if (identity.digest !== `sha256:${createHash("sha256").update(canonical(payload)).digest("hex")}`) {
|
||||
throw new Error("Remote provider-pack payload digest mismatch");
|
||||
}
|
||||
|
||||
@@ -77,3 +77,14 @@ test("release assembly rejects rehashed stale or missing packs before staging an
|
||||
}
|
||||
} finally { rmSync(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test("file layout is a closed, digest-bound policy with legacy compatibility", () => {
|
||||
const legacy = seal(fixture());
|
||||
const independent = seal({ ...fixture(), fileLayout: "independent-regular-files-v1" });
|
||||
assert.notEqual(independent.digest, legacy.digest);
|
||||
assert.equal(verifyReleaseProviderPack(independent, revision), independent);
|
||||
assert.equal(verifyReleaseProviderPack(legacy, revision), legacy);
|
||||
for (const fileLayout of [null, {}, "unknown-policy"]) {
|
||||
assert.throws(() => verifyReleaseProviderPack(seal({ ...fixture(), fileLayout }), revision), /file layout/);
|
||||
}
|
||||
});
|
||||
@@ -1,3 +1,7 @@
|
||||
import { createRequire } from "node:module";
|
||||
import { readdir } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
@@ -246,3 +250,31 @@ describe("ACPX sidecar input sequencing", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("closed link-count failure detail", () => {
|
||||
const classify = (detail: string) => acpxSidecarErrorCode(Object.assign(new Error("private-canary"), {
|
||||
detailCode: "AGENT_STARTUP_FAILED", stderrSummary: `PAPERCLIP_ACPX_IMPORT_FAILURE:UNVERIFIED_MODULE:LINK_COUNT:END PAPERCLIP_ACPX_LINK_COUNT:${detail}:END private-canary /secret`,
|
||||
}));
|
||||
it.each(["1:1:2:I:11111110", "2:2:1:D:11111101", "1:0:18446744073709551615:I:11111111"])("preserves bounded metadata %s", detail => {
|
||||
expect(classify(detail)).toBe(`AGENT_STARTUP_FAILED.UNVERIFIED_MODULE.LINK_COUNT.READ.${detail.replaceAll(":", ".")}`);
|
||||
});
|
||||
it.each(["0:1:2:I:11111110", "3:1:2:I:11111110", "1:-1:2:I:11111110", "1:01:2:I:11111110", "1:1:18446744073709551616:I:11111110", "1:1:2:D:11111110", "1:1:1:I:11111110", "1:1:2:I:01111110", "1:1:2:I:111111100", "1:1:2:I:11111110.PRIVATE", "1:1:2:I:11111110:END_PRIVATE"])("drops malformed metadata without dropping fence: %s", detail => {
|
||||
expect(classify(detail)).toBe("AGENT_STARTUP_FAILED.UNVERIFIED_MODULE.LINK_COUNT");
|
||||
});
|
||||
it("survives the installed ACPX summarizer without leaking or accepting truncated details", async () => {
|
||||
const directory = dirname(createRequire(import.meta.url).resolve("acpx/runtime"));
|
||||
const chunk = (await readdir(directory)).find(name => /^live-checkpoint-.*\.js$/.test(name));
|
||||
expect(chunk).toBeDefined();
|
||||
const exports = await import(pathToFileURL(join(directory, chunk!)).href);
|
||||
const client = Object.values(exports).find(value => typeof value === "function" && typeof value.prototype?.summarizeStartupStderr === "function") as { prototype: { summarizeStartupStderr: (parts: string[]) => string } };
|
||||
const base = "PAPERCLIP_ACPX_IMPORT_FAILURE:UNVERIFIED_MODULE:LINK_COUNT:END";
|
||||
const detail = "PAPERCLIP_ACPX_LINK_COUNT:1:2:1:D:11111110:END";
|
||||
for (const complete of [true, false]) {
|
||||
const summary = client.prototype.summarizeStartupStderr([`${base}\n${complete ? detail : detail.slice(0, -1)}\nprivate-canary /secret`]);
|
||||
const code = acpxSidecarErrorCode(Object.assign(new Error("private-canary"), { detailCode: "AGENT_STARTUP_FAILED", stderrSummary: summary }));
|
||||
expect(code).toBe(`AGENT_STARTUP_FAILED.UNVERIFIED_MODULE.LINK_COUNT${complete ? ".READ.1.2.1.D.11111110" : ""}`);
|
||||
expect(code).not.toMatch(/private|secret/);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -97,7 +97,8 @@ function directAcpxSidecarErrorCode(error: Error): string | null {
|
||||
?? /(?:^|\n)PAPERCLIP_ACPX_IMPORT_FAILURE:(UNVERIFIED_MODULE|OTHER)(?::([A-Z_]+))?(?:\r?\n|$)/.exec(stderr);
|
||||
if (importFailure?.[1] === "UNVERIFIED_MODULE" && importFailure[2] === undefined) return "AGENT_STARTUP_FAILED.UNVERIFIED_MODULE";
|
||||
if (importFailure?.[1] === "UNVERIFIED_MODULE" && MODULE_FENCES.has(importFailure[2])) {
|
||||
return `AGENT_STARTUP_FAILED.UNVERIFIED_MODULE.${importFailure[2]}`;
|
||||
const detail = importFailure[2] === "LINK_COUNT" ? moduleLinkCountDetail(stderr) : null;
|
||||
return `AGENT_STARTUP_FAILED.UNVERIFIED_MODULE.${importFailure[2]}${detail ? `.READ.${detail.replaceAll(":", ".")}` : ""}`;
|
||||
}
|
||||
if (/ERR_ACPX_UNVERIFIED_MODULE/.test(stderr)) {
|
||||
return "AGENT_STARTUP_FAILED.UNVERIFIED_MODULE";
|
||||
@@ -181,3 +182,15 @@ const STABLE_ACPX_SIDECAR_CODES = new Set([
|
||||
"ACPX_TOOL_CALL_STALE",
|
||||
...GENERIC_ACPX_OUTPUT_CODES,
|
||||
]);
|
||||
|
||||
|
||||
/** Failure-only unsigned metadata; no provider strings or identifiers cross. */
|
||||
function moduleLinkCountDetail(stderr: string): string | null {
|
||||
const match = /(?:^|\s)PAPERCLIP_ACPX_LINK_COUNT:([12]):(0|[1-9][0-9]{0,19}):(0|[1-9][0-9]{0,19}):([ID]):(111111[01]{2}):END(?=\s|$)/.exec(stderr);
|
||||
if (!match) return null;
|
||||
const before = BigInt(match[2]!);
|
||||
const after = BigInt(match[3]!);
|
||||
if (before > 18446744073709551615n || after > 18446744073709551615n || before === after
|
||||
|| match[4] !== (after > before ? "I" : "D")) return null;
|
||||
return match.slice(1).join(":");
|
||||
}
|
||||
@@ -1766,6 +1766,10 @@ describe("ACPX installation integrity", () => {
|
||||
if (reasons[transition]) {
|
||||
pass = 0;
|
||||
expect(read).toThrow(expect.objectContaining({ code: "ERR_ACPX_UNVERIFIED_MODULE", moduleFence: reasons[transition] }));
|
||||
if (transition === "nlink") {
|
||||
pass = 0;
|
||||
expect(read).toThrow(expect.objectContaining({ moduleReadDiagnostic: "1:1:2:I:11111110" }));
|
||||
}
|
||||
}
|
||||
expect(pass).toBeLessThanOrEqual(2);
|
||||
if (transition === "snapshot_second") expect(verify).toHaveBeenCalledTimes(2);
|
||||
@@ -1774,7 +1778,19 @@ describe("ACPX installation integrity", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.runIf(process.platform !== "win32").each(["once", "recurring", "bytes", "mode", "rename", "replacement", "symlink"] as const)("loads dependency bytes only after stable ctime-only continuity (%s)", async (transition) => {
|
||||
it("reports the second read attempt without accepting link drift", () => {
|
||||
const bytes = Buffer.from("stable bytes");
|
||||
const before = { dev: 1n, ino: 2n, mode: 0o100444n, uid: 1n, gid: 1n, nlink: 1n,
|
||||
size: BigInt(bytes.length), mtimeNs: 10n, ctimeNs: 20n, isFile: () => true };
|
||||
let passes = 0;
|
||||
expect(() => readStableSnapshotModuleSource({ before, maxBytes: 64, verify: () => {},
|
||||
read: (buffer, offset, length, position) => { if (position === 0) passes++; return bytes.copy(buffer, offset, position, position + length); },
|
||||
stat: () => ({ ...before, ctimeNs: 21n, nlink: passes === 2 ? 0n : 1n }),
|
||||
})).toThrow(expect.objectContaining({ code: "ERR_ACPX_UNVERIFIED_MODULE", moduleFence: "LINK_COUNT", moduleReadDiagnostic: "2:1:0:D:11111111" }));
|
||||
expect(passes).toBe(2);
|
||||
});
|
||||
|
||||
it.runIf(process.platform !== "win32").each(["once", "recurring", "bytes", "mode", "rename", "replacement", "symlink", "link"] as const)("loads dependency bytes only after stable ctime-only continuity (%s)", async (transition) => {
|
||||
const fixture = await installationFixture();
|
||||
await writeFile(join(fixture.commandDirectory, "dependency.mjs"), 'export const value = "dependency-success";');
|
||||
const command = `import fs from 'node:fs';
|
||||
@@ -1785,6 +1801,7 @@ describe("ACPX installation integrity", () => {
|
||||
if (buffer.subarray(offset, offset + count).includes(Buffer.from('dependency-success'))) {
|
||||
moduleFd = fd; passes += 1;
|
||||
if (${JSON.stringify(transition)} === 'bytes' && passes === 2) buffer[offset] = 0;
|
||||
if (process.platform === 'linux' && passes === 1 && ${JSON.stringify(transition)} === 'link') fs.linkSync(new URL('./dependency.mjs', import.meta.url), new URL('./dependency-link.mjs', import.meta.url));
|
||||
if (passes === 1 && ['rename','replacement','symlink'].includes(${JSON.stringify(transition)})) {
|
||||
const named = new URL('./dependency.mjs', import.meta.url);
|
||||
fs.renameSync(named, new URL('./moved.mjs', import.meta.url));
|
||||
@@ -1799,6 +1816,7 @@ describe("ACPX installation integrity", () => {
|
||||
if (fd === moduleFd && options?.bigint) {
|
||||
metadata.ctimeNs += ${JSON.stringify(transition)} === 'recurring' ? BigInt(passes) : 1n;
|
||||
if (${JSON.stringify(transition)} === 'mode') metadata.mode ^= 0o100n;
|
||||
if (process.platform !== 'linux' && ${JSON.stringify(transition)} === 'link') metadata.nlink += 1n;
|
||||
}
|
||||
return metadata;
|
||||
};
|
||||
@@ -1821,7 +1839,12 @@ describe("ACPX installation integrity", () => {
|
||||
const [code] = await closed;
|
||||
expect(code).toBe(transition === "once" ? 0 : 1);
|
||||
expect(stdout).toBe(transition === "once" ? "dependency-success" : "");
|
||||
const fences: Record<string, string> = { recurring: "REPEATED_CTIME", bytes: "BYTE_CONTINUITY", mode: "MODE" };
|
||||
const fences: Record<string, string> = { recurring: "REPEATED_CTIME", bytes: "BYTE_CONTINUITY", mode: "MODE", link: "LINK_COUNT" };
|
||||
if (transition === "link") {
|
||||
expect(stderr).toContain("PAPERCLIP_ACPX_LINK_COUNT:1:1:2:I:11111110:END");
|
||||
expect(acpxSidecarErrorCode(Object.assign(new Error("private-canary"), { detailCode: "AGENT_STARTUP_FAILED", stderrSummary: stderr.replace(/\s+/gu, " ") })))
|
||||
.toBe("AGENT_STARTUP_FAILED.UNVERIFIED_MODULE.LINK_COUNT.READ.1.1.2.I.11111110");
|
||||
}
|
||||
const fence = fences[transition];
|
||||
if (fence && !(transition === "bytes" && process.platform === "darwin")) {
|
||||
expect(stderr).toContain(`PAPERCLIP_ACPX_IMPORT_FAILURE:UNVERIFIED_MODULE:${fence}:END\n`);
|
||||
|
||||
@@ -1870,9 +1870,9 @@ export function readStableSnapshotModuleSource(input: {
|
||||
verify: (bytes: Buffer) => void;
|
||||
maxBytes: number;
|
||||
}): Buffer {
|
||||
const reject = (moduleFence: string): never => {
|
||||
const reject = (moduleFence: string, moduleReadDiagnostic?: string): never => {
|
||||
throw Object.assign(new Error("ACPX provider module changed while it was read"), {
|
||||
code: "ERR_ACPX_UNVERIFIED_MODULE", moduleFence,
|
||||
code: "ERR_ACPX_UNVERIFIED_MODULE", moduleFence, ...(moduleReadDiagnostic ? { moduleReadDiagnostic } : {}),
|
||||
});
|
||||
};
|
||||
let before = input.before;
|
||||
@@ -1898,7 +1898,17 @@ export function readStableSnapshotModuleSource(input: {
|
||||
if (before.mode !== after.mode) reject("MODE");
|
||||
if (before.uid !== after.uid) reject("UID");
|
||||
if (before.gid !== after.gid) reject("GID");
|
||||
if (before.nlink !== after.nlink) reject("LINK_COUNT");
|
||||
if (before.nlink !== after.nlink) {
|
||||
// Failure-only data: never admit a link topology change as hydration.
|
||||
const bounded = before.nlink >= 0n && after.nlink >= 0n
|
||||
&& before.nlink <= 18446744073709551615n && after.nlink <= 18446744073709551615n;
|
||||
const equal = [before.dev === after.dev, before.ino === after.ino, before.mode === after.mode,
|
||||
before.uid === after.uid, before.gid === after.gid, before.size === after.size,
|
||||
before.mtimeNs === after.mtimeNs, before.ctimeNs === after.ctimeNs].map(value => value ? "1" : "0").join("");
|
||||
reject("LINK_COUNT", bounded
|
||||
? `${attempt + 1}:${before.nlink}:${after.nlink}:${after.nlink > before.nlink ? "I" : "D"}:${equal}`
|
||||
: undefined);
|
||||
}
|
||||
if (before.mtimeNs !== after.mtimeNs) reject("MTIME");
|
||||
if (first !== null && !first.equals(bytes)) reject("BYTE_CONTINUITY");
|
||||
if (before.ctimeNs === after.ctimeNs) return bytes;
|
||||
@@ -2060,7 +2070,7 @@ function snapshotBootstrap(format: AcpxCommandFormat, guarded = false): string {
|
||||
guarded
|
||||
? "const exitOnImportFailure = reapOnGuardianLoss;"
|
||||
: "const exitOnImportFailure = process.exit.bind(process);",
|
||||
'import(target).catch((error) => { let category = "OTHER"; try { if (error?.code === "ERR_ACPX_UNVERIFIED_MODULE") { category = "UNVERIFIED_MODULE"; const fence = error.moduleFence; if (["RESOLUTION", "OPEN", "BOUNDS", "ANCESTRY", "FORMAT", "PATH_IDENTITY", "READ_RESULT", "SIZE", "DEVICE", "INODE", "MODE", "UID", "GID", "LINK_COUNT", "MTIME", "BYTE_CONTINUITY", "REPEATED_CTIME"].includes(fence)) category += ":" + fence; } } catch {} try { writeImportFailure(2, "PAPERCLIP_ACPX_IMPORT_FAILURE:" + category + ":END\\n"); console.error(error); } finally { exitOnImportFailure(1); } });',
|
||||
'import(target).catch((error) => { let category = "OTHER"; try { if (error?.code === "ERR_ACPX_UNVERIFIED_MODULE") { category = "UNVERIFIED_MODULE"; const fence = error.moduleFence; if (["RESOLUTION", "OPEN", "BOUNDS", "ANCESTRY", "FORMAT", "PATH_IDENTITY", "READ_RESULT", "SIZE", "DEVICE", "INODE", "MODE", "UID", "GID", "LINK_COUNT", "MTIME", "BYTE_CONTINUITY", "REPEATED_CTIME"].includes(fence)) category += ":" + fence; } } catch {} try { writeImportFailure(2, "PAPERCLIP_ACPX_IMPORT_FAILURE:" + category + ":END\\n"); const detail = error?.moduleReadDiagnostic; if (category === "UNVERIFIED_MODULE:LINK_COUNT" && typeof detail === "string" && /^[12]:(0|[1-9][0-9]{0,19}):(0|[1-9][0-9]{0,19}):[ID]:111111[01]{2}$/.test(detail)) writeImportFailure(2, "PAPERCLIP_ACPX_LINK_COUNT:" + detail + ":END\\n"); console.error(error); } finally { exitOnImportFailure(1); } });',
|
||||
].join("");
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
chmod,
|
||||
cp,
|
||||
lstat,
|
||||
link,
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
open,
|
||||
@@ -1517,6 +1518,28 @@ describe("remote provider pack manifest", () => {
|
||||
expect(readRemoteProviderPackManifest(root).payload.pins.opencode).toBe(
|
||||
"1.18.34",
|
||||
);
|
||||
// Content digests cannot distinguish hardlinks from independent files.
|
||||
const legacyDigest = readRemoteProviderPackManifest(root).digest;
|
||||
const alias = join(root, "node_modules", "node-alias");
|
||||
await link(join(root, "node_modules", "node", "bin", "node"), alias);
|
||||
expect(readRemoteProviderPackManifest(root).digest).toBe(legacyDigest);
|
||||
Object.assign(payload, { fileLayout: "independent-regular-files-v1" });
|
||||
await writeManifest();
|
||||
expect(() => readRemoteProviderPackManifest(root)).toThrow("provider pack file layout");
|
||||
expect((await lstat(alias)).nlink).toBe(2); // Reject; never repair immutable caches.
|
||||
await rm(alias);
|
||||
const independent = readRemoteProviderPackManifest(root);
|
||||
expect(independent.digest).not.toBe(legacyDigest);
|
||||
expect(readBundledRemoteProviderPackManifest(join(root, "provider-pack.json")).digest).toBe(independent.digest);
|
||||
expect(independent.payload.distDigest).toBe(payload.distDigest);
|
||||
expect(readRemoteProviderPackManifest(root).digest).toBe(independent.digest);
|
||||
Object.assign(payload, { fileLayout: "unknown-policy" });
|
||||
await writeManifest();
|
||||
expect(() => readRemoteProviderPackManifest(root)).toThrow("provider pack file layout");
|
||||
expect(() => readBundledRemoteProviderPackManifest(join(root, "provider-pack.json"))).toThrow("provider pack file layout");
|
||||
delete (payload as typeof payload & { fileLayout?: string }).fileLayout;
|
||||
await writeManifest();
|
||||
expect(readRemoteProviderPackManifest(root).digest).toBe(legacyDigest);
|
||||
const cursorPath = "provider-assets/cursor/linux-x64";
|
||||
await mkdir(join(root, cursorPath), { recursive: true });
|
||||
await writeFile(join(root, cursorPath, "runtime"), "pinned Cursor runtime");
|
||||
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
import { nativeCompletionFeedback } from "./native-completion-feedback.js";
|
||||
import { hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent } from "../acknowledged-native-stop.js";
|
||||
import { stoppedCodexTurnIsTextOnly } from "./stopped-codex-turn.js";
|
||||
import { verifyProviderPackFileLayout } from "./remote-provider-pack-file-layout.js";
|
||||
import { prepareVerifiedRemoteProviderPack } from "./remote-provider-pack.js";
|
||||
import { verifyRemoteProviderPackArtifacts, assertRemoteProviderPackVerificationResult, computerProviderPackCachePath, prepareComputerProviderPackCache, pinnedComputerProviderPack, computerAcpxLaunchProfileDigest, readPinnedComputerProviderMetadata, assertPinnedComputerProviderState } from "./remote-provider-pack-cache.js";
|
||||
import { selectRemotePiCompanion } from "./remote-pi-companion.js";
|
||||
@@ -73,6 +74,7 @@ import {
|
||||
readSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -10219,6 +10221,7 @@ type RemoteProviderPackManifest = {
|
||||
schema: typeof REMOTE_PROVIDER_PACK_SCHEMA;
|
||||
digest: string;
|
||||
payload: {
|
||||
fileLayout?: "independent-regular-files-v1";
|
||||
pins: typeof REMOTE_PROVIDER_PACK_PINS;
|
||||
target: { platform: string; architecture: string };
|
||||
runnerSourceRevision: string;
|
||||
@@ -10366,6 +10369,7 @@ export function validateRemoteProviderPackIdentity(
|
||||
"runner_remote_provider_artifact_incompatible: provider pack pins or source revision do not match",
|
||||
);
|
||||
}
|
||||
verifyProviderPackFileLayout(null, payload.fileLayout, { lstatSync, statSync, readdirSync }, { join });
|
||||
const digest = `sha256:${createHash("sha256")
|
||||
.update(canonicalJson(payload))
|
||||
.digest("hex")}`;
|
||||
@@ -10476,6 +10480,9 @@ export function validateRemoteProviderPackIdentity(
|
||||
"runner_remote_provider_artifact_incompatible: provider bridge digest mismatch",
|
||||
);
|
||||
}
|
||||
if (verifyControllerFiles) {
|
||||
verifyProviderPackFileLayout(packRoot, payload.fileLayout, { lstatSync, statSync, readdirSync }, { join });
|
||||
}
|
||||
return structuredClone(manifest);
|
||||
}
|
||||
|
||||
@@ -12449,6 +12456,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
"const packageVersion=(pkg)=>JSON.parse(fs.readFileSync(path.join(root,'node_modules',...pkg.split('/'),'package.json'),'utf8')).version",
|
||||
"const expectedPackages={acpx:manifest.payload.pins.acpx,'@agentclientprotocol/claude-agent-acp':manifest.payload.pins.claudeAcp,'@agentclientprotocol/codex-acp':manifest.payload.pins.codexAcp,'opencode-ai':manifest.payload.pins.opencode}",
|
||||
"for(const [pkg,version] of Object.entries(expectedPackages))if(packageVersion(pkg)!==version)fail('package_version_mismatch')",
|
||||
`(${verifyProviderPackFileLayout.toString()})(root,manifest.payload.fileLayout,fs,path)`,
|
||||
].join(";");
|
||||
await verifyRemoteProviderPackArtifacts({
|
||||
runner: remoteCommandRunner,
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { verifyProviderPackFileLayout } from "./remote-provider-pack-file-layout.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });
|
||||
function fixture() {
|
||||
const root = fs.mkdtempSync(path.join(tmpdir(), "remote-file-layout-")); roots.push(root);
|
||||
fs.mkdirSync(path.join(root, "nested")); fs.writeFileSync(path.join(root, "nested", "one"), "same bytes");
|
||||
fs.symlinkSync("nested/one", path.join(root, "link"));
|
||||
return root;
|
||||
}
|
||||
function check(root: string, policy: unknown, remote: boolean) {
|
||||
if (!remote) return verifyProviderPackFileLayout(root, policy, fs, path);
|
||||
// Exercise precisely the self-contained function serialized by the guest verifier.
|
||||
const program = `const fs=require('node:fs'),path=require('node:path');(${verifyProviderPackFileLayout.toString()})(process.argv[1],JSON.parse(process.argv[2]).policy,fs,path)`;
|
||||
execFileSync(process.execPath, ["-e", program, root, JSON.stringify({ policy })], { stdio: "pipe" });
|
||||
}
|
||||
describe.each([false, true])("provider file layout validation remote=%s", remote => {
|
||||
it("accepts independent files and symlinks; rejects later hardlinks without repair", () => {
|
||||
const root = fixture(); const policy = "independent-regular-files-v1";
|
||||
check(root, policy, remote);
|
||||
fs.linkSync(path.join(root, "nested", "one"), path.join(root, "two"));
|
||||
expect(() => check(root, policy, remote)).toThrow("runner_remote_provider_artifact_incompatible: provider pack file layout");
|
||||
expect(fs.lstatSync(path.join(root, "two")).nlink).toBe(2);
|
||||
check(root, undefined, remote); // Legacy caches remain readable and unchanged.
|
||||
expect(fs.lstatSync(path.join(root, "two")).nlink).toBe(2);
|
||||
});
|
||||
it("accepts an authority-selected preinstalled root alias without following interior directory aliases", () => {
|
||||
const root = fixture();
|
||||
const aliasParent = fs.mkdtempSync(path.join(tmpdir(), "preinstalled-file-layout-")); roots.push(aliasParent);
|
||||
const alias = path.join(aliasParent, "approved-image-pack"); fs.symlinkSync(root, alias);
|
||||
const outside = path.join(aliasParent, "outside"); fs.mkdirSync(outside);
|
||||
fs.writeFileSync(path.join(outside, "one"), "unrelated");
|
||||
fs.linkSync(path.join(outside, "one"), path.join(outside, "two"));
|
||||
fs.symlinkSync(outside, path.join(root, "interior-directory-alias"));
|
||||
check(alias, "independent-regular-files-v1", remote);
|
||||
expect(fs.lstatSync(path.join(outside, "one")).nlink).toBe(2);
|
||||
fs.linkSync(path.join(root, "nested", "one"), path.join(root, "two"));
|
||||
expect(() => check(alias, "independent-regular-files-v1", remote)).toThrow("runner_remote_provider_artifact_incompatible: provider pack file layout");
|
||||
});
|
||||
it.each([null, "unknown-policy", {}, 1])("rejects unknown policy %j", policy => {
|
||||
expect(() => check(fixture(), policy, remote)).toThrow("runner_remote_provider_artifact_incompatible: provider pack file layout");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
/** Also serialized into the remote verifier; keep this body self-contained. */
|
||||
export function verifyProviderPackFileLayout(
|
||||
root: string | null,
|
||||
policy: unknown,
|
||||
fs: Pick<typeof import("node:fs"), "lstatSync" | "statSync" | "readdirSync">,
|
||||
path: Pick<typeof import("node:path"), "join">,
|
||||
): void {
|
||||
if (policy === undefined) return; // Existing immutable packs retain their original contract.
|
||||
if (policy !== "independent-regular-files-v1") throw new Error("runner_remote_provider_artifact_incompatible: provider pack file layout is unsupported");
|
||||
if (root === null) return; // Bundled manifest identity has no controller-side asset tree.
|
||||
// The caller may select an approved preinstalled-image root alias. Only this
|
||||
// root follows that alias; interior directory symlinks remain untouched.
|
||||
if (!fs.statSync(root).isDirectory()) throw new Error("runner_remote_provider_artifact_incompatible: provider pack file layout root is invalid");
|
||||
const visit = (directory: string): void => {
|
||||
for (const name of fs.readdirSync(directory)) {
|
||||
const file = path.join(directory, name);
|
||||
const stat = fs.lstatSync(file);
|
||||
if (stat.isDirectory()) visit(file);
|
||||
else if (stat.isFile()) {
|
||||
if (stat.nlink !== 1) throw new Error("runner_remote_provider_artifact_incompatible: provider pack file layout requires independent regular files");
|
||||
} else if (!stat.isSymbolicLink()) throw new Error("runner_remote_provider_artifact_incompatible: provider pack file layout entry is unsupported");
|
||||
}
|
||||
};
|
||||
visit(root);
|
||||
}
|
||||
Reference in new issue
Block a user