mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-21 16:27:18 +02:00
## Thinking Path > - Paperclip manages AI agents and their work. > - Agent creation, approval, pause, and termination change whether an agent can work. > - These changes currently use separate service and database paths. > - Some agents need setup after their record exists and before their harness can run. > - This PR adds one module that owns those state changes and their transactions. > - The module records progress and retries incomplete work after a server restart. ## Linked Issues or Issue Description **Problem or motivation** A hire can become active before its execution environment is ready. Direct agent state writes also bypass one common lifecycle boundary. Termination does not have a durable step for resource cleanup. **Proposed solution** Use agent lifecycle commands for hiring, approval, pause, resume, and termination. Keep proposed hires pending until approval. Prepare each approved hire, test its saved harness configuration, and then permit work. Wait for required plugin work before completing a step. **Alternatives considered** A general database commit hook would expose transaction details to callers. A timer alone would delay each new hire. This module owns each command transaction and starts its worker after commit. A periodic scan recovers work after a process stops. **Roadmap alignment** This change adds the lifecycle boundary for the existing agent and plugin systems. It does not add a user interface or a provider implementation. It replaces the lifecycle delivery approach in #15391. Related proposals include #11475 and #13099; this change does not add their external executor protocols. ## What Changed - Add durable approval, preparation, verification, pause, resume, stop, and cleanup states. - Keep agent creation, lifecycle state, configuration writes, and agent record deletion behind `modules/agent-lifecycle`. Keep validation, credential rules, reads, onboarding, invitations, general approvals, and company data deletion in their services. - Commit a hire before the remaining onboarding or invitation work. Serialize requests with the existing dedicated database connection helper. Reuse the hire after a failed attempt. - Keep accepted work in the run queue during setup. Require execution and cleanup evidence before completing pause or termination. - Retain the original credential owner when approving migrated hires. - Start lifecycle work after each command commits. Use database leases and revision checks for retries and late results. - Add a generic required plugin method and capability. Store the required plugin IDs for each agent. Track host and plugin completion separately. - Keep harness verification and credential rules in services. Supply their results to lifecycle through explicit ports. Reject failed logins and incomplete probes. - Remove reverse imports from lifecycle adapters into services. Share record queries and validation below both layers. - Use one hire decision path for agent IDs and approval IDs. Resolve the approval and agent change in one transaction. Expose policy reconciliation on the command object. - Save configuration and verification invalidation through one module operation. Ordinary commands own their transaction. Restrict the shared transaction integration to its listed callers. Reject identity, company, accounting, timestamp, and unknown fields. - Require completed termination before deleting agent records. The company deletion service calls the module through a separate deletion interface. - Save an approved secret before applying its agent binding. A failed binding leaves the secret approved. A retry reuses it. - Remove old permission and metadata export files. Move hire configuration rules out of lifecycle persistence. - Report failed worker steps and scans with operation context and known error codes. Omit provider messages, stacks, and configuration values. Document ordinary application use and extension rules. - Recover expired native owners only after execution stops. Retry cleanup of failed retained leases. Wait for setup in the live smoke script. - Keep manual, budget, and company pause reasons separate. Guard execution status writes with the ready state. - Add a migration, boundary checks, regression tests, and a lifecycle guide. Keep the current UI. - Limit periodic policy checks to 100 eligible agents per minute. Continue from the last agent ID. Exclude pending hires and agents in termination or a final state. Keep explicit company and budget updates immediate. ## Verification - Latest head `ccc3c86b0` aligns the shared status update schema with the PATCH route. All 15 shared tests, 104 server route/OpenAPI tests, 2 CLI tests, and shared/server/CLI TypeScript checks pass. The Greptile comment is fixed. CI is running; no new Apex review was requested for this small fix. - Rebase `75708ac94` rebases onto master at `2eb5187e4`. The backup test uses the shared 90-second timeout from master; the older timeout commit was removed. The affected backup test passes. - Agent budget edits now pass the target agent ID through enforcement. All 50 affected tests, server TypeScript, and 11 boundary tests pass. Both configuration update paths have regression coverage. CI is running on the latest head. No new Apex review was requested for these small fixes. - Rebase `9b568666a` preserves the run-control extraction and delivery-work startup changes from master. All 559 affected tests, server TypeScript, and 11 boundary tests pass. CI and Apex review are running on the final head. - The policy scan fix passes 56 lifecycle and diagnostic tests, 24 policy and caller tests, and 11 boundary tests. A regression test checks the page limit, interval, excluded states, and cursor wraparound. - Rebase `fd4698750` passes all 611 tests in eight affected lifecycle, route, and heartbeat suites. Server TypeScript and all 11 module boundary tests pass. The company deletion rollback and concurrent hire tests are included. - Follow-up `00aac7646` fixes the failed decision deletion test and the public update schema. All 126 affected server tests, 8 shared tests, 2 CLI tests, and 11 boundary tests pass. Shared, server, CLI, and UI TypeScript checks pass. - Server TypeScript passes: `pnpm --filter @paperclipai/server exec tsc --noEmit`. - All 11 boundary tests pass: `node --test scripts/check-module-boundaries.test.mjs`. The repository boundary scan also passes. - All 68 lifecycle, failure diagnostic, and harness verification tests pass. Tests reject forbidden fields through the root command, combined transition command, and restricted transaction integration. They also check invalid fields returned by configuration preparation. - Failure tests cover host work, plugin work, claims, renewals, deferrals, and scans. Log tests check known error codes and exclusion of private error contents. - All 355 tests in 10 existing caller suites pass. These tests cover secret approval, pairing, pending hires, credentials, company import, built-in agents, managed agents, instructions, and skills. - The branch is rebased onto `origin/master` at `2eb5187e4`. The queue guards and cancellation lock fix use the extracted heartbeat queue. Agent cancellation uses the extracted run-control file. The source diff scan found no secrets or private URLs. - Earlier checks cover approval retries, rollback, late verification results, policy holds, deletion rollback, concurrent company deletion, and queue admission during setup. - Before the rebase, CI passed on `00aac7646` and Greptile Apex rated it 5/5 with no open comments. CI and a new Apex review are pending for the rebased commit. The branch has no merge conflicts. - The full local build and native Dot suite were not run. The host has no Cargo. No live provider test was run. ## Risks - Background policy recovery takes more than one minute when more than 100 agents are eligible. Explicit company and budget updates still reconcile immediately. - The restricted configuration integration keeps an agent reference and its dependent records in one transaction. It cannot change a budget or invoke a lifecycle transition. A periodic scan starts pending setup after that transaction commits. - Secret approval and binding use separate transactions. A failed binding can leave an approved secret with no agent binding. - New approved hires remain unavailable until setup and verification complete. Existing clients see `paused` during these steps. This PR does not change the UI. - Migration `0320_daily_onslaught.sql` maps existing statuses and pause reasons. It does not create external resources or claim that an existing harness passed verification. - Use a coordinated server update for this migration. Older server versions can write legacy status without the new lifecycle checks. - A failed onboarding or invitation request can leave a committed hire. A retry reuses that hire and completes the remaining records. - Deletion requires completed termination. Company deletion can require another request while cleanup is pending. - Required plugins must make repeated calls safe and reject older revisions. A disabled or removed required plugin blocks completion until it is restored. - A new hire can run a second harness test after the existing UI test. Some adapters can charge for this test. - No live provider test was run. Provider implementation and resource backfill remain separate work. ## Model Used OpenAI GPT-6 through Codex, with reasoning, code tools, and local test execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have described the issue in this PR with the feature request field labels - [x] I have not referenced internal or instance-local issues or links - [x] My branch name describes the change - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented risks - [x] Targeted local tests pass - [x] All Paperclip CI gates are green on the new commit - [x] Greptile Apex is 5/5 with no open comments on the new commit - [x] I will address review comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
258 lines
16 KiB
TypeScript
258 lines
16 KiB
TypeScript
import { createAgentLifecycle } from "../services/agent-lifecycle.js";
|
|
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 createAgentLifecycle(db).requestHire(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(createAgentLifecycle(db).requestHire(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***");
|
|
});
|
|
});
|