mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 21:21:27 +01:00
test: retain selected input blockers and authenticate private oracle identity
This commit is contained in:
1 parent
8c9b4ac273
commit
994897f542
7 files changed
+154
-12
No files matched your search
@@ -1,3 +1,4 @@
|
||||
import { verifyRetainedChatOracleIdentity } from "./chat-private-inputs.js";
|
||||
import { installedChatFingerprintIdentity, installedChatScenarioIds } from "./chat-installed-lane.js";
|
||||
import { chatPrivateInputRequirements, chatPrivateInputNameIdentity } from "./chat-private-inputs.js";
|
||||
import { createHash } from "node:crypto";
|
||||
@@ -91,6 +92,7 @@ export function chatCatalogCaseFingerprint(descriptor: ChatCatalogDescriptor, se
|
||||
selectedExecution = { ...(selectedExecution as Record<string, unknown>), journeyKind: descriptor.journeyKind ?? "agent-chat" };
|
||||
const root = fileURLToPath(new URL("../../", import.meta.url));
|
||||
const privateInputNameIdentity = retainedPrivateInputNames === undefined ? chatPrivateInputNameIdentity((selectedExecution as { executionId: string }).executionId) : retainedPrivateInputNames;
|
||||
if (retainedPrivateInputNames !== undefined) verifyRetainedChatOracleIdentity(retainedPrivateInputNames, descriptor);
|
||||
const lane = assertChatCatalogFingerprintLane({ ...(selectedExecution as Record<string, unknown>), scenarioId: descriptor.scenarioId, installedSource: descriptor.installedSource });
|
||||
const installedObservation = descriptor.installedSource && retainedInstalledIdentity === undefined
|
||||
? installedChatFingerprintIdentity(process.env, (selectedExecution as { executionId: string }).executionId) : undefined;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { mkdtempSync, writeFileSync, statSync, chmodSync, rmSync } from "node:fs
|
||||
import path from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { stageChatPrivateInputs, readChatPrivateInputs, chatPrivateInputNameIdentity, scrubChatPrivateEnvironment, CHAT_PRIVATE_INPUTS_ENV } from "./chat-private-inputs.js";
|
||||
import { stageChatPrivateInputs, readChatPrivateInputs, chatPrivateSetupBlockers, chatLaunchCredentialNames, chatPrivateInputNameIdentity, scrubChatPrivateEnvironment, CHAT_PRIVATE_INPUTS_ENV } from "./chat-private-inputs.js";
|
||||
import type { MatrixExecution } from "./types.js";
|
||||
import type { ChatCatalogDescriptor } from "./chat-catalog-registry.js";
|
||||
import { runtimePrivateRequirements } from "./chat-runtime-private-requirements.js";
|
||||
@@ -77,5 +77,27 @@ it("resolves only the finite SSH private key reference and refuses an alternate
|
||||
const inputs = readChatPrivateInputs("selected", [], { [CHAT_PRIVATE_INPUTS_ENV]: staged.filename, PAPERCLIP_RUNNER_E2E_TEMP_ROOT: root });
|
||||
expect(inputs.read("PAPERCLIP_CHAT_EVAL_SSH_PRIVATE_KEY")).toBe("selected-ssh-key"); expect(inputs.read("PAPERCLIP_CHAT_EVAL_OTHER_KEY")).toBeUndefined();
|
||||
prerequisites.privateKeyEnv = "PAPERCLIP_CHAT_EVAL_OTHER_KEY"; writeFileSync(configFile, JSON.stringify(config), { mode: 0o600 });
|
||||
expect(() => stageChatPrivateInputs({ execution: { ...execution, task: { id: scenarioId } } as MatrixExecution, descriptor, privateDir: root, secrets: [], env: { PAPERCLIP_CHAT_CATALOG_EXTERNAL_CONFIG: configFile, PAPERCLIP_CHAT_EVAL_OTHER_KEY: "wrong-key" } })).toThrow("finite contract");
|
||||
rmSync(staged.filename);
|
||||
const blocked = stageChatPrivateInputs({ execution: { ...execution, task: { id: scenarioId } } as MatrixExecution, descriptor, privateDir: root, secrets: [], env: { PAPERCLIP_CHAT_CATALOG_EXTERNAL_CONFIG: configFile, PAPERCLIP_CHAT_EVAL_OTHER_KEY: "wrong-key" } });
|
||||
const blockedInputs = readChatPrivateInputs("selected", [], { [CHAT_PRIVATE_INPUTS_ENV]: blocked.filename, PAPERCLIP_RUNNER_E2E_TEMP_ROOT: root });
|
||||
expect(chatPrivateSetupBlockers(blockedInputs, descriptor)).toContain("unavailable-external-configuration:ssh"); expect(blockedInputs.read("PAPERCLIP_CHAT_EVAL_OTHER_KEY")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("retains missing selected credentials inside a reserved setup receipt while profile credentials stay launch prerequisites", () => {
|
||||
const root = fixture(); const descriptor = { requiredCredentials: ["OPENAI_API_KEY" as const] };
|
||||
const selected = { ...execution, requiredCredentials: ["CODEX_AUTH_JSON", "OPENAI_API_KEY"] } as MatrixExecution;
|
||||
const staged = stageChatPrivateInputs({ execution: selected, descriptor, privateDir: root, secrets: [], env: {} });
|
||||
const env = { [CHAT_PRIVATE_INPUTS_ENV]: staged.filename, PAPERCLIP_RUNNER_E2E_TEMP_ROOT: root };
|
||||
const inputs = readChatPrivateInputs("selected", [], env);
|
||||
expect(chatPrivateSetupBlockers(inputs, descriptor)).toEqual(["missing-credential:OPENAI_API_KEY"]);
|
||||
expect(chatPrivateInputNameIdentity("selected", env)?.credentialNames).toEqual(["OPENAI_API_KEY"]);
|
||||
expect(chatLaunchCredentialNames(selected, descriptor)).toEqual(["CODEX_AUTH_JSON"]);
|
||||
expect(chatLaunchCredentialNames({ ...selected, profile: { ...selected.profile, credential: "OPENAI_API_KEY" } }, descriptor)).toContain("OPENAI_API_KEY");
|
||||
});
|
||||
it("stages missing provider fields/configuration as sanitized setup blockers without leaking private filenames", () => {
|
||||
const root = fixture(); const descriptor = { externalInput: { provider: "notion" as const, fields: ["recentFactJson"] } };
|
||||
const staged = stageChatPrivateInputs({ execution, descriptor, privateDir: root, secrets: [], env: { PAPERCLIP_CHAT_CATALOG_EXTERNAL_CONFIG: "/private/not-an-existing-fixture" } });
|
||||
const inputs = readChatPrivateInputs("selected", [], { [CHAT_PRIVATE_INPUTS_ENV]: staged.filename, PAPERCLIP_RUNNER_E2E_TEMP_ROOT: root });
|
||||
expect(chatPrivateSetupBlockers(inputs, descriptor)).toEqual(["unavailable-external-configuration:notion"]);
|
||||
expect(JSON.stringify(inputs.setupBlockers)).not.toContain("not-an-existing-fixture");
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { CHAT_ORACLE_KEY_ENV, privateOracleIdentity, oracleSemanticFields, verifyRetainedPrivateOracle, type PrivateOracleIdentity } from "./chat-private-oracle.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { lstatSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
@@ -10,11 +11,12 @@ const externalConfigEnv = "PAPERCLIP_CHAT_CATALOG_EXTERNAL_CONFIG";
|
||||
export interface ChatExternalInputRequirement { provider: "notion" | "slack" | "agentmail" | "vault" | "github" | RuntimePrivateProvider; fields: readonly string[] }
|
||||
type PrivateInputDescriptor = Pick<ChatCatalogDescriptor, "requiredCredentials" | "externalInput"> & Partial<Pick<ChatCatalogDescriptor, "scenarioId">>;
|
||||
export interface ChatPrivateInputs {
|
||||
readonly setupBlockers?: readonly string[];
|
||||
readonly credentials: Readonly<Partial<Record<CredentialName, string>>>;
|
||||
read(name: string): string | undefined;
|
||||
configuration(name: "external-provider"): unknown;
|
||||
}
|
||||
interface PrivateEnvelope { version: 1; executionId: string; credentials: Partial<Record<CredentialName, string>>; references: Record<string, string>; external?: unknown }
|
||||
interface PrivateEnvelope { version: 1; executionId: string; credentials: Partial<Record<CredentialName, string>>; references: Record<string, string>; external?: unknown; setupBlockers?: string[]; oracleExpectation?: PrivateOracleIdentity; declaredCredentialNames?: string[]; declaredReferenceNames?: string[]; declaredExternalRequirements?: Array<{ provider: string; fields: string[] }> }
|
||||
function readPrivateJson(filename: string, ownedRoot?: string): unknown {
|
||||
const info = lstatSync(filename);
|
||||
if (!info.isFile() || info.isSymbolicLink() || info.mode & 0o077 || info.size > 262144
|
||||
@@ -35,15 +37,19 @@ export function chatPrivateInputRequirements(descriptor?: PrivateInputDescriptor
|
||||
export function stageChatPrivateInputs(input: { execution: MatrixExecution; descriptor?: PrivateInputDescriptor; privateDir: string; env: NodeJS.ProcessEnv; secrets: string[] }) {
|
||||
if (input.descriptor?.scenarioId && input.execution.task?.id !== input.descriptor.scenarioId) throw new Error("Selected private input declaration belongs to another scenario");
|
||||
const requirements = chatPrivateInputRequirements(input.descriptor);
|
||||
const envelope: PrivateEnvelope = { version: 1, executionId: input.execution.id, credentials: {}, references: {} };
|
||||
const envelope: PrivateEnvelope = { version: 1, executionId: input.execution.id, credentials: {}, references: {}, setupBlockers: [], declaredCredentialNames: requirements.credentialNames, declaredReferenceNames: [], declaredExternalRequirements: requirements.external ? [{ provider: requirements.external.provider, fields: requirements.external.fields }] : [] };
|
||||
for (const name of requirements.credentialNames) {
|
||||
const value = input.env[name]?.trim(); if (!value) throw new Error(`Missing selected-case credential ${name}`);
|
||||
const value = input.env[name]?.trim(); if (!value) { envelope.setupBlockers!.push(`missing-credential:${name}`); continue; }
|
||||
envelope.credentials[name] = value; input.secrets.push(value);
|
||||
}
|
||||
if (requirements.external) {
|
||||
try {
|
||||
const ref = input.env[externalConfigEnv]; if (!ref) throw new Error("Missing selected-case private external configuration");
|
||||
const config = readPrivateJson(ref) as { schemaVersion?: number; providers?: Record<string, { disposable?: boolean; resourceIds?: string[]; credentialEnv?: string[]; prerequisites?: Record<string, string> }> };
|
||||
const binding = config.schemaVersion === 1 ? config.providers?.[requirements.external.provider] : undefined;
|
||||
if (binding?.prerequisites) for (const field of requirements.external.fields) {
|
||||
if (typeof binding.prerequisites[field] !== "string" || !binding.prerequisites[field]?.trim()) envelope.setupBlockers!.push(`missing-external-field:${requirements.external.provider}:${field}`);
|
||||
}
|
||||
if (!binding || binding.disposable !== true || !Array.isArray(binding.resourceIds) || !binding.resourceIds.length
|
||||
|| !Array.isArray(binding.credentialEnv) || (!binding.credentialEnv.length && !runtimePrivateProviders.includes(requirements.external.provider)) || !binding.prerequisites
|
||||
|| requirements.external.fields.some(field => typeof binding.prerequisites?.[field] !== "string" || !binding.prerequisites[field]?.trim())) throw new Error("Selected disposable external configuration lacks declared prerequisites; contents withheld");
|
||||
@@ -54,12 +60,16 @@ export function stageChatPrivateInputs(input: { execution: MatrixExecution; desc
|
||||
const expected = runtimePrivateReferenceNames(requirements.external.provider);
|
||||
if (expected.some(name => !names.includes(name)) || names.some(name => !expected.includes(name))) throw new Error("Runtime private reference names do not match the selected provider's finite contract");
|
||||
}
|
||||
envelope.declaredReferenceNames = [...new Set(names)].sort();
|
||||
for (const name of new Set(names)) {
|
||||
if (!/^PAPERCLIP_CHAT_EVAL_[A-Z0-9_]+$/.test(name)) throw new Error("External credential reference is not a declared private environment name");
|
||||
const value = input.env[name]?.trim(); if (!value) throw new Error(`Missing selected external environment reference ${name}`);
|
||||
const value = input.env[name]?.trim(); if (!value) { envelope.setupBlockers!.push(`missing-external-reference:${name}`); continue; }
|
||||
envelope.references[name] = value; input.secrets.push(value);
|
||||
}
|
||||
try { envelope.oracleExpectation = privateOracleIdentity(requirements.external.provider, requirements.external.fields, selected.prerequisites, input.env); }
|
||||
catch { envelope.setupBlockers!.push(`unavailable-oracle-commitment:${requirements.external.provider}`); }
|
||||
envelope.external = { schemaVersion: 1, providers: { [requirements.external.provider]: selected } };
|
||||
} catch { envelope.setupBlockers!.push(`unavailable-external-configuration:${requirements.external.provider}`); }
|
||||
}
|
||||
const filename = path.join(input.privateDir, "chat-selected-inputs.json");
|
||||
writeFileSync(filename, JSON.stringify(envelope), { mode: 0o600, flag: "wx" });
|
||||
@@ -76,10 +86,12 @@ export function readChatPrivateInputs(executionId: string, secrets: string[], en
|
||||
if (typeof value !== "string" || !value.trim()) throw new Error("Invalid private credential value; contents withheld");
|
||||
secrets.push(value);
|
||||
}
|
||||
return { credentials: Object.freeze(envelope.credentials), read: name => envelope.references[name] ?? envelope.credentials[name as CredentialName],
|
||||
if (envelope.setupBlockers?.some(value => !/^(?:missing-credential:[A-Z0-9_]+|missing-external-reference:PAPERCLIP_CHAT_EVAL_[A-Z0-9_]+|missing-external-field:[a-zA-Z]+:[a-zA-Z][a-zA-Z0-9]*|(?:unavailable-external-configuration|unavailable-oracle-commitment):[a-zA-Z]+)$/.test(value))) throw new Error("Invalid private setup blocker receipt");
|
||||
return { setupBlockers: Object.freeze(envelope.setupBlockers ?? []), credentials: Object.freeze(envelope.credentials), read: name => envelope.references[name] ?? envelope.credentials[name as CredentialName],
|
||||
configuration: name => name === "external-provider" ? envelope.external : undefined };
|
||||
}
|
||||
export function scrubChatPrivateEnvironment(env: NodeJS.ProcessEnv, executions: readonly MatrixExecution[], removeReference = false) {
|
||||
delete env[CHAT_ORACLE_KEY_ENV];
|
||||
for (const key of Object.keys(env)) if (key.startsWith("PAPERCLIP_CHAT_EVAL_") || key === externalConfigEnv || removeReference && [CHAT_PRIVATE_INPUTS_ENV, "PAPERCLIP_CHAT_INSTALLED_PLAN", "PAPERCLIP_CHAT_OPERATOR_INSTALL_RECEIPT", "PAPERCLIP_CHAT_INSTALLED_SOURCE_CONFIG"].includes(key)) delete env[key];
|
||||
if (executions.length) {
|
||||
const profileNames = new Set(executions.flatMap(execution => [execution.profile.credential, execution.environment.credential].filter(Boolean)));
|
||||
@@ -95,6 +107,28 @@ export function chatPrivateInputNameIdentity(executionId: string, env: NodeJS.Pr
|
||||
const envelope = readPrivateJson(reference, root) as PrivateEnvelope;
|
||||
if (envelope.executionId !== executionId) throw new Error("Private input identity belongs to another execution");
|
||||
const external = envelope.external as { providers?: Record<string, { prerequisites?: Record<string, unknown> }> } | undefined;
|
||||
return { credentialNames: Object.keys(envelope.credentials).sort(), referenceNames: Object.keys(envelope.references).sort(),
|
||||
externalRequirements: Object.entries(external?.providers ?? {}).map(([provider, binding]) => ({ provider, fields: Object.keys(binding.prerequisites ?? {}).sort() })) };
|
||||
return { ...(envelope.oracleExpectation ? { oracleExpectation: envelope.oracleExpectation } : {}), credentialNames: envelope.declaredCredentialNames ?? Object.keys(envelope.credentials).sort(), referenceNames: envelope.declaredReferenceNames ?? Object.keys(envelope.references).sort(),
|
||||
externalRequirements: envelope.declaredExternalRequirements ?? Object.entries(external?.providers ?? {}).map(([provider, binding]) => ({ provider, fields: Object.keys(binding.prerequisites ?? {}).sort() })) };
|
||||
}
|
||||
|
||||
/** Profile/environment credentials remain genuine launch prerequisites; selected
|
||||
* case-only inputs are evaluated within its reserved setup, never batch admission. */
|
||||
export function chatLaunchCredentialNames(execution: MatrixExecution, descriptor?: PrivateInputDescriptor): CredentialName[] {
|
||||
const selected = new Set(descriptor?.requiredCredentials ?? []);
|
||||
const launch = new Set([execution.profile.credential, execution.environment.credential].filter(Boolean));
|
||||
return execution.requiredCredentials.filter(name => !selected.has(name) || launch.has(name));
|
||||
}
|
||||
export function chatPrivateSetupBlockers(inputs: ChatPrivateInputs | undefined, descriptor?: PrivateInputDescriptor): string[] {
|
||||
const requirements = chatPrivateInputRequirements(descriptor); const result = [...inputs?.setupBlockers ?? []];
|
||||
for (const name of requirements.credentialNames) if (!inputs?.credentials[name]?.trim()) result.push(`missing-credential:${name}`);
|
||||
if (requirements.external && !inputs?.configuration("external-provider")) result.push(`unavailable-external-configuration:${requirements.external.provider}`);
|
||||
return [...new Set(result)].sort();
|
||||
}
|
||||
|
||||
export function verifyRetainedChatOracleIdentity(identity: ReturnType<typeof chatPrivateInputNameIdentity> | undefined, descriptor: PrivateInputDescriptor, env: NodeJS.ProcessEnv = process.env) {
|
||||
const requirement = descriptor.externalInput; if (!requirement || !oracleSemanticFields(requirement.provider, requirement.fields).length) return;
|
||||
const filename = env[externalConfigEnv]; if (!filename) throw new Error("Retained private oracle expectations unavailable; evidence cannot qualify");
|
||||
const config = readPrivateJson(filename) as { schemaVersion?: number; providers?: Record<string, { prerequisites?: Record<string, string> }> };
|
||||
if (config.schemaVersion !== 1) throw new Error("Retained private oracle configuration unavailable");
|
||||
verifyRetainedPrivateOracle(identity?.oracleExpectation, requirement.provider, requirement.fields, config.providers?.[requirement.provider]?.prerequisites ?? {}, env);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { mkdtempSync, writeFileSync, rmSync, readFileSync } from "node:fs";
|
||||
import { randomBytes, createHash } from "node:crypto";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { CHAT_ORACLE_KEY_ENV, privateOracleIdentity, verifyRetainedPrivateOracle } from "./chat-private-oracle.js";
|
||||
import { stageChatPrivateInputs, chatPrivateInputNameIdentity, verifyRetainedChatOracleIdentity, scrubChatPrivateEnvironment, CHAT_PRIVATE_INPUTS_ENV } from "./chat-private-inputs.js";
|
||||
import type { MatrixExecution } from "./types.js";
|
||||
const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
|
||||
function fixture() { const root = mkdtempSync(path.join(tmpdir(), "chat-oracle-")); roots.push(root); const key = path.join(root, "campaign-key"); writeFileSync(key, randomBytes(32), { mode: 0o600 }); return { root, key, env: { [CHAT_ORACLE_KEY_ENV]: key } }; }
|
||||
const fields = ["recentMarker", "olderMarker", "recentFactJson", "olderFactJson", "apiVersion"];
|
||||
const values = { recentMarker: "private-recent", olderMarker: "private-old", recentFactJson: '{"subject":"Acorn","value":"private-fact","aliases":["private-alias"]}', olderFactJson: '{"subject":"Old","value":"old-fact"}', apiVersion: "2025-09-03" };
|
||||
it("commits every audited actual semantic expectation while excluding credentials/incidental IDs", () => {
|
||||
const f = fixture(); const original = privateOracleIdentity("notion", fields, values, f.env)!;
|
||||
for (const field of fields) expect(privateOracleIdentity("notion", fields, { ...values, [field]: `${values[field as keyof typeof values]}-changed` }, f.env)?.commitment).not.toBe(original.commitment);
|
||||
expect(privateOracleIdentity("notion", fields, { ...values, workspaceId: "different-disposable-id", tokenEnv: "different-secret-ref" }, f.env)).toEqual(original);
|
||||
const publicValue = JSON.stringify(original); for (const value of Object.values(values)) expect(publicValue).not.toContain(value);
|
||||
expect(publicValue).not.toContain(createHash("sha256").update(values.recentFactJson).digest("hex"));
|
||||
expect(() => verifyRetainedPrivateOracle(original, "notion", fields, values, f.env)).not.toThrow();
|
||||
});
|
||||
it("refuses lost, replaced or absent campaign keys and changed retained expectations without creating a replacement", () => {
|
||||
const f = fixture(); const original = privateOracleIdentity("notion", fields, values, f.env)!;
|
||||
expect(() => privateOracleIdentity("notion", fields, values, {})).toThrow("key unavailable");
|
||||
expect(() => verifyRetainedPrivateOracle(original, "notion", fields, { ...values, recentMarker: "changed" }, f.env)).toThrow("mismatch");
|
||||
writeFileSync(f.key, randomBytes(32)); expect(() => verifyRetainedPrivateOracle(original, "notion", fields, values, f.env)).toThrow("mismatch");
|
||||
rmSync(f.key); expect(() => verifyRetainedPrivateOracle(original, "notion", fields, values, f.env)).toThrow();
|
||||
});
|
||||
it("retains only opaque names/commitments across envelope cleanup and requalifies with actual host expectations/key", () => {
|
||||
const f = fixture(); const config = path.join(f.root, "external.json"); const keyBytes = readFileSync(f.key).toString("hex");
|
||||
writeFileSync(config, JSON.stringify({ schemaVersion: 1, providers: { notion: { disposable: true, resourceIds: ["disposable"], credentialEnv: ["PAPERCLIP_CHAT_EVAL_NOTION_AUTH"], prerequisites: values } } }), { mode: 0o600 });
|
||||
const descriptor = { externalInput: { provider: "notion" as const, fields } }; const execution = { id: "selected" } as MatrixExecution;
|
||||
const env = { ...f.env, PAPERCLIP_CHAT_CATALOG_EXTERNAL_CONFIG: config, PAPERCLIP_CHAT_EVAL_NOTION_AUTH: "never-committed-credential" };
|
||||
const staged = stageChatPrivateInputs({ execution, descriptor, privateDir: f.root, secrets: [], env }); const retained = chatPrivateInputNameIdentity("selected", { [CHAT_PRIVATE_INPUTS_ENV]: staged.filename, PAPERCLIP_RUNNER_E2E_TEMP_ROOT: f.root });
|
||||
rmSync(staged.filename); expect(() => verifyRetainedChatOracleIdentity(retained, descriptor, env)).not.toThrow();
|
||||
expect(JSON.stringify(retained)).not.toContain(keyBytes); expect(JSON.stringify(retained)).not.toContain("never-committed-credential");
|
||||
const publicEnv = scrubChatPrivateEnvironment({ ...env }, []); expect(publicEnv[CHAT_ORACLE_KEY_ENV]).toBeUndefined();
|
||||
rmSync(f.key); expect(() => verifyRetainedChatOracleIdentity(retained, descriptor, env)).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
import { lstatSync, readFileSync } from "node:fs";
|
||||
export const CHAT_ORACLE_KEY_ENV = "PAPERCLIP_CHAT_ORACLE_COMMITMENT_KEY";
|
||||
/** Audited with external owner: these actual private values select expected
|
||||
* Notion answers/provider contract. IDs, origins and credential references are
|
||||
* provenance, never included. New semantic consumers require an explicit edit. */
|
||||
export const privateOracleSemanticFields = { notion: ["recentMarker", "olderMarker", "recentFactJson", "olderFactJson", "apiVersion"] } as const;
|
||||
export interface PrivateOracleIdentity { provider: string; fields: string[]; keyIdentity: string; commitment: string }
|
||||
function readKey(env: NodeJS.ProcessEnv): Buffer {
|
||||
const filename = env[CHAT_ORACLE_KEY_ENV]; if (!filename) throw new Error("Private oracle campaign commitment key unavailable");
|
||||
let info; try { info = lstatSync(filename); } catch { throw new Error("Private oracle campaign commitment key unavailable"); }
|
||||
if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o777) !== 0o600 || typeof process.getuid === "function" && info.uid !== process.getuid()) throw new Error("Private oracle key must be an existing owned0600 regular file");
|
||||
let bytes: Buffer; try { bytes = readFileSync(filename); } catch { throw new Error("Private oracle campaign commitment key unavailable"); } if (bytes.length !== 32) throw new Error("Private oracle key must contain exactly32 existing random bytes"); return bytes;
|
||||
}
|
||||
export function oracleSemanticFields(provider: string, declaredFields: readonly string[]): string[] {
|
||||
const audited = privateOracleSemanticFields[provider as keyof typeof privateOracleSemanticFields] as readonly string[] | undefined;
|
||||
return declaredFields.filter(field => audited?.includes(field)).sort();
|
||||
}
|
||||
export function privateOracleIdentity(provider: string, declaredFields: readonly string[], prerequisites: Record<string, string>, env: NodeJS.ProcessEnv): PrivateOracleIdentity | undefined {
|
||||
const fields = oracleSemanticFields(provider, declaredFields); if (!fields.length) return;
|
||||
if (fields.some(field => typeof prerequisites[field] !== "string" || !prerequisites[field]?.trim())) throw new Error("Selected private oracle expectations unavailable");
|
||||
const key = readKey(env); const mac = (value: string) => createHmac("sha256", key).update(value).digest("hex");
|
||||
return { provider, fields, keyIdentity: mac("paperclip.chat-catalog.oracle-key.v1"),
|
||||
commitment: mac(JSON.stringify({ schema: "paperclip.chat-catalog.oracle-expectations.v1", provider, fields: fields.map(field => [field, prerequisites[field]]) })) };
|
||||
}
|
||||
/** Host reconciliation must re-read the existing campaign key and actual
|
||||
* private expectations. A lost/replaced key or changed oracle input cannot
|
||||
* silently authenticate a retained old observation. No key is ever generated. */
|
||||
export function verifyRetainedPrivateOracle(expected: PrivateOracleIdentity | undefined, provider: string, declaredFields: readonly string[], prerequisites: Record<string, string>, env: NodeJS.ProcessEnv) {
|
||||
const current = privateOracleIdentity(provider, declaredFields, prerequisites, env);
|
||||
if (!current && !expected) return;
|
||||
if (!current || !expected || current.provider !== expected.provider || JSON.stringify(current.fields) !== JSON.stringify(expected.fields)
|
||||
|| !/^[a-f0-9]{64}$/.test(expected.keyIdentity) || !/^[a-f0-9]{64}$/.test(expected.commitment)
|
||||
|| !timingSafeEqual(Buffer.from(current.keyIdentity, "hex"), Buffer.from(expected.keyIdentity, "hex")) || !timingSafeEqual(Buffer.from(current.commitment, "hex"), Buffer.from(expected.commitment, "hex"))) throw new Error("Retained private oracle commitment/key mismatch; evidence is ineligible until provenance is resolved");
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { CHAT_ORACLE_KEY_ENV } from "./chat-private-oracle.js";
|
||||
import { stagePublishedChatInstall, ChatInstalledCleanupError } from "./chat-installed-lane.js";
|
||||
import { stageChatPrivateInputs, CHAT_PRIVATE_INPUTS_ENV } from "./chat-private-inputs.js";
|
||||
import { stageChatPrivateInputs, chatLaunchCredentialNames, CHAT_PRIVATE_INPUTS_ENV } from "./chat-private-inputs.js";
|
||||
import { createPrivateDiagnosticStream, diagnosticSecrets, PRIVATE_DIAGNOSTICS_ENV, readPrivateDiagnosticSecrets, stagePrivateDiagnostics } from "./private-diagnostics.js";
|
||||
import { sanitizePrivateReporterArtifacts } from "./private-reporter-artifacts.js";
|
||||
import { findChatCatalogCase } from "./chat-catalog-registry.js";
|
||||
@@ -497,6 +498,7 @@ async function runAttempt(input: {
|
||||
let installedCli = await verifyInstalledCli(process.env, executions);
|
||||
const selectedDescriptor = execution.suite.id === "chat-features" ? findChatCatalogCase(execution.task.id) : undefined;
|
||||
let sourceEnvironment = { ...process.env };
|
||||
delete sourceEnvironment[CHAT_ORACLE_KEY_ENV];
|
||||
const installedPlugin = await verifyInstalledDaytonaPlugin(process.env, executions);
|
||||
const startedAtMs = Date.now();
|
||||
const sharedMemoryBaseline = snapshotDarwinSharedMemory();
|
||||
@@ -1145,7 +1147,7 @@ async function main() {
|
||||
assertRemoteNativeEvidencePrerequisites(executions, process.env);
|
||||
const missingCredentials = process.env.PAPERCLIP_E2E_OPERATIONS_MANIFEST ? [] : [
|
||||
...new Set(
|
||||
executions.flatMap((execution) => execution.requiredCredentials),
|
||||
executions.flatMap((execution) => chatLaunchCredentialNames(execution, execution.suite.id === "chat-features" ? findChatCatalogCase(execution.task.id) : undefined)),
|
||||
),
|
||||
].filter((name) => !process.env[name]?.trim());
|
||||
if (missingCredentials.length > 0) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { readChatPrivateInputs } from "./chat-private-inputs.js";
|
||||
import { readChatPrivateInputs, chatPrivateSetupBlockers, chatPrivateInputRequirements } from "./chat-private-inputs.js";
|
||||
import { trackedPrivateSecrets } from "./private-diagnostics.js";
|
||||
import { findChatCatalogCase } from "./chat-catalog-registry.js";
|
||||
import { runChatBoundaryFlow } from "./chat-boundary-flow.js";
|
||||
@@ -928,6 +928,15 @@ for (const execution of executions) {
|
||||
trace?.phase("setup");
|
||||
await saveTrace();
|
||||
const catalogDescriptor = execution.suite.id === "chat-features" ? findChatCatalogCase(execution.task.id) : undefined;
|
||||
if (catalogDescriptor) {
|
||||
const blockers = chatPrivateSetupBlockers(privateInputs, catalogDescriptor);
|
||||
if (blockers.length) {
|
||||
failureClassOverride = "permanent_infrastructure";
|
||||
await writeSanitizedJson(snapshotsDir, "chat-catalog-input-prerequisite.json", { scenarioId: execution.task.id, phase: "reserved-setup", querySent: false, modelAdmissions: 0,
|
||||
requirements: chatPrivateInputRequirements(catalogDescriptor), blockers, inputCleanup: "owned by launcher finally" }, secrets);
|
||||
throw new Error(`Selected case setup prerequisite unavailable: ${blockers.join(", ")}`);
|
||||
}
|
||||
}
|
||||
if (catalogDescriptor?.journeyKind === "browser-boundary") {
|
||||
const scenario = chatCatalogScenarios.find(row => row.id === execution.task.id);
|
||||
if (!scenario || !catalogDescriptor.boundaryTarget) throw new Error("Boundary scenario or target identity missing");
|
||||
|
||||
Reference in new issue
Block a user