Test SDK evidence against an owned reviewed reference

This commit is contained in:
Dotta committed 2026-11-10 11:37:22 -06:00
1 parent ae246610d0
commit 6284d6881b
3 files changed
+133 -17

No files matched your search

+50 -3
View File
@@ -5,6 +5,8 @@ import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { existsSync } from "node:fs";
import { prepareReviewedSdkReference } from "./source-sdk-reviewed-fixture.js";
import pins from "./source-sdk-public-inputs.json" with { type: "json" };
import { afterEach, expect, it } from "vitest";
import { stagePrivateDiagnostics } from "./private-diagnostics.js";
import { prepareSourceServerDependencies } from "./source-startup.js";
@@ -110,11 +112,24 @@ it("retains declarations and source maps under names the private result sealer a
for (const file of receipt.files) expect(hash(await readFile(path.join(uploadDir, SOURCE_SDK_DIAGNOSTICS, file.retainedPath)))).toBe(file.sha256);
await expect(sealManualResultEvidence(context, [], results)).resolves.not.toThrow();
});
// Needs the built SDK (scripts/ensure-plugin-build-deps.mjs) and the pinned public source.
// Build a genuine OWN normal producer-certified reviewed reference. The live
// CI lock can be regenerated for unrelated PR patches and must not be relabeled reviewed.
const builtSdk = ["packages/shared/dist", "packages/plugins/sdk/dist"].every(target =>
existsSync(new URL(`../../${target}/.paperclip-build-complete`, import.meta.url)));
it.skipIf(!builtSdk)("seals the real built SDK upload, keeping proven key-shaped declarations out", async () => {
const repositoryRoot = await realpath(path.resolve(import.meta.dirname, "../.."));
it("seals a normal producer-certified reviewed-reference SDK, keeping key-shaped declarations out", async () => {
const originalRoot=await realpath(path.resolve(import.meta.dirname,"../.."));
const repositoryRoot=await realpath(await mkdtemp(path.join(os.tmpdir(),"source-sdk-reviewed-build-")));roots.push(repositoryRoot);
await prepareReviewedSdkReference(originalRoot,repositoryRoot);
// Existing normal Shared then SDK producer, exact original configs/options.
// Fresh dist directories and OWN cache/Shared resolution; no donor outputs.
expect(existsSync(path.join(repositoryRoot,"packages/shared/dist"))).toBe(false);
expect(existsSync(path.join(repositoryRoot,"packages/plugins/sdk/dist"))).toBe(false);
await prepareSourceServerDependencies(repositoryRoot,{...process.env},false);
for(const directory of ["packages/shared/dist","packages/plugins/sdk/dist"]){
expect(await realpath(path.join(repositoryRoot,directory))).toBe(path.join(repositoryRoot,directory));
expect(JSON.parse(await readFile(path.join(repositoryRoot,directory,".paperclip-build-complete"),"utf8")))
.toMatchObject({sources:expect.stringMatching(/^[a-f0-9]{64}$/),outputs:expect.stringMatching(/^[a-f0-9]{64}$/)});
}
const root = await realpath(await mkdtemp(path.join(os.tmpdir(), "source-sdk-real-unit-"))); roots.push(root);
const temporaryRoot = path.join(root, "attempt"), results = path.join(root, "results"), uploadDir = path.join(results, "campaign", "attempt-1");
await mkdir(path.join(temporaryRoot, "artifacts-private"), { recursive: true, mode: 0o700 }); await mkdir(path.join(temporaryRoot, "selected-private-inputs"), { recursive: true, mode: 0o700 });
@@ -126,3 +141,35 @@ it.skipIf(!builtSdk)("seals the real built SDK upload, keeping proven key-shaped
const context = { root, protocol: MANUAL_PRIVATE_PROTOCOL, private: true, workflowSha: "a".repeat(40), targetSha: "b".repeat(40), runId: "123", attempt: "1", executionIds: [MANUAL_PRIVATE_EXECUTIONS[0]!] } as ManualPrivateHandoff;
await expect(sealManualResultEvidence(context, secrets, results)).resolves.not.toThrow();
}, 120_000);
it("withholds real unreviewed-build SDK bytes instead of authenticating the CI-resolved lock",async()=>{
const originalRoot=await realpath(path.resolve(import.meta.dirname,"../.."));
let repositoryRoot=originalRoot,restoreLock:(()=>Promise<void>)|undefined;
const actual=await readFile(path.join(originalRoot,"pnpm-lock.yaml"));
if(hash(actual)===pins.lockSha256){
// On a reviewed local checkout, make the same refusal observable in an
// OWN genuine-built reference by invalidating only its owning lock input.
repositoryRoot=await realpath(await mkdtemp(path.join(os.tmpdir(),"source-sdk-unreviewed-build-")));roots.push(repositoryRoot);
await prepareReviewedSdkReference(originalRoot,repositoryRoot);
await prepareSourceServerDependencies(repositoryRoot,{...process.env},false);
const file=path.join(repositoryRoot,"pnpm-lock.yaml"),reviewed=await readFile(file);
await writeFile(file,Buffer.concat([reviewed,Buffer.from("\n# unreviewed unit input mutation\n")]));
restoreLock=()=>writeFile(file,reviewed);
}else if(!builtSdk)throw new Error("Unreviewed CI build requires its actual normal producer outputs");
const root=await realpath(await mkdtemp(path.join(os.tmpdir(),"source-sdk-unreviewed-refusal-")));roots.push(root);
const temporaryRoot=path.join(root,"attempt");
await mkdir(path.join(temporaryRoot,"selected-private-inputs"),{recursive:true,mode:0o700});
stagePrivateDiagnostics(temporaryRoot,[executionId],["synthetic-unit-provider-credential-0123456789"]);
try{
await expect(retainPreparedSourceSdk({repositoryRoot,temporaryRoot,executionIds:[executionId],sourceRevision,installed:false}))
.rejects.toThrow("Source SDK evidence privacy check failed; bytes withheld");
const file=path.join(temporaryRoot,"artifacts-private/cases/plugins.install-plugin/snapshots/source-sdk-privacy-observations.json");
const observation=JSON.parse(await readFile(file,"utf8"));
expect(observation.complete).toBe(false);expect(observation.audit.publicSource).toBeNull();
expect(observation.audit.bounded).toBe(true);expect(observation.audit.suppressedFindings).toBe(0);
expect(observation.audit.observations).toEqual(expect.arrayContaining([expect.objectContaining({
pathSha256:hash("packages/shared/dist/validators/agent.d.ts"),detector:3,classification:"unresolved_context"})]));
await expect(stat(path.join(temporaryRoot,"artifacts-private/source-sdk-build/receipt.json"))).rejects.toThrow();
await expect(stat(path.join(temporaryRoot,"artifacts-private/source-sdk-build/packages"))).rejects.toThrow();
}finally{await restoreLock?.();}
},120_000);
+11 -14
View File
@@ -3,6 +3,7 @@ import { copyFile, mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile }
import path from "node:path";
import os from "node:os";
import { beforeAll, afterAll, expect, it } from "vitest";
import { prepareReviewedSdkReference } from "./source-sdk-reviewed-fixture.js";
import pins from "./source-sdk-public-inputs.json" with { type: "json" };
import { createSdkArtifactScanner, sdkPublicTypeSyntax, verifySdkPublicSource } from "./source-sdk-public-type.js";
import { findSecretLeakMatch, normalizedSecrets } from "./redaction.js";
@@ -12,16 +13,18 @@ const blob = (v: string | Buffer) => createHash("sha1").update(`blob ${Buffer.by
const originalRoot = path.resolve(import.meta.dirname, "../.."), file = "packages/shared/dist/validators/synthetic-unit.d.ts", inputFile = file.replace("/dist/", "/src/").replace(/\.d\.ts$/, ".ts");
const source = 'import {z} from "zod";export const schema=z.object({daytona_api_key:z.string().min(1)});';
const declaration = 'import {z} from "zod";export declare const schema:{daytona_api_key:z.ZodOptional<z.ZodString>};';
let root: string; let fixtureLockSha256: string;
let root: string; let reviewedRoot: string; let fixtureLockSha256: string;
const fixtureInputs: Record<string, string> = {};
beforeAll(async () => {
root = await realpath(await mkdtemp(path.join(os.tmpdir(), "sdk-public-type-synthetic-")));
for (const [relative] of Object.entries(pins.inputs)) { const dest = path.join(root, relative); await mkdir(path.dirname(dest), { recursive: true }); await copyFile(path.join(originalRoot, relative), dest); fixtureInputs[relative] = blob(await readFile(dest)); }
await copyFile(path.join(originalRoot, "pnpm-lock.yaml"), path.join(root, "pnpm-lock.yaml")); fixtureLockSha256 = hash(await readFile(path.join(root, "pnpm-lock.yaml")));
await symlink(await realpath(path.join(originalRoot, "node_modules")), path.join(root, "node_modules"));
await symlink(await realpath(path.join(originalRoot, "packages/shared/node_modules")), path.join(root, "packages/shared/node_modules"));
await prepareReviewedSdkReference(originalRoot,root);
reviewedRoot=await realpath(await mkdtemp(path.join(os.tmpdir(),"sdk-public-reviewed-reference-")));
await prepareReviewedSdkReference(originalRoot,reviewedRoot);
for(const relative of Object.keys(pins.inputs))fixtureInputs[relative]=blob(await readFile(path.join(root,relative)));
fixtureLockSha256=hash(await readFile(path.join(root,"pnpm-lock.yaml")));
});
afterAll(async () => { if (root) await rm(root, { recursive: true, force: true }); });
afterAll(async () => { for(const directory of [root,reviewedRoot])if(directory)await rm(directory,{recursive:true,force:true}); });
async function fixture(sourceText = source) {
await mkdir(path.dirname(path.join(root, inputFile)), { recursive: true }); await writeFile(path.join(root, inputFile), sourceText);
return { ...pins, lockSha256: fixtureLockSha256, inputs: { ...fixtureInputs, [inputFile]: blob(sourceText) } };
@@ -29,13 +32,7 @@ async function fixture(sourceText = source) {
it("default public proof accepts the reviewed build lock and still rejects a changed lock", async () => {
const directory = await realpath(await mkdtemp(path.join(os.tmpdir(), "sdk-reviewed-runtime-")));
try {
for (const relative of Object.keys(pins.inputs)) {
const destination = path.join(directory, relative);
await mkdir(path.dirname(destination), { recursive: true });
await copyFile(path.join(originalRoot, relative), destination);
}
await symlink(await realpath(path.join(originalRoot, "node_modules")), path.join(directory, "node_modules"));
await symlink(await realpath(path.join(originalRoot, "packages/shared/node_modules")), path.join(directory, "packages/shared/node_modules"));
await prepareReviewedSdkReference(originalRoot,directory);
const reviewed = JSON.parse(await readFile(path.join(originalRoot, "tests/runner-e2e/report-lock.json"), "utf8"));
const lock = await readFile(path.join(directory, "pnpm-lock.yaml"));
expect(hash(lock)).toBe(reviewed.outputSha256);
@@ -56,7 +53,7 @@ it("classifies the shipped agent env schema declaration and keeps a literal at t
// Plugin cells retain packages/shared/dist/validators/agent.d.ts, whose
// `OPENROUTER_API_KEY: z.ZodOptional<z.ZodString>` matches the OpenRouter key
// shape. Stale default pins left it unresolved and blocked web-server startup.
const repository = await realpath(originalRoot), agentFile = "packages/shared/dist/validators/agent.d.ts";
const repository = reviewedRoot, agentFile = "packages/shared/dist/validators/agent.d.ts";
const shipped = 'import { z } from "zod";\nexport declare const env: z.ZodObject<{\n OPENROUTER_API_KEY: z.ZodOptional<z.ZodString>;\n}>;\n';
const scanner = createSdkArtifactScanner(repository, []); expect(await scanner.scan(agentFile, Buffer.from(shipped))).toBe(true);
expect((await scanner.audit()).observations.map(row => row.classification)).toEqual(["public_schema_type"]);
@@ -0,0 +1,72 @@
// Test-only reviewed SDK reference. Actual CI builds may use an unreviewed
// resolved lock; neither this fixture nor production admits that as public proof.
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { copyFile, mkdir, readFile, readdir, realpath, symlink, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import path from "node:path";
import pins from "./source-sdk-public-inputs.json" with { type: "json" };
import { prepareReportLock } from "./prepare-report-lock.mjs";
import { verifySdkPublicSource } from "./source-sdk-public-type.js";
const sha=(bytes:Buffer)=>createHash("sha256").update(bytes).digest("hex");
const blob=(bytes:Buffer)=>createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
const gitFile=(root:string,file:string)=>execFileSync("git",["show",`HEAD:${file}`],{cwd:root,maxBuffer:8*1024*1024,stdio:["ignore","pipe","pipe"]});
// Create owned directories, link only read-only installed third-party inputs.
// Never link workspace compiled exports or donor node_modules/.cache: the
// normal producer's lock and every Shared/SDK emit stay in this fixture root.
async function thirdPartyLinks(from:string,to:string,installedStore:string){
const link=async(source:string,destination:string)=>{
const target=await realpath(source);
// A local workspace may have an unscoped name too. Admit only installed
// third-party store entries, never another checkout/package's exports.
if(target!==installedStore&&!target.startsWith(installedStore+path.sep))return;
await symlink(target,destination);
};
await mkdir(to,{recursive:true});
for(const entry of await readdir(from,{withFileTypes:true})){
if([".cache",".bin","@paperclipai"].includes(entry.name))continue;
const source=path.join(from,entry.name),destination=path.join(to,entry.name);
if(entry.name.startsWith("@")){
await mkdir(destination,{recursive:true});
for(const child of await readdir(source))await link(path.join(source,child),path.join(destination,child));
}else await link(source,destination);
}
}
export async function prepareReviewedSdkReference(original:string,directory:string){
if(await realpath(directory)!==directory||(await readdir(directory)).length!==0)throw new Error("Reviewed SDK reference needs a fresh owned directory");
const policyFile="tests/runner-e2e/report-lock.json",patchFile="tests/runner-e2e/report-lock.patch";
const policyBytes=gitFile(original,policyFile),policy=JSON.parse(policyBytes.toString("utf8"));
if(!(await readFile(path.join(original,policyFile))).equals(policyBytes)||policy.outputSha256!==pins.lockSha256)
throw new Error("Reviewed SDK reference policy does not match public proof");
const committed=gitFile(original,"pnpm-lock.yaml");
if(![policy.inputSha256,policy.outputSha256].includes(sha(committed)))throw new Error("Committed SDK reference lock is not reviewed");
for(const [file,expected]of Object.entries(pins.inputs)){
const bytes=file==="pnpm-lock.yaml"?committed:await readFile(path.join(original,file));
if(file!=="pnpm-lock.yaml"&&blob(bytes)!==expected)throw new Error("Reviewed SDK reference source changed");
const target=path.join(directory,file);await mkdir(path.dirname(target),{recursive:true});
if(file==="pnpm-lock.yaml")await writeFile(target,bytes);else await copyFile(path.join(original,file),target);
}
for(const file of [policyFile,patchFile]){
const bytes=gitFile(original,file);
if(!(await readFile(path.join(original,file))).equals(bytes))throw new Error("Reviewed SDK lock policy changed");
const target=path.join(directory,file);await mkdir(path.dirname(target),{recursive:true});
await writeFile(target,bytes);
}
// Same existing authenticated input->output correction. No hash refresh,
// changed-lock admission, install, resolver or compiler-option substitution.
await prepareReportLock(directory);
if(sha(await readFile(path.join(directory,"pnpm-lock.yaml")))!==policy.outputSha256)throw new Error("Reviewed SDK reference lock changed");
const installedStore=await realpath(path.join(original,"node_modules/.pnpm"));
await thirdPartyLinks(path.join(original,"node_modules"),path.join(directory,"node_modules"),installedStore);
for(const name of ["shared","plugins/sdk"])await thirdPartyLinks(path.join(original,"packages",name,"node_modules"),path.join(directory,"packages",name,"node_modules"),installedStore);
for(const modules of ["node_modules","packages/plugins/sdk/node_modules"]){
const scope=path.join(directory,modules,"@paperclipai");await mkdir(scope,{recursive:true});
await symlink(path.join(directory,"packages/shared"),path.join(scope,"shared"));
}
const require=createRequire(path.join(directory,"packages/plugins/sdk/package.json"));
const sharedEntry=await realpath(require.resolve("@paperclipai/shared"));
if(!sharedEntry.startsWith(path.join(directory,"packages/shared")+path.sep))throw new Error("SDK reference resolved a donor workspace");
// Authenticate original compiler/parser/Zod/source pins BEFORE normal build.
await verifySdkPublicSource(directory);
}