Give managed agents persistent cryptographic identities (#15352)

Give agents persistent Ed25519 identities encrypted with the existing instance master key. Create keys transactionally for new agents and lazily before supported managed runs, expose public identities in the API and agent UI, and protect private material during runtime delivery and output persistence.

Preserve identities in recovery backups while giving imported and development-cloned agents fresh keys.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-10-06 13:57:03 -05:00
1 parent d9f600043f
commit a590ab769d
73 files changed
+2014 -63

No files matched your search

@@ -357,6 +357,12 @@ describe("agent cross-tenant route authorization", () => {
isInstanceAdmin: false,
};
const deniedCases = [
{
label: "public cryptographic identity",
request: (app: express.Express) =>
requestApp(app, (baseUrl) => request(baseUrl).get(`/api/agents/${agentId}/identity`)),
untouched: [],
},
{
label: "pause",
request: (app: express.Express) =>
@@ -1,7 +1,7 @@
import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { eq } from "drizzle-orm";
import { agents, companies, companyMemberships, createDb, principalPermissionGrants } from "@paperclipai/db";
import { activityLog, agents, companies, companyMemberships, createDb, principalPermissionGrants } from "@paperclipai/db";
import { LOW_TRUST_REVIEW_PRESET, type PermissionKey } from "@paperclipai/shared";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { agentService } from "../services/agents.js";
@@ -137,6 +137,7 @@ describeDatabase("new agent configuration defaults", () => {
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId));
await db.delete(companyMemberships).where(eq(companyMemberships.companyId, companyId));
await db.delete(agents).where(eq(agents.companyId, companyId));
await db.delete(activityLog).where(eq(activityLog.companyId, companyId));
await db.delete(companies).where(eq(companies.id, companyId));
});
@@ -178,6 +179,7 @@ describeDatabase("new agent configuration defaults", () => {
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId));
await db.delete(agents).where(eq(agents.companyId, companyId));
await db.delete(activityLog).where(eq(activityLog.companyId, companyId));
await db.delete(companies).where(eq(companies.id, companyId));
});
@@ -207,6 +209,7 @@ describeDatabase("new agent configuration defaults", () => {
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId));
await db.delete(agents).where(eq(agents.companyId, companyId));
await db.delete(activityLog).where(eq(activityLog.companyId, companyId));
await db.delete(companies).where(eq(companies.id, companyId));
});
@@ -235,6 +238,7 @@ describeDatabase("new agent configuration defaults", () => {
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId));
await db.delete(companyMemberships).where(eq(companyMemberships.companyId, companyId));
await db.delete(agents).where(eq(agents.companyId, companyId));
await db.delete(activityLog).where(eq(activityLog.companyId, companyId));
await db.delete(companies).where(eq(companies.id, companyId));
});
});
@@ -0,0 +1,36 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { mkdtemp, readFile, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { createRequire } from "node:module";
import { expect, it, vi } from "vitest";
import { localEncryptedProvider } from "../secrets/local-encrypted-provider.js";
it("atomically publishes one complete master key across competing processes", async () => {
const directory = await mkdtemp(join(tmpdir(), "identity-master-race-"));
const keyFile = join(directory, "master.key");
const providerPath = fileURLToPath(new URL("../secrets/local-encrypted-provider.ts", import.meta.url));
const tsx = createRequire(import.meta.url).resolve("tsx/esm");
try {
const script = `import {localEncryptedProvider as p} from ${JSON.stringify(providerPath)}; console.log(JSON.stringify(await p.createSecret({value:'race-challenge'})));`;
const children = await Promise.all(Array.from({ length: 6 }, () => promisify(execFile)(process.execPath,
["--import", tsx, "--input-type=module", "-e", script], {
env: { ...process.env, PAPERCLIP_SECRETS_MASTER_KEY: "", PAPERCLIP_SECRETS_MASTER_KEY_FILE: keyFile },
})));
expect(Buffer.from(await readFile(keyFile, "utf8"), "base64")).toHaveLength(32);
expect((await stat(keyFile)).mode & 0o777).toBe(0o600);
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "");
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY_FILE", keyFile);
for (const child of children) {
expect(await localEncryptedProvider.resolveVersion(JSON.parse(child.stdout))).toBe("race-challenge");
}
await rm(keyFile);
await expect(localEncryptedProvider.resolveVersion(JSON.parse(children[0].stdout))).rejects.toThrow("master key file is missing");
await expect(stat(keyFile)).rejects.toMatchObject({ code: "ENOENT" });
} finally {
vi.unstubAllEnvs();
await rm(directory, { recursive: true, force: true });
}
}, 30_000);
+256
View File
@@ -0,0 +1,256 @@
import { randomBytes, randomUUID, verify, generateKeyPairSync } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import express from "express";
import request from "supertest";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { eq } from "drizzle-orm";
import { agentIdentityKeys, agents, companies, createDb, closeRegisteredClients, ensurePostgresDatabase, runDatabaseBackup, runDatabaseRestore, type Db } from "@paperclipai/db";
import { resolveWorktreeSeedPlan } from "../../../cli/src/commands/worktree-lib.js";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { agentIdentityService, supportsManagedAgentIdentity } from "../services/agent-identity.js";
import { agentService } from "../services/agents.js";
import { localEncryptedProvider } from "../secrets/local-encrypted-provider.js";
import { execute } from "../adapters/process/execute.js";
import { createAgentIdentityRedactor } from "../services/agent-identity-redaction.js";
import { heartbeatService } from "../services/heartbeat.js";
import { agentRoutes } from "../routes/agents.js";
import { actorMiddleware } from "../middleware/auth.js";
import { errorHandler } from "../middleware/error-handler.js";
import { drainHeartbeatRunsToQuiescence } from "./helpers/drain-heartbeat-runs.js";
describe("agent cryptographic identity", () => {
let db: Db;
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let directory: string;
let companyId: string;
beforeAll(async () => {
directory = await mkdtemp(join(tmpdir(), "paperclip-identity-"));
vi.stubEnv("PAPERCLIP_HOME", directory);
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "");
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY_FILE", join(directory, "master.key"));
database = await startEmbeddedPostgresTestDatabase("paperclip-identity-");
db = createDb(database.connectionString);
companyId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Identity test", issuePrefix: "KEY", defaultResponsibleUserId: "identity-test-owner" });
});
afterAll(async () => {
await database?.cleanup();
vi.unstubAllEnvs();
await rm(directory, { recursive: true, force: true });
});
async function oldAgent() {
const [agent] = await db.insert(agents).values({ companyId, name: randomUUID(), role: "engineer" }).returning();
return agent;
}
it("migration and public reads leave existing agents unprovisioned", async () => {
const agent = await oldAgent();
expect(await agentIdentityService(db).getPublicIdentity(companyId, agent.id)).toBeNull();
expect(await db.select().from(agentIdentityKeys).where(eq(agentIdentityKeys.agentId, agent.id))).toHaveLength(0);
for (const type of ["http", "openclaw_gateway", "hermes_gateway"]) expect(supportsManagedAgentIdentity(type)).toBe(false);
for (const provider of ["claude_managed", "aws_agentcore"]) expect(supportsManagedAgentIdentity("paperclip_runner", { provider })).toBe(false);
expect(supportsManagedAgentIdentity("paperclip_runner", { provider: "codex" }, "claude_managed_agents_api")).toBe(false);
expect(supportsManagedAgentIdentity("paperclip_runner", { provider: "claude_managed" }, "codex_app_server")).toBe(true);
});
it("concurrent first runs converge, restart/model/name changes preserve keys, and ownership is enforced", async () => {
const agent = await oldAgent();
const pairs = await Promise.all(Array.from({ length: 8 }, () =>
agentIdentityService(db).ensureAgentIdentity(companyId, agent.id)));
expect(new Set(pairs.map(pair => pair.privateKeyPem)).size).toBe(1);
await db.update(agents).set({ name: "Renamed", adapterConfig: { model: "another-model" }, status: "paused" }).where(eq(agents.id, agent.id));
const freshDb = createDb(database.connectionString);
expect(await agentIdentityService(freshDb).ensureAgentIdentity(companyId, agent.id)).toEqual(pairs[0]);
expect(await agentIdentityService(db).getPublicIdentity(randomUUID(), agent.id)).toBeNull();
await expect(agentIdentityService(db).ensureAgentIdentity(randomUUID(), agent.id)).rejects.toThrow("Agent not found");
const second = await oldAgent();
expect((await agentIdentityService(db).ensureAgentIdentity(companyId, second.id)).keyId).not.toBe(pairs[0].keyId);
await db.delete(agents).where(eq(agents.id, second.id));
expect(await agentIdentityService(db).getPublicIdentity(companyId, second.id)).toBeNull();
});
it("creates identities in the agent creation transaction and rolls both writes back on failure", async () => {
const created = await agentService(db).create(companyId, { name: "New identity", role: "engineer", status: "pending_approval" });
expect(await agentIdentityService(db).getPublicIdentity(companyId, created.id)).toMatchObject({ algorithm: "Ed25519" });
const id = randomUUID();
await expect(db.transaction(async tx => {
await tx.insert(agents).values({ id, companyId, name: "Rollback", role: "engineer" });
await agentIdentityService(tx as unknown as Db).ensureAgentIdentity(companyId, id);
throw new Error("rollback");
})).rejects.toThrow("rollback");
expect(await db.select().from(agents).where(eq(agents.id, id))).toHaveLength(0);
expect(await agentIdentityService(db).getPublicIdentity(companyId, id)).toBeNull();
const fail = vi.spyOn(localEncryptedProvider, "createSecret").mockRejectedValueOnce(new Error("encryption unavailable"));
await expect(agentService(db).create(companyId, { name: "Must roll back", role: "engineer", status: "pending_approval" })).rejects.toThrow("encryption unavailable");
fail.mockRestore();
expect(await db.select().from(agents).where(eq(agents.name, "Must roll back"))).toHaveLength(0);
});
it("fails closed for wrong master keys, corrupted material and mismatched public keys", async () => {
const agent = await oldAgent();
const identity = await agentIdentityService(db).ensureAgentIdentity(companyId, agent.id);
const [stored] = await db.select().from(agentIdentityKeys).where(eq(agentIdentityKeys.agentId, agent.id));
expect(JSON.stringify(stored)).not.toContain(identity.privateKeyPem.split("\n")[1]);
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", randomBytes(32).toString("base64"));
await expect(agentIdentityService(db).ensureAgentIdentity(companyId, agent.id)).rejects.toThrow("decryption failed");
expect(await agentIdentityService(db).getPublicIdentity(companyId, agent.id)).toMatchObject({ keyId: identity.keyId });
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "");
await db.update(agentIdentityKeys).set({ privateKeyMaterial: { ...stored.privateKeyMaterial, ciphertext: "AAAA" } }).where(eq(agentIdentityKeys.agentId, agent.id));
await expect(agentIdentityService(db).ensureAgentIdentity(companyId, agent.id)).rejects.toThrow();
const other = generateKeyPairSync("ed25519").publicKey.export({ type: "spki", format: "pem" }).toString();
await db.update(agentIdentityKeys).set({ privateKeyMaterial: stored.privateKeyMaterial, publicKeyPem: other }).where(eq(agentIdentityKeys.agentId, agent.id));
await expect(agentIdentityService(db).ensureAgentIdentity(companyId, agent.id)).rejects.toThrow("do not match");
expect((await db.select().from(agentIdentityKeys).where(eq(agentIdentityKeys.agentId, agent.id)))[0].keyId).toBe(identity.keyId);
});
it("a real managed process signs a random challenge before and after reconnect, ignoring hostile env overrides", async () => {
const agent = await oldAgent();
const challenge = randomBytes(32).toString("base64");
let publicPem = "";
for (let restart = 0; restart < 2; restart++) {
const restarted = agentIdentityService(createDb(database.connectionString));
const identity = await restarted.ensureAgentIdentity(companyId, agent.id);
const publicIdentity = await restarted.getPublicIdentity(companyId, agent.id);
if (restart) expect(publicIdentity!.publicKeyPem).toBe(publicPem);
publicPem = publicIdentity!.publicKeyPem;
vi.stubEnv("PAPERCLIP_AGENT_PRIVATE_KEY", "inherited override");
const logs: string[] = [];
const metas: unknown[] = [];
await execute({
runId: randomUUID(), agent, agentIdentity: identity,
config: { command: process.execPath, cwd: directory, args: ["-e", `const {sign}=require('node:crypto'); process.stdout.write(sign(null,Buffer.from(process.env.CHALLENGE,'base64'),process.env.PAPERCLIP_AGENT_PRIVATE_KEY).toString('base64'));`], env: { CHALLENGE: challenge, PAPERCLIP_AGENT_PRIVATE_KEY: "configured override" } },
context: {}, runtime: { sessionId: null, sessionParams: null, taskKey: null },
onLog: async (_stream, chunk) => { logs.push(chunk); }, onMeta: async meta => { metas.push(meta); },
});
expect(verify(null, Buffer.from(challenge, "base64"), publicPem, Buffer.from(logs.join(""), "base64"))).toBe(true);
expect(JSON.stringify(metas)).not.toContain(identity.privateKeyPem.split("\n")[1]);
}
});
it("lazily provisions through managed run preparation, exposes only the public API key, and redacts emitted keys", async () => {
const agent = await oldAgent();
const app = express();
app.use(actorMiddleware(db, { deploymentMode: "local_trusted" }));
app.use("/api", agentRoutes(db));
app.use(errorHandler);
const firstRead = await request(app).get(`/api/agents/${agent.id}/identity`);
expect(firstRead.status).toBe(200);
expect(firstRead.body).toBeNull();
const challenge = randomBytes(32).toString("base64");
await db.update(agents).set({ adapterType: "process", adapterConfig: {
command: process.execPath, cwd: directory,
args: ["-e", `const {sign}=require('node:crypto'); const k=process.env.PAPERCLIP_AGENT_PRIVATE_KEY; console.log('SIGNATURE:'+sign(null,Buffer.from(process.env.CHALLENGE,'base64'),k).toString('base64')); process.stdout.write(k.slice(0,40)); setTimeout(()=>process.stdout.write(k.slice(40)),30);`],
env: { CHALLENGE: challenge, PAPERCLIP_AGENT_PRIVATE_KEY: "ignored override" },
} }).where(eq(agents.id, agent.id));
let previousKeyId = "";
for (let restart = 0; restart < 2; restart++) {
const heartbeat = heartbeatService(createDb(database.connectionString));
try {
const run = await heartbeat.invoke(agent.id, "on_demand", {}, "manual");
expect(run).toBeTruthy();
await drainHeartbeatRunsToQuiescence(db, heartbeat);
const finished = await heartbeat.getRun(run!.id);
expect(finished?.status, JSON.stringify(finished)).toBe("succeeded");
const publicResponse = await request(app).get(`/api/agents/${agent.id}/identity`);
expect(publicResponse.status).toBe(200);
expect(Object.keys(publicResponse.body).sort()).toEqual(["algorithm", "createdAt", "keyId", "publicKeyPem"]);
if (restart) expect(publicResponse.body.keyId).toBe(previousKeyId);
previousKeyId = publicResponse.body.keyId;
const signature = /SIGNATURE:([A-Za-z0-9+/=]+)/.exec(finished!.stdoutExcerpt ?? "")?.[1];
expect(signature).toBeTruthy();
expect(verify(null, Buffer.from(challenge, "base64"), publicResponse.body.publicKeyPem, Buffer.from(signature!, "base64"))).toBe(true);
const privateBody = (await agentIdentityService(db).ensureAgentIdentity(companyId, agent.id)).privateKeyPem.split("\n")[1];
expect(JSON.stringify(finished)).not.toContain(privateBody);
expect(JSON.stringify(await heartbeat.readLog(run!.id))).not.toContain(privateBody);
} finally {
await drainHeartbeatRunsToQuiescence(db, heartbeat);
}
}
}, 60_000);
it("persists ordinary stdout and stderr endings after settling the identity buffer", async () => {
const agent = await oldAgent();
await db.update(agents).set({ adapterType: "process", adapterConfig: {
command: process.execPath, cwd: directory,
args: ["-e", "process.stdout.write('safe-'); process.stderr.write('safeM');"],
} }).where(eq(agents.id, agent.id));
const heartbeat = heartbeatService(db);
try {
const run = await heartbeat.invoke(agent.id, "on_demand", {}, "manual");
await drainHeartbeatRunsToQuiescence(db, heartbeat);
const finished = await heartbeat.getRun(run!.id);
expect(finished?.status).toBe("succeeded");
expect(finished?.stdoutExcerpt).toMatch(/safe-$/);
expect(finished?.stderrExcerpt).toMatch(/safeM$/);
const lines = (await heartbeat.readLog(run!.id)).content.trim().split("\n").map(line => JSON.parse(line));
expect(lines.filter(line => line.stream === "stdout").map(line => line.chunk).join("")).toContain("safe-");
expect(lines.filter(line => line.stream === "stderr").map(line => line.chunk).join("")).toContain("safeM");
} finally {
await drainHeartbeatRunsToQuiescence(db, heartbeat);
}
}, 60_000);
it("disaster recovery retains identity; both development seed modes omit it and mint fresh keys", async () => {
const agent = await oldAgent();
const original = await agentIdentityService(db).ensureAgentIdentity(companyId, agent.id);
for (const mode of ["backup", "minimal", "full"] as const) {
const seed = mode === "backup" ? undefined : resolveWorktreeSeedPlan(mode);
const backup = await runDatabaseBackup({
connectionString: database.connectionString, backupDir: join(directory, mode),
backupEngine: "javascript", retention: { dailyDays: 1, weeklyWeeks: 0, monthlyMonths: 0 },
excludeTables: seed?.excludedTables, nullifyColumns: seed?.nullifyColumns,
});
const target = new URL(database.connectionString);
const admin = new URL(database.connectionString);
admin.pathname = "/postgres";
await ensurePostgresDatabase(admin.toString(), `identity_${mode}`);
target.pathname = `/identity_${mode}`;
await runDatabaseRestore({ connectionString: target.toString(), backupFile: backup.backupFile });
const restored = agentIdentityService(createDb(target.toString()));
if (mode === "backup") expect(await restored.ensureAgentIdentity(companyId, agent.id)).toEqual(original);
else {
expect(await restored.getPublicIdentity(companyId, agent.id)).toBeNull();
expect((await restored.ensureAgentIdentity(companyId, agent.id)).keyId).not.toBe(original.keyId);
}
await closeRegisteredClients(target.toString());
}
}, 60_000);
});
describe("identity output redaction", () => {
const pem = generateKeyPairSync("ed25519").privateKey.export({ format: "pem", type: "pkcs8" }).toString();
it("redacts PEM, JSON-escaped PEM and raw private material", () => {
const redactor = createAgentIdentityRedactor(pem);
for (const text of [pem, JSON.stringify(pem), pem.split("\n")[1]]) {
expect(redactor.redact({ output: text }).output).not.toContain(pem.split("\n")[1]);
}
});
it("settles ordinary endings and interrupted keys on item and turn completion", () => {
const redactor = createAgentIdentityRedactor(pem);
expect(redactor.delta("run:turn:item", { kind: "reasoning", text: "Thinking-" }, "item").text).toBe("Thinking");
const completed = redactor.settleDeltas("run:turn:item", {}, false);
expect(completed).toMatchObject({ outputTails: [{ itemId: "item", payload: { kind: "reasoning", text: "-" } }] });
expect(redactor.settleDeltas("run:turn:", {}, true)).toEqual({});
redactor.delta("run:turn:other", { text: pem.slice(0, 42) }, "other");
expect(redactor.settleDeltas("run:turn:", {}, true)).toMatchObject({ outputTails: [{ payload: { text: "***REDACTED***" } }] });
expect(redactor.delta("run:turn:other", { text: "hello" }).text).toBe("hello");
});
it("redacts every split boundary and interleaved streams, including interrupted prefixes", () => {
for (let split = 1; split < pem.length; split++) {
const redactor = createAgentIdentityRedactor(pem);
let output = redactor.chunk("stdout", pem.slice(0, split));
expect(redactor.chunk("stderr", "ordinary output\n")).toBe("ordinary output\n");
output += redactor.chunk("stdout", pem.slice(split));
output += redactor.finish("stdout");
expect(output).not.toContain(pem.split("\n")[1]);
}
const redactor = createAgentIdentityRedactor(pem);
expect(redactor.chunk("stdout", pem.slice(0, 42))).toBe("");
expect(redactor.finish("stdout")).toBe("***REDACTED***");
});
});
@@ -1008,7 +1008,7 @@ describeEmbeddedPostgres("accepted plan workspace refresh", () => {
expect(adapterInput.context.paperclipTaskMarkdown).not.toContain("Create child issues from the approved plan only");
}, 20_000);
it("preserves accepted-plan continuation resume state when the wake issue owns the in-flight claim", async () => {
it("preserves accepted-plan instructions but replaces a pre-identity session when the wake issue owns the in-flight claim", async () => {
const companyId = randomUUID();
const projectId = randomUUID();
const projectWorkspaceId = randomUUID();
@@ -1138,7 +1138,8 @@ describeEmbeddedPostgres("accepted plan workspace refresh", () => {
runtime: { sessionId: string | null; sessionParams: Record<string, unknown> | null };
context: Record<string, unknown>;
};
expect(adapterInput.runtime.sessionId).toBe("accepted-plan-retry-session");
// The old process predates identity injection and must be replaced.
expect(adapterInput.runtime.sessionId).toBeNull();
expect(adapterInput.context.acceptedPlanWakeRouting).toBeUndefined();
expect(adapterInput.context.paperclipTaskMarkdown).toContain(
"Implement the accepted plan on this issue when the work is small and cohesive.",
+1 -1
View File
@@ -26,7 +26,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec
const cwd = asString(config.cwd, process.cwd());
const envConfig = parseObject(config.env);
const env: Record<string, string> = {
...buildPaperclipEnv(agent),
...buildPaperclipEnv(agent, ctx.agentIdentity),
...buildRuntimeToolsEnv(ctx.runtimeTools),
};
for (const [k, v] of Object.entries(envConfig)) {
+7
View File
@@ -1,4 +1,5 @@
import { aiRoutingHarness } from "@paperclipai/shared";
import { agentIdentityService } from "../services/agent-identity.js";
import { aiConnectionRouterService, poolMemberRuntimeConfig } from "../services/ai-connection-router.js";
import { connectionIntentService } from "../services/connection-intents.js";
import { completeConnectionIntentSchema } from "@paperclipai/shared";
@@ -4386,6 +4387,12 @@ export function agentRoutes(
res.json(rows);
});
router.get("/agents/:id/identity", async (req, res) => {
const agent = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Agent not found");
if (!agent || !(await assertAgentReadAllowed(req, res, agent))) return;
res.json(await agentIdentityService(db).getPublicIdentity(agent.companyId, agent.id));
});
router.get("/agents/:id", async (req, res) => {
const id = req.params.id as string;
const agent = await getAccessibleResource(req, res, svc.getById(id), "Agent not found");
+19
View File
@@ -3456,6 +3456,25 @@ registry.registerPath({
responses: { 200: r.ok(), 401: r.unauthorized, 404: r.notFound },
});
registry.registerPath({
method: "get",
path: "/api/agents/{id}/identity",
tags: ["agents"],
summary: "Get an agent's public cryptographic identity, or null before provisioning",
request: { params: z.object({ id: z.string() }) },
responses: {
200: r.ok(z.object({
algorithm: z.literal("Ed25519"),
keyId: z.string(),
publicKeyPem: z.string(),
createdAt: z.string().datetime(),
}).nullable()),
401: r.unauthorized,
403: r.forbidden,
404: r.notFound,
},
});
registry.registerPath({
method: "patch",
path: "/api/agents/{id}",
+16 -8
View File
@@ -1,5 +1,5 @@
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { chmodSync, existsSync, linkSync, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import path from "node:path";
import { resolveDefaultSecretsKeyFilePath } from "../home-paths.js";
import type {
@@ -45,7 +45,7 @@ function decodeMasterKey(raw: string): Buffer | null {
return null;
}
function loadOrCreateMasterKey(): Buffer {
function loadOrCreateMasterKey(allowCreate = true): Buffer {
const envKeyRaw = process.env.PAPERCLIP_SECRETS_MASTER_KEY;
if (envKeyRaw && envKeyRaw.trim().length > 0) {
const fromEnv = decodeMasterKey(envKeyRaw);
@@ -68,16 +68,24 @@ function loadOrCreateMasterKey(): Buffer {
return decoded;
}
if (!allowCreate) throw new Error(`Secrets master key file is missing: ${keyPath}`);
const dir = path.dirname(keyPath);
mkdirSync(dir, { recursive: true });
const generated = randomBytes(32);
writeFileSync(keyPath, generated.toString("base64"), { encoding: "utf8", mode: 0o600 });
const temporaryPath = `${keyPath}.${process.pid}.${randomBytes(12).toString("hex")}.tmp`;
writeFileSync(temporaryPath, generated.toString("base64"), { encoding: "utf8", mode: 0o600, flag: "wx" });
try {
chmodSync(keyPath, 0o600);
} catch {
// best effort
// A hard link publishes a complete file without overwriting a competitor's
// key. Opening the destination with wx would expose an empty/partial file.
try {
linkSync(temporaryPath, keyPath);
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
}
} finally {
unlinkSync(temporaryPath);
}
return generated;
return loadOrCreateMasterKey(false);
}
function enforceKeyFilePermissionsBestEffort(keyPath: string) {
@@ -272,7 +280,7 @@ export const localEncryptedProvider: SecretProviderModule = {
throw badRequest("local_encrypted does not support external reference secrets");
},
async resolveVersion(input) {
const masterKey = loadOrCreateMasterKey();
const masterKey = loadOrCreateMasterKey(false);
return decryptValue(masterKey, asLocalEncryptedMaterial(input.material));
},
async deleteOrArchive() {
@@ -0,0 +1,95 @@
import { REDACTED_EVENT_VALUE } from "../redaction.js";
import { redactRegisteredSecretValues } from "./run-secret-redaction.js";
/** Keep private material in memory only; do not copy it into run snapshots. */
export function createAgentIdentityRedactor(privateKeyPem?: string) {
const values = privateKeyPem ? [...new Set([
privateKeyPem,
privateKeyPem.trim(),
JSON.stringify(privateKeyPem).slice(1, -1),
...privateKeyPem.split(/\r?\n/).filter(line => line && !line.startsWith("-----")),
])].sort((a, b) => b.length - a.length) : [];
const pending = new Map<string, string>();
const deltaStreams = new Map<string, {
scope: string; itemId?: string; payload: Record<string, unknown>; paths: string[];
}>();
const redactor = {
values,
redact<T>(value: T): T { return redactRegisteredSecretValues(value, values); },
// Hold only a suffix that could begin a secret. Separate buffers prevent
// interleaved stdout/stderr from defeating matching across output chunks.
chunk(stream: string, chunk: string): string {
let text = (pending.get(stream) ?? "") + chunk;
for (const value of values) text = text.split(value).join(REDACTED_EVENT_VALUE);
let held = 0;
for (const value of values) {
for (let size = Math.min(value.length - 1, text.length); size > held; size--) {
if (text.endsWith(value.slice(0, size))) { held = size; break; }
}
}
if (held) pending.set(stream, text.slice(-held));
else pending.delete(stream);
return held ? text.slice(0, -held) : text;
},
// An interrupted partial secret must not be flushed as plaintext.
finish(stream: string): string {
const held = pending.get(stream);
pending.delete(stream);
// Ed25519 PEM/PKCS#8 values begin with fixed structural bytes. Preserve
// ordinary endings such as a dash; longer interrupted fragments stay hidden.
return held ? (held.length < 8 ? held : REDACTED_EVENT_VALUE) : "";
},
/** Delta payloads can repeat output under text and provider-specific fields. */
delta<T>(stream: string, value: T, itemId?: string): T {
const scope = stream;
const paths: string[] = [];
const payload = value as Record<string, unknown>;
// Durable transports can share one envelope item ID across provider items.
stream = JSON.stringify([stream, payload.itemId, payload.providerItemId, payload.channel, payload.stream]);
const visit = (entry: unknown, path: string, field: string): unknown => {
if (typeof entry === "string") {
if (!/^(text|delta|output|patch)$/.test(field)) return redactor.redact(entry);
const key = `${stream}:${path}`;
const output = redactor.chunk(key, entry);
if (pending.has(key)) paths.push(key);
return output;
}
if (Array.isArray(entry)) return entry.map((child, index) => visit(child, `${path}.${index}`, field));
if (entry && typeof entry === "object") return Object.fromEntries(
Object.entries(entry).map(([key, child]) => [key, visit(child, `${path}.${key}`, key)]),
);
return entry;
};
const result = visit(value, "", "") as T;
for (const previous of deltaStreams.get(stream)?.paths ?? []) {
if (pending.has(previous) && !paths.includes(previous)) paths.push(previous);
}
if (paths.length) deltaStreams.set(stream, { scope, itemId, paths,
payload: Object.fromEntries(["itemId", "providerItemId", "kind", "channel", "stream"]
.filter(key => typeof payload[key] === "string").map(key => [key, redactor.redact(payload[key])])),
});
else deltaStreams.delete(stream);
return result;
},
/** Settle output in the terminal event, preserving its source receipt identity. */
settleDeltas(scope: string, payload: Record<string, unknown>, wholeTurn: boolean) {
const tails: Array<{ itemId?: string; payload: Record<string, unknown> }> = [];
for (const [stream, descriptor] of deltaStreams) {
if (wholeTurn ? !descriptor.scope.startsWith(scope) : descriptor.scope !== scope) continue;
if (!wholeTurn && payload.itemId && descriptor.payload.itemId && payload.itemId !== descriptor.payload.itemId) continue;
const primary = descriptor.paths.find(path => path === `${stream}:.text`) ?? descriptor.paths[0];
let text = "";
for (const path of descriptor.paths) {
const tail = redactor.finish(path);
if (path === primary) text = tail;
}
deltaStreams.delete(stream);
if (text) tails.push({ itemId: descriptor.itemId, payload: { ...descriptor.payload, text } });
}
return tails.length ? { ...payload, outputTails: [
...(Array.isArray(payload.outputTails) ? payload.outputTails : []), ...tails,
] } : payload;
},
};
return redactor;
}
+88
View File
@@ -0,0 +1,88 @@
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { agentIdentityKeys, agents, type Db } from "@paperclipai/db";
import type { AgentPublicIdentity } from "@paperclipai/shared";
import { notFound } from "../errors.js";
import { localEncryptedProvider } from "../secrets/local-encrypted-provider.js";
import { persistActivity } from "./activity-log.js";
const publicColumns = {
algorithm: agentIdentityKeys.algorithm,
keyId: agentIdentityKeys.keyId,
publicKeyPem: agentIdentityKeys.publicKeyPem,
createdAt: agentIdentityKeys.createdAt,
};
export function agentIdentityService(db: Db) {
const ownership = (companyId: string, agentId: string) => and(
eq(agentIdentityKeys.companyId, companyId), eq(agentIdentityKeys.agentId, agentId),
);
return {
// Reading an identity must never provision it or decrypt private material.
async getPublicIdentity(companyId: string, agentId: string): Promise<AgentPublicIdentity | null> {
const [row] = await db.select(publicColumns).from(agentIdentityKeys).where(ownership(companyId, agentId));
return row ? { ...row, createdAt: row.createdAt.toISOString() } : null;
},
async ensureAgentIdentity(companyId: string, agentId: string) {
return db.transaction(async (tx) => {
// Lock the parent even when there is no identity row yet. This also
// serializes deletion and works inside the agent-creation transaction.
const [owner] = await tx.select({ id: agents.id }).from(agents)
.where(and(eq(agents.companyId, companyId), eq(agents.id, agentId))).for("update");
if (!owner) throw notFound("Agent not found");
let [row] = await tx.select().from(agentIdentityKeys).where(ownership(companyId, agentId));
if (!row) {
const keys = generateKeyPairSync("ed25519");
const publicKeyPem = keys.publicKey.export({ type: "spki", format: "pem" }).toString();
const keyId = fingerprint(keys.publicKey.export({ type: "spki", format: "der" }));
const privateKeyPem = keys.privateKey.export({ type: "pkcs8", format: "pem" }).toString();
const encrypted = await localEncryptedProvider.createSecret({ value: privateKeyPem });
[row] = await tx.insert(agentIdentityKeys).values({
companyId, agentId, algorithm: "Ed25519", keyId, publicKeyPem,
privateKeyMaterial: encrypted.material,
}).returning();
await persistActivity(tx as unknown as Db, {
companyId, actorType: "system", actorId: "system",
action: "agent.identity.created", entityType: "agent", entityId: agentId,
details: { algorithm: "Ed25519", keyId },
});
}
const privateKeyPem = await localEncryptedProvider.resolveVersion({
material: row.privateKeyMaterial, externalRef: null,
});
// Fail closed on corruption or a wrong master key; never replace a key.
const privateKey = createPrivateKey(privateKeyPem);
const derived = createPublicKey(privateKey).export({ type: "spki", format: "der" });
const stored = createPublicKey(row.publicKeyPem).export({ type: "spki", format: "der" });
if (row.algorithm !== "Ed25519" || privateKey.asymmetricKeyType !== "ed25519" ||
!derived.equals(stored) || fingerprint(stored) !== row.keyId) {
throw new Error("Agent identity public and private keys do not match");
}
return { keyId: row.keyId, publicKeyPem: row.publicKeyPem, privateKeyPem };
});
},
};
}
function fingerprint(spki: Buffer): string {
return `sha256:${createHash("sha256").update(spki).digest("base64url")}`;
}
export function supportsManagedAgentIdentity(
adapterType: string,
config?: { provider?: unknown },
persistedDriver?: string | null,
): boolean {
if (adapterType === "paperclip_runner") {
// API-hosted providers have no process environment under our control.
return persistedDriver
? ["codex", "codex_app_server", "opencode_server", "acpx_runtime"].includes(persistedDriver)
: [undefined, "codex", "opencode", "acpx"].includes(config?.provider as string | undefined);
}
return new Set([
"process", "claude_local", "codex_local", "cursor_cloud",
"gemini_local", "grok_local", "hermes_local", "kimi_local", "opencode_local", "pi_local", "cursor",
]).has(adapterType);
}
+3
View File
@@ -58,6 +58,8 @@ import {
} from "./built-in-agent-metadata.js";
import { issueThreadInteractionService } from "./issue-thread-interactions.js";
import { agentIdentityService } from "./agent-identity.js";
function hashToken(token: string) {
return createHash("sha256").update(token).digest("hex");
}
@@ -945,6 +947,7 @@ export function agentService(db: Db) {
})
.returning()
.then((rows) => rows[0]);
await agentIdentityService(txDb).ensureAgentIdentity(companyId, created.id);
// New standard agents receive the standard direct grants at activation.
// Low-trust and bundled agents keep their explicit, narrower grants.
if (created.status !== "pending_approval" && !permissionsImplyLowTrust(normalizedPermissions) &&
+36 -8
View File
@@ -1,3 +1,6 @@
import { createAgentIdentityRedactor } from "./agent-identity-redaction.js";
import { agentIdentityService, supportsManagedAgentIdentity } from "./agent-identity.js";
import { buildAgentIdentityEnv } from "@paperclipai/adapter-utils/server-utils";
import { retryIdempotentDatabaseOperation } from "../database-retry.js";
import { prepareConnectionInstructionDelivery } from "./connection-instructions.js";
import { resolveAssignedConnectionInstructionsForRun } from "./native-runtime/assigned-mcp-tools.js";
@@ -1487,6 +1490,7 @@ const LOW_TRUST_SENSITIVE_ENV_KEY_RE =
// 3. Any other PAPERCLIP_*-named binding is user data and flows through to
// the run env like any non-prefixed binding.
const FORBIDDEN_ENV_BINDING_KEYS = new Set([
"PAPERCLIP_AGENT_KEY_ID", "PAPERCLIP_AGENT_PUBLIC_KEY", "PAPERCLIP_AGENT_PRIVATE_KEY",
"PAPERCLIP_RUNNER_NETWORK_ACCESS",
"PAPERCLIP_RUNNER_NETWORK_ROOTS",
"PAPERCLIP_API_KEY",
@@ -1514,7 +1518,7 @@ function stripForbiddenEnvBindings(
const filtered = Object.fromEntries(
Object.entries(record).filter(
([key]) =>
!FORBIDDEN_ENV_BINDING_KEYS.has(key) &&
!FORBIDDEN_ENV_BINDING_KEYS.has(key.toUpperCase()) &&
!(managedGitHubCredentials && MANAGED_GITHUB_TOKEN_KEYS.has(key)),
),
);
@@ -6579,6 +6583,7 @@ function buildSessionConfigCategoryValues(input: {
secretManifest: readonly EffectiveRunConfigSecretManifestEntry[];
runtimeSkills: unknown;
agentConfigRevision: unknown;
agentIdentityKeyId?: string;
}) {
const sanitizedSecretManifest = sanitizeSecretManifestForConfigFingerprint(
input.secretManifest,
@@ -6600,6 +6605,7 @@ function buildSessionConfigCategoryValues(input: {
return {
adapter: {
adapterType: input.adapterType,
...(input.agentIdentityKeyId ? { agentIdentityKeyId: input.agentIdentityKeyId } : {}),
agentConfigRevision: input.agentConfigRevision,
},
adapterConfig: input.effectiveAdapterConfig,
@@ -6632,6 +6638,7 @@ export async function buildEffectiveRunSessionConfigMetadata(input: {
secretManifest?: readonly EffectiveRunConfigSecretManifestEntry[];
runtimeSkills: unknown;
agentConfigRevision?: unknown;
agentIdentityKeyId?: string;
}): Promise<EffectiveRunSessionConfigMetadata> {
const secretManifest = input.secretManifest ?? [];
const instructions = await resolveInstructionsConfigFingerprintMetadata(
@@ -6651,6 +6658,7 @@ export async function buildEffectiveRunSessionConfigMetadata(input: {
secretManifest,
runtimeSkills: input.runtimeSkills,
agentConfigRevision: input.agentConfigRevision ?? null,
agentIdentityKeyId: input.agentIdentityKeyId,
});
const fingerprints = createEffectiveRunConfigFingerprints({
session: categoryValues,
@@ -20532,6 +20540,7 @@ export function heartbeatService(
> | null = null;
let providerTraceFinalized = false;
let readFailureReportSecrets: () => string[] = () => [];
let identityRedactor = createAgentIdentityRedactor();
try {
let agent = await getAgent(run.agentId);
@@ -21870,9 +21879,15 @@ export function heartbeatService(
resolve: () => resolveAssignedConnectionInstructionsForRun(db, { companyId: agent.companyId, agentId: agent.id, runId: run.id }),
context, config: connectorDelivery.config, native: agent.adapterType === "paperclip_runner",
});
const agentIdentity = supportsManagedAgentIdentity(agent.adapterType, agent.adapterConfig, run.runtimeMode === "native" ? run.driverKind : undefined)
? await agentIdentityService(db).ensureAgentIdentity(agent.companyId, agent.id)
: undefined;
identityRedactor = createAgentIdentityRedactor(agentIdentity?.privateKeyPem);
if (agentIdentity) secretKeys.add("PAPERCLIP_AGENT_PRIVATE_KEY");
const resolvedFailureSecrets = readFailureReportSecrets();
readFailureReportSecrets = () => [
...resolvedFailureSecrets,
...identityRedactor.values,
...collectRunFailureSecretValues(runtimeConfig.env, secretKeys),
];
const latestAgentConfigRevision = await getLatestAgentConfigRevision(
@@ -21880,6 +21895,7 @@ export function heartbeatService(
agent.id,
);
const sessionConfigMetadataInput = {
agentIdentityKeyId: agentIdentity?.keyId,
adapterType: agent.adapterType,
effectiveAdapterConfig: runtimeConfig,
managedAiHome: managedAiRuntime?.home,
@@ -21978,7 +21994,7 @@ export function heartbeatService(
compatibleConfigMetadata,
wakeResetReason: wakeSessionResetReason,
preserveLegacySessionWithoutConfigMetadata:
acceptedPlanContinuationWake && !acceptedPlanWakeRoutingDecision,
acceptedPlanContinuationWake && !acceptedPlanWakeRoutingDecision && !agentIdentity,
});
const resetTaskSession =
shouldResetTaskSessionForWake(context) || sessionConfigFreshness.reset;
@@ -23430,7 +23446,7 @@ export function heartbeatService(
const currentUserRedactionOptions =
await getCurrentUserRedactionOptions();
const onLog = async (stream: "stdout" | "stderr", chunk: string) => {
const appendIdentityRedactedLog = async (stream: "stdout" | "stderr", chunk: string) => {
const sanitizedChunk = compactRunLogChunk(
redactCurrentUserText(chunk, currentUserRedactionOptions),
);
@@ -23505,6 +23521,8 @@ export function heartbeatService(
},
});
};
const onLog = (stream: "stdout" | "stderr", chunk: string) =>
appendIdentityRedactedLog(stream, identityRedactor.chunk(stream, chunk));
if (runScopedMentionedSkillKeys.length > 0) {
await onLog(
"stdout",
@@ -23593,6 +23611,7 @@ export function heartbeatService(
}
}
const onAdapterMeta = async (meta: AdapterInvocationMeta) => {
meta = identityRedactor.redact(meta);
if (meta.env && secretKeys.size > 0) {
for (const key of secretKeys) {
if (key in meta.env) meta.env[key] = "***REDACTED***";
@@ -23608,6 +23627,7 @@ export function heartbeatService(
};
const onAdapterEvent = async (event: AdapterRuntimeEvent) => {
event = identityRedactor.redact(event);
const eventType = event.eventType.trim();
if (!eventType) return;
await appendRunEvent(currentRun, {
@@ -24176,6 +24196,7 @@ export function heartbeatService(
getNativeFreshSessionHandoff = nativeReviewRequest ? undefined : getFreshSessionHandoff;
const buildExecution = ({ normalizedSessionId, resumedSession }: { normalizedSessionId: string; resumedSession: boolean }) =>
buildNativeExecutionInput({
agentKeyId: agentIdentity?.keyId,
companyId: agent.companyId,
runId: run.id,
issue: nativeReviewRequest ? { ...issueRef, title: `Review: ${issueRef.title}`, description: nativeReviewRequest } : issueRef,
@@ -24910,6 +24931,7 @@ export function heartbeatService(
process.env,
executionWorkspace.cwd,
),
...buildAgentIdentityEnv(agentIdentity),
...(instructionCopy && isAgentDirectoryCopy(instructionCopy) ? { AGENT_HOME: instructionCopy.executionRoot } : {}),
...(nativeMcpServer
? {
@@ -25066,6 +25088,7 @@ export function heartbeatService(
legacyAdapterEntered = true;
return withAdapterExecutionPhase(executionPhaseContext, "adapter_execution", () => adapter.execute({
getFreshSessionHandoff,
agentIdentity,
runId: run.id,
agent,
runtime: runtimeForAdapter,
@@ -25146,6 +25169,11 @@ export function heartbeatService(
if (!guardedDispatch.dispatched) return;
adapterResult = await guardedDispatch.resultPromise;
}
adapterResult = identityRedactor.redact(adapterResult);
for (const stream of ["stdout", "stderr"] as const) {
const tail = identityRedactor.finish(stream);
if (tail) await appendIdentityRedactedLog(stream, tail);
}
if (instructionSave) adapterResult.resultJson = { ...adapterResult.resultJson, instructionSave };
adapterResult = applyWorkspaceRestoreFailure(adapterResult);
// A returned result can include a failed restore. Keep the workspace
@@ -26224,7 +26252,7 @@ export function heartbeatService(
// child. Let the cancellation write settle before attempting failure.
await processRunCancellationSettlements.get(run.id)?.settled;
const message = redactCurrentUserText(
err instanceof Error ? err.message : "Unknown adapter failure",
identityRedactor.redact(err instanceof Error ? err.message : "Unknown adapter failure"),
await getCurrentUserRedactionOptions(),
);
const workspaceValidationFailure = isWorkspaceValidationFailure(err)
@@ -26267,7 +26295,7 @@ export function heartbeatService(
recordedResponsibleUserDenialCode ??
nativeTerminalFailureCode ??
"adapter_failed";
logger.error({ err, runId }, "heartbeat execution failed");
logger.error({ err: identityRedactor.redact({ message: err instanceof Error ? err.message : String(err), stack: err instanceof Error ? err.stack : undefined }), runId }, "heartbeat execution failed");
let logSummary: {
bytes: number | null;
@@ -26481,9 +26509,9 @@ export function heartbeatService(
// Setup code before adapter.execute threw (e.g. ensureRuntimeState, resolveWorkspaceForRun).
// The inner catch did not fire, so we must record the failure here.
const message = redactCurrentUserText(
outerErr instanceof Error
identityRedactor.redact(outerErr instanceof Error
? outerErr.message
: "Unknown setup failure",
: "Unknown setup failure"),
await getCurrentUserRedactionOptions(),
);
// A missing secret/env binding is a known pre-dispatch configuration gap,
@@ -26527,7 +26555,7 @@ export function heartbeatService(
nonRetryablePreflightCode ??
"setup_failed";
logger.error(
{ err: outerErr, runId },
{ err: identityRedactor.redact({ message: outerErr instanceof Error ? outerErr.message : String(outerErr), stack: outerErr instanceof Error ? outerErr.stack : undefined }), runId },
"heartbeat execution setup failed",
);
const setupFailureAgent = await getAgent(run.agentId).catch(() => null);
@@ -57,6 +57,7 @@ export function buildNativeExecutionInput(input: {
previousTurn?: { runId: string; task: { title: string; description: string | null } } | null;
conversationMode?: boolean;
agentId: string;
agentKeyId?: string;
workspace: {
id: string;
cwd: string;
@@ -207,6 +208,7 @@ export function buildNativeExecutionInput(input: {
runId: input.runId,
issueId: input.issue.id,
agentId: input.agentId,
...(input.agentKeyId ? { agentKeyId: input.agentKeyId } : {}),
executionWorkspaceId: input.workspace.id,
},
task: {
@@ -18,6 +18,7 @@ import {
} from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { tmpdir } from "node:os";
import { inspect } from "node:util";
import { join } from "node:path";
import {
heartbeatRuns,
@@ -39,7 +40,7 @@ import {
type NativeExecutionInput,
type PrpEvent,
} from "@paperclipai/paperclip-runner";
import { createHash } from "node:crypto";
import { createHash, generateKeyPairSync } from "node:crypto";
import { DatabaseSync } from "node:sqlite";
import { nativeSha256 } from "./canonical.js";
import * as noLaunchProofModule from "./native-maintenance-no-launch.js";
@@ -6271,6 +6272,23 @@ describe("native warm session supervision", () => {
return { base, next, run };
}
it("replaces an older warm process before the first turn with cryptographic identity", async () => {
const { base } = fixture("identity-key-upgrade");
const next = { ...base, binding: { ...base.binding, runId: "identity-key-next" } };
const close = vi.fn(async () => undefined);
state.execute.mockReset().mockImplementationOnce(async options => {
options.onSession?.({ close }); return result;
}).mockImplementationOnce(async options => {
expect(close).toHaveBeenCalledWith({ reason: "warm native session configuration changed" });
expect(options.existingSession).toBeUndefined();
return result;
});
await executePaperclipNativeSession({ db: leaseDb(base), execution: base, runnerInstanceId: "runner" });
await executePaperclipNativeSession({ db: leaseDb(next), execution: next, runnerInstanceId: "runner",
runnerEnvironment: { PAPERCLIP_AGENT_KEY_ID: "sha256:identity-key" } });
expect(state.execute).toHaveBeenCalledTimes(2);
});
it("awaits prior idle ownership retirement before launching the accepted-plan session", async () => {
const { base, next, run } = fixture("identity-handoff");
let finishClose!: () => void;
@@ -7594,6 +7612,34 @@ describe("native session bounded recovery", () => {
});
});
it.each(["full", "truncated"])("redacts %s identity from native failure writes, logs, and rethrown errors", async (mode) => {
const privateKeyPem = generateKeyPairSync("ed25519").privateKey.export({ type: "pkcs8", format: "pem" }).toString();
const keyBody = privateKeyPem.split("\n")[1];
const failure = new Error(`native provider failed: ${mode === "full" ? privateKeyPem : privateKeyPem.slice(0, 64)}`);
void failure.stack; // Also cover stacks materialized before the catch boundary.
const updates: Array<{ table: unknown; values: Record<string, unknown> }> = [];
const logs: string[] = [];
state.execute.mockReset().mockRejectedValueOnce(failure);
state.upsertRecoveryAction.mockReset().mockResolvedValue({});
const service = vi.spyOn(issueServiceModule, "issueService").mockReturnValue({
update: vi.fn(async () => ({ status: "blocked", statusVersion: 1 })),
} as unknown as ReturnType<typeof issueServiceModule.issueService>);
try {
await expect(executePaperclipNativeSession({
db: leaseDb(execution, {}, {}, updates), execution, runnerInstanceId: "runner",
runnerEnvironment: { PAPERCLIP_AGENT_PRIVATE_KEY: privateKeyPem },
onLog: async (_stream, text) => { logs.push(text); },
})).rejects.toBe(failure);
expect(updates.some(entry => entry.table === nativeRunFinalizations && entry.values.failureDetail)).toBe(true);
for (const output of [inspect(updates.map(entry => entry.values), { depth: null }), logs.join(""), failure.message, failure.stack!]) {
expect(output).not.toContain(keyBody.slice(0, 24));
expect(output).toContain("***REDACTED***");
}
} finally {
service.mockRestore();
}
});
it("persists actionable operator recovery without an automatic cleanup wake", async () => {
const updates: Array<{ table: unknown; values: Record<string, unknown> }> =
[];
@@ -3,6 +3,7 @@ import { readLocalAiCredentialFile } from "../local-ai-credential-file.js";
import { prepareGrokRunnerCredentials } from "./grok-runner-credentials.js";
import { copyBackGrokAuth } from "@paperclipai/adapter-grok-local/server";
import { createAgentIdentityRedactor } from "../agent-identity-redaction.js";
import {
isSupportedRemoteCodexVersion,
parseCodexCliVersion,
@@ -5256,6 +5257,7 @@ function nativeSessionConfigDigest(
.update(
JSON.stringify({
companyId: execution.binding.companyId,
...(execution.binding.agentKeyId ? { agentKeyId: execution.binding.agentKeyId } : {}),
normalizedSessionId: nativeSessionKey(execution),
executionLocation,
provider: execution.provider,
@@ -5308,6 +5310,7 @@ function nativeHarnessEnvironmentFingerprint(
.update(
canonicalJson({
companyId: execution.binding.companyId,
...(execution.binding.agentKeyId ? { agentKeyId: execution.binding.agentKeyId } : {}),
agentId: execution.binding.agentId,
issueId: execution.binding.issueId,
normalizedSessionId: nativeSessionKey(execution),
@@ -7294,6 +7297,14 @@ export async function executePaperclipNativeSession(input: {
},
) => Promise<unknown>;
}): Promise<AdapterExecutionResult> {
const agentKeyId = input.runnerEnvironment?.PAPERCLIP_AGENT_KEY_ID;
if (agentKeyId) {
// Recovered pre-upgrade inputs also need the current public identity marker
// before deciding whether an already-running provider can be reused.
input = { ...input, execution: { ...input.execution,
binding: { ...input.execution.binding, agentKeyId },
} };
}
const runId = input.execution.binding.runId;
if (nativeSessionStartups.has(runId)) {
throw new Error("native_session_supervisor_busy");
@@ -7435,6 +7446,10 @@ export async function executePaperclipNativeSession(input: {
async function executePaperclipNativeSessionWithinScope(
input: Parameters<typeof executePaperclipNativeSession>[0],
): Promise<AdapterExecutionResult> {
const identityRedactor = createAgentIdentityRedactor(input.runnerEnvironment?.PAPERCLIP_AGENT_PRIVATE_KEY);
const redactIdentityText = (text: string) => redactSensitiveText(
identityRedactor.chunk("diagnostic", text) + identityRedactor.finish("diagnostic"),
);
if (
input.execution.provider.kind !== "codex" &&
input.execution.provider.kind !== "opencode" &&
@@ -7853,6 +7868,7 @@ async function executePaperclipNativeSessionWithinScope(
controlPlaneSourceInstanceId: controlPlaneInstanceId,
},
{
privateKeyPem: input.runnerEnvironment?.PAPERCLIP_AGENT_PRIVATE_KEY,
onCommittedEvent: async (event) => {
await toolTrace.observe(event);
if (event.eventType === "item.completed" &&
@@ -8412,6 +8428,7 @@ async function executePaperclipNativeSessionWithinScope(
requireSessionCloseBeforeReturn: runnerdBackend !== null || input.instructionWorkingCopy !== undefined,
onSessionClosed: input.instructionWorkingCopy?.collectStopped,
onCheckpoint: async (snapshot) => {
snapshot = identityRedactor.redact(snapshot);
if (warmSessionId !== null && warmConfigDigest !== null) {
await persistWarmNativeCheckpoint(
input.execution,
@@ -8428,7 +8445,7 @@ async function executePaperclipNativeSessionWithinScope(
}
},
onPostCompletionEnrichmentFailure: async ({ stage, error }) => {
const detail = redactSensitiveText(
const detail = redactIdentityText(
error instanceof Error ? error.message : String(error),
).slice(-4_096);
await input.onLog?.(
@@ -8439,7 +8456,7 @@ async function executePaperclipNativeSessionWithinScope(
onSessionQuarantined: async (reason) => {
await input.onLog?.(
"stderr",
`[paperclip-runner] warm native session quarantined: ${redactSensitiveText(reason).slice(-1_000)}\n`,
`[paperclip-runner] warm native session quarantined: ${redactIdentityText(reason).slice(-1_000)}\n`,
);
},
onContinuityBreak: async (continuity) => {
@@ -8636,6 +8653,16 @@ async function executePaperclipNativeSessionWithinScope(
clearSteeringDeliveries(input.execution.binding.runId);
clearNativeRuntimeRequestResolutions(input.execution.binding.runId);
} catch (error) {
// Preserve typed failure semantics while removing credentials before any
// persistence, reporting, logging, or rethrow at this boundary.
if (error instanceof Error) {
const originalMessage = error.message;
error.message = redactIdentityText(originalMessage);
if (error.stack) error.stack = redactIdentityText(originalMessage
? error.stack.split(originalMessage).join(error.message) : error.stack);
} else {
error = identityRedactor.redact(error);
}
if (nativeRunsDetachingForRestart.has(input.execution.binding.runId)) {
await leaseRenewal.stop().catch(() => undefined);
liveQuestions.close();
@@ -8674,7 +8701,7 @@ async function executePaperclipNativeSessionWithinScope(
);
const failedAtMs = Date.now();
const executionFailureMessage = redactSensitiveText(
const executionFailureMessage = redactIdentityText(
error instanceof Error ? error.message : String(error),
).slice(-4_096);
if (!taskSettleScope) {
@@ -8785,11 +8812,10 @@ async function executePaperclipNativeSessionWithinScope(
const { exhausted } = recoveryProjection;
const integrityFailure =
sourceFailureCode === "native_event_replay_conflict";
const message =
error instanceof Error
? error.message.slice(0, 2_000)
: String(error).slice(0, 2_000);
const sanitizedStderrTail = redactSensitiveText(message).slice(-4_096);
const message = redactIdentityText(
error instanceof Error ? error.message : String(error),
).slice(0, 2_000);
const sanitizedStderrTail = redactIdentityText(message).slice(-4_096);
// Set inside the transaction only when the write below genuinely
// transitions the run into "failed". Read after the transaction
// commits, so a rolled-back write never reports a false failure.
@@ -8820,7 +8846,7 @@ async function executePaperclipNativeSessionWithinScope(
recoveryState:
phase === "retryable_failure" ? "resuming_session" : "blocked",
failureCode,
failureDetail: {
failureDetail: identityRedactor.redact({
message,
originalFailureCode:
error instanceof NativeProviderTerminalFailure
@@ -8857,7 +8883,7 @@ async function executePaperclipNativeSessionWithinScope(
"bootstrap_retry"
? "Retry provider bootstrap on this same run; durable evidence proves no provider session or provider event was created."
: "Resume this same run from its exact persisted native provider checkpoint after the retry delay.",
},
}),
nextAttemptAt,
recoveryHistory: sql`(
select coalesce(jsonb_agg(item order by ordinal), '[]'::jsonb)
@@ -1,6 +1,6 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { asc, eq, sql } from "drizzle-orm";
import { randomUUID } from "node:crypto";
import { generateKeyPairSync, randomUUID } from "node:crypto";
import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils";
import { readCompletedAssistantMessageCandidate, resolveHeartbeatRunResponse, selectHeartbeatRunFinalAgentMessage } from "../heartbeat-run-summary.js";
import {
@@ -299,6 +299,90 @@ describe("PaperclipControlPlanePort conformance", () => {
}
});
it("redacts identity private material before persisting native events and checkpoints", async () => {
const identity = { ...CONTROL_PLANE_CONFORMANCE_OPEN.identity, runId: randomUUID(), sessionId: randomUUID() };
const runnerId = randomUUID();
const privateKeyPem = generateKeyPairSync("ed25519").privateKey.export({ type: "pkcs8", format: "pem" }).toString();
const keyBody = privateKeyPem.split("\n")[1];
await db.insert(heartbeatRuns).values({
id: identity.runId, companyId: identity.companyId, agentId: identity.agentId,
status: "running", runtimeMode: "native", nativeIssueId: identity.issueId,
nativeSessionId: identity.sessionId, runnerInstanceId: runnerId,
completionContractId: contractId, completionContractSha256: contractSha,
contextSnapshot: { issueId: identity.issueId },
});
const observed: PrpEvent[] = [];
const port = new PaperclipControlPlanePort(db, {
...identity, completionContractId: contractId, completionContractSha256: contractSha,
sourceInstanceId: runnerId, controlPlaneSourceInstanceId: `identity-${identity.runId}`,
}, { privateKeyPem, onCommittedEvent: async event => { observed.push(event); } });
await port.openRun({ identity, backendKind: "mock", sourceInstanceId: runnerId });
await port.appendEvent({
schema: "paperclip.prp.event.v1", sourceEventId: `${runnerId}:1`, sourceSeq: 1,
sourceInstanceId: runnerId, sourceKind: "runner", runId: identity.runId,
normalizedSessionId: identity.sessionId, eventType: "tool.execution.started", schemaVersion: 1,
priority: 0, emittedAt: new Date().toISOString(), payload: {
schema: "paperclip.tool.execution.v1", executionId: "identity-output", transport: "builtin",
operation: "execute", name: "diagnostic", target: null, namespace: null, readOnly: true,
status: "running", durationMs: null, exitCode: null, progress: null,
output: privateKeyPem, outputBytes: Buffer.byteLength(privateKeyPem), outputTruncated: false,
outputDigest: `sha256:${"a".repeat(64)}`,
},
});
await port.checkpointSession({ backendKind: "mock", sessionId: identity.sessionId, identity,
semanticResult: { ...CONTROL_PLANE_CONFORMANCE_RESULT, summary: privateKeyPem },
});
let sourceSeq = 2;
for (const [itemId, chunks] of [
["halves", [keyBody.slice(0, 31), keyBody.slice(31)]],
["bytes", [...keyBody]],
] as const) {
for (const [index, chunk] of chunks.entries()) {
const event: PrpEvent = {
schema: "paperclip.prp.event.v1", sourceEventId: `${runnerId}:${sourceSeq}`, sourceSeq: sourceSeq++,
sourceInstanceId: runnerId, sourceKind: "runner", runId: identity.runId,
normalizedSessionId: identity.sessionId, turnId: "identity-turn", itemId,
eventType: "item.delta", schemaVersion: 1, priority: 1, emittedAt: new Date().toISOString(),
payload: { itemId, kind: "commandExecution", text: chunk, update: { delta: chunk } },
};
await port.appendEvent(event);
expect((await port.appendEvent(event)).disposition).toBe("duplicate");
if (index === 0) await port.appendEvent({
...event, sourceEventId: `${runnerId}:${sourceSeq}`, sourceSeq: sourceSeq++,
payload: { itemId: "another-provider-item", kind: "commandExecution", text: "Unrelated output\n", update: { delta: "Unrelated output\n" } },
});
}
}
await port.appendEvent({
schema: "paperclip.prp.event.v1", sourceEventId: `${runnerId}:${sourceSeq}`, sourceSeq: sourceSeq++,
sourceInstanceId: runnerId, sourceKind: "runner", runId: identity.runId,
normalizedSessionId: identity.sessionId, turnId: "tail-turn", itemId: "reasoning-item",
eventType: "item.delta", schemaVersion: 1, priority: 1, emittedAt: new Date().toISOString(),
payload: { kind: "reasoning", text: "Thinking-" },
});
const terminal: PrpEvent = {
schema: "paperclip.prp.event.v1", sourceEventId: `${runnerId}:${sourceSeq}`, sourceSeq: sourceSeq++,
sourceInstanceId: runnerId, sourceKind: "runner", runId: identity.runId,
normalizedSessionId: identity.sessionId, turnId: "tail-turn",
eventType: "turn.completed", schemaVersion: 1, priority: 0, emittedAt: new Date().toISOString(),
payload: { status: "completed" },
};
await port.appendEvent(terminal);
expect((await port.appendEvent(terminal)).disposition).toBe("duplicate");
expect(observed.at(-1)?.payload.outputTails).toEqual([{ itemId: "reasoning-item", payload: { kind: "reasoning", text: "-" } }]);
const persistedEvents = await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, identity.runId));
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, identity.runId));
for (const value of [persistedEvents, observed, run.runnerProfileJson]) {
expect(JSON.stringify(value)).not.toContain(keyBody);
expect(JSON.stringify(value)).toContain("***REDACTED***");
}
for (const itemId of ["halves", "bytes"]) {
const deltas = observed.filter(event => event.payload.itemId === itemId).map(event => event.payload);
expect(deltas.map(delta => delta.text).join("")).toBe("***REDACTED***");
expect(deltas.map(delta => (delta.update as { delta: string }).delta).join("")).toBe("***REDACTED***");
}
});
it("runs the unchanged package conformance suite against Paperclip persistence", async () => {
const identity = CONTROL_PLANE_CONFORMANCE_OPEN.identity;
const committedEventIds: string[] = [];
@@ -1,3 +1,4 @@
import { createAgentIdentityRedactor } from "../agent-identity-redaction.js";
import { and, asc, eq, gt, or } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
@@ -39,6 +40,9 @@ export interface PaperclipControlPlaneBinding {
controlPlaneSourceInstanceId: string;
}
const IDENTITY_DELTA_RETRY_WINDOW = 1_024;
const IDENTITY_DELTA_RETRY_BYTES = 4 * 1024 * 1024;
function isPrpEvent(value: NativeRunEvent | PrpEvent): value is PrpEvent {
return "schema" in value && [
"paperclip.prp.event.v1",
@@ -71,6 +75,9 @@ function assertTerminal(value: unknown): asserts value is PrpTerminalState {
/** Production implementation of the runner package's deliberately narrow persistence port. */
export class PaperclipControlPlanePort implements ControlPlanePort {
readonly #db: Db;
readonly #identityRedactor: ReturnType<typeof createAgentIdentityRedactor>;
readonly #redactedDeltas = new Map<string, { event: PrpEvent; originalSha: string; bytes: number }>();
#redactedDeltaBytes = 0;
readonly #binding: PaperclipControlPlaneBinding;
#sessionId: string | null = null;
readonly #onCommittedEvent?: (event: PrpEvent) => Promise<void>;
@@ -80,11 +87,14 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
db: Db,
binding: PaperclipControlPlaneBinding,
options: {
/** Runtime-only secret; never part of the persisted binding. */
privateKeyPem?: string;
onCommittedEvent?: (event: PrpEvent) => Promise<void>;
onDuplicateEvent?: (event: PrpEvent) => Promise<void>;
} = {},
) {
this.#db = db;
this.#identityRedactor = createAgentIdentityRedactor(options.privateKeyPem);
this.#binding = structuredClone(binding);
this.#onCommittedEvent = options.onCommittedEvent;
this.#onDuplicateEvent = options.onDuplicateEvent;
@@ -151,6 +161,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
}
async checkpointSession(snapshot: PersistedNativeSession): Promise<void> {
snapshot = this.#identityRedactor.redact(snapshot);
const identity = snapshot.identity;
if (
identity.companyId !== this.#binding.companyId
@@ -183,7 +194,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
if (!isPrpEvent(value)) throw new Error("native_legacy_event_not_supported");
const validated = validatePrpEvent(value);
if (!validated.ok) throw new Error(`native_event_schema_invalid:${validated.issues[0]?.message ?? "unknown"}`);
const event = validated.event;
let event = this.#identityRedactor.redact(validated.event);
if (event.runId !== this.#binding.runId || (this.#sessionId && event.normalizedSessionId !== this.#sessionId)) {
throw new Error("native_event_binding_mismatch");
}
@@ -193,6 +204,37 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
if (event.sourceInstanceId !== expectedSourceInstanceId) {
throw new Error("native_event_source_binding_mismatch");
}
const terminalItem = /^item\.(completed|failed|cancelled)$/.test(event.eventType);
const terminalTurn = /^(turn|session)\.(completed|failed|cancelled|interrupted|closed)$/.test(event.eventType);
if ((event.eventType === "item.delta" || terminalItem || terminalTurn) && this.#identityRedactor.values.length > 0) {
const key = `${event.sourceInstanceId}:${event.sourceEventId}`;
const cached = this.#redactedDeltas.get(key);
const originalSha = nativeSha256(validated.event);
if (cached) {
if (cached.originalSha !== originalSha) throw new Error("native_event_source_payload_conflict");
event = cached.event;
} else {
const stream = `${event.sourceInstanceId}:${event.turnId}:${event.itemId}`;
event = { ...event, payload: event.eventType === "item.delta"
? this.#identityRedactor.delta(stream, validated.event.payload, event.itemId)
: this.#identityRedactor.settleDeltas(
terminalTurn ? (event.eventType.startsWith("session.") ? `${event.sourceInstanceId}:` : `${event.sourceInstanceId}:${event.turnId}:`) : stream,
event.payload, terminalTurn,
),
};
// Retries must use the same redacted payload without consuming a delta twice.
const bytes = Buffer.byteLength(JSON.stringify(event));
this.#redactedDeltas.set(key, { event, originalSha, bytes });
this.#redactedDeltaBytes += bytes;
// Match the bounded runner transcript retry window; large tool output
// also has a byte cap so long runs cannot retain another full transcript.
while (this.#redactedDeltas.size > IDENTITY_DELTA_RETRY_WINDOW || this.#redactedDeltaBytes > IDENTITY_DELTA_RETRY_BYTES) {
const oldest = this.#redactedDeltas.keys().next().value!;
this.#redactedDeltaBytes -= this.#redactedDeltas.get(oldest)!.bytes;
this.#redactedDeltas.delete(oldest);
}
}
}
const persisted = await appendHeartbeatRunEvent(this.#db, {
companyId: this.#binding.companyId,
runId: this.#binding.runId,
@@ -264,6 +306,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
}
async completeRun(value: NativeRunResult | CompleteControlPlaneRunInput): Promise<void> {
value = this.#identityRedactor.redact(value);
if (!isCompleteInput(value)) throw new Error("native_structured_result_required");
// Capture compatibility diagnostics before canonical validation removes
// legacy/non-actionable attention payloads. They are operator evidence,