Files
PaperClipAI/server/src/__tests__/agent-secrets-routes.test.ts
T
DottaandClaude 1e13c58a4e fix(heartbeat): name the cause of generic adapter failures and keep SQL text off the board (#20483)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Heartbeat run settlement records why a run failed, and the board
shows that record.
> - Runs that fail without a named code settle as `adapter_failed` (or
`setup_failed`) with no cause.
> - A user, an operator, and the restart chaos harness cannot tell what
went wrong from such a run.
> - Some run errors also show raw SQL statement text to users.
> - This pull request records a bounded `failureCause` code for generic
failures, shows it on the board, and keeps SQL text out of run errors.
> - The benefit is that a generic failure now names its cause, for
example "adapter failed (40001)", without leaking messages, SQL, or
secrets.

## Linked Issues or Issue Description

Refs #20385 (the nested-cause extraction this change reuses). Related:
#20421 (restart chaos universal checks U1-U4).

**What happened?**

The restart chaos audit of 79 saved waves found 30 failed runs with
`errorCode: "adapter_failed"` and a null or generic error. Every U3
("diagnosable") warning was `adapter_failed`. Nobody could tell what
failed. Some board run errors also showed raw SQL statement text from
wrapped database errors (Drizzle `Failed query: ... params: ...`).

**Expected behavior**

A run that fails with a generic code names a short, safe cause. The
board shows the cause next to the stop reason. Run error text never
shows SQL statements or their parameters.

**Steps to reproduce**

Make an adapter throw a wrapped database error (an `Error` whose nested
`cause` has `code: "40001"` and whose message has a Drizzle `Failed
query:` statement). Before this change, the run settles as
`adapter_failed` with no cause, and `heartbeat_runs.error` contains the
SQL statement and parameters. The new tests in
`server/src/services/heartbeat/run-completion.test.ts` reproduce this.

## What Changed

- Runner: move the #20385 event-commit cause extraction into
`safeErrorCauseCode`
(`packages/paperclip-runner/src/control-plane/safe-error-cause.ts`) and
export it. The Runner's own diagnostics use the same function, unchanged
in behavior.
- Shared: add the `failureCause` contract
(`packages/shared/src/run-failure-cause.ts`): one `[A-Za-z0-9_.:-]`
token of at most 80 characters, `normalizeRunFailureCause`,
`readRunFailureCause`, and `withoutSqlStatementText`.
- Server: add `server/src/services/heartbeat/run-failure-cause.ts`.
Settlement records `resultJson.failureCause` only when the code is
generic (`adapter_failed`, `setup_failed`). `errorCode` stays the same.
- Thrown errors (`failRun`, `failRunSetup`): `provider_http_<status>`,
else `provider_<category>`, else the first safe code in the error and up
to three nested causes (`40001`, `ECONNRESET`), else the error class
name, else `unknown_error`.
- Adapter results without a code (`completeRun`): the error family,
`signal_<name>`, `process_cancellation_failed`, `exit_code_<n>`,
`adapter_reported_error`, or `unknown_error`.
- The failure log lines (`heartbeat execution failed`, `heartbeat
execution setup failed`, and a new `heartbeat run failed` warning for
generic adapter results) include `failureCause` and `errorCode`.
- Server: replace SQL statement text in run error text with "Database
query failed (<cause>)" at all three settlement paths, including the
cancelled branch. The execution blocker's `runError`, the attention
inbox (failed-run excerpt and metadata), and continuation summaries
apply the same replacement on read, so older rows also stop showing SQL
there.
- Server: Retry admission and failed-preparation replay accept only a
closed set of `resultJson` keys. `failureCause` is added to each of
those lists (`task-retry.ts`, `chat-channels/failed-run-retry.ts`,
`cancelled-native-startup.ts`, `fresh-workspace-continuation.ts`). It is
a diagnostic code with no execution or replay authority, so a
failed-preparation run stays retryable.
- Server: `runsForIssue` returns a validated top-level `failureCause`.
It is null for older rows, non-string JSON values, and malformed values.
- UI: `RunForIssue.failureCause`; `IssueRunLedger` shows "adapter failed
(40001)". Older runs keep "adapter failed". The Storybook run-ledger
fixture has a failed run with a cause.
- Restart chaos harness: run samples keep `failureCause`. U3 treats a
generic code with a specific `failureCause` as diagnosable. A bare
`Error`, `unknown_error`, or the no-code fallback
`adapter_reported_error` still counts as vague. U3 stays a warning.
- Docs: `doc/run-log-events.md` and the harness README describe the
field and the SQL replacement.

## Verification

- Red before the fix: the four new `run-completion.test.ts` cases failed
against `origin/master`'s `run-completion.ts` (no `failureCause`, SQL
text in `error`).
- Green:
- `server/src/services/heartbeat/run-completion.test.ts`: all tests
passed (real embedded PostgreSQL). New cases cover a nested `40001`
three levels deep for execution and setup failures, SQL and a secret
parameter absent from `error` and `resultJson`, the bound (an
81-character code and a SQL "code" fall back to the class name),
`exit_code_137` for a code-less adapter result, a cancelled result with
SQL text, no cause for a named code, and the log line. On this loaded
host the suite's `afterAll` database teardown hit its 30 s hook limit
after every test passed (the known local teardown limit, also seen in
#20385). CI runs the suite.
- `server/src/services/heartbeat/run-failure-cause.test.ts` (4),
`server/src/__tests__/activity-service.test.ts` (recorded, legacy,
malformed, overlong, boolean, and number cause projections),
`server/src/__tests__/issue-continuation-summary.test.ts` (legacy SQL
row).
- `packages/shared/src/run-failure-cause.test.ts` (6),
`ui/src/components/IssueRunLedger.test.tsx` (21), restart chaos
`universal.test.ts` and `observer.test.ts`.
-
`packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts`:
207 passed (the stall-diagnostic cases still read `40001` and
`ECONNRESET`).
- Typecheck: shared, runner, server (all layers), UI, restart chaos
harness. `pnpm check:token-gates`: all gates clean.
- `pnpm verify` returned exit 2 (global doc input changed); required CI
supplies broad coverage.
- CI on `6295f8d` found that the new key made failed-preparation runs
ineligible for Retry (`chat-channels.integration.test.ts` saved
board-message Retry got 409;
`workspace-recovery-preparation-dispatch.test.ts` dispatched 0 Retries).
Both reproduced locally and pass after the allowlist fix, with the other
459 Retry cases in `chat-channels.integration.test.ts` and all 25 in
`workspace-recovery-preparation-dispatch.test.ts`.
- No chaos waves were run. Storybook was not opened in a browser; the
fixture typechecks and the label is covered by the UI test.

## Risks

- Low risk. `errorCode` values do not change, so retry, recovery, and
comparison logic is unaffected.
- No schema change and no migration. `failureCause` is a new optional
`resultJson` key. Rows saved by the previous release have no key and
render as before; a new row read by an old server is ignored.
- The SQL replacement only acts on a Drizzle `Failed query:` marker, or
on `$n` placeholder text with a statement shape. Ordinary error text
does not change. When it acts, it also drops the text after the
statement.
- Code that checks `resultJson` against a closed key list must allow
`failureCause`. I found and updated the four lists on the Retry path; a
list I missed would refuse a Retry for a run with a generic failure.
- This is the run log / instance database path. It adds no Telemetry
event.
- The server failure log line still logs the raw error message
(unchanged behavior); only the board-facing text is changed.

## Model Used

- Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, used through
Claude Code with tool use (shell, file editing) and code execution for
tests.

## 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 either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-10 02:14:53 -06:00

306 lines
13 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { mkdirSync, rmSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import express from "express";
import request from "supertest";
import { eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
activityLog,
agents,
companies,
companySecretBindings,
companySecretProviderConfigs,
companySecretVersions,
companySecrets,
createDb,
heartbeatRuns,
secretAccessEvents,
} from "@paperclipai/db";
import { LOW_TRUST_REVIEW_PRESET, type AgentApiKeyScope } from "@paperclipai/shared";
import { REDACTED_EVENT_VALUE } from "../redaction.js";
import { errorHandler } from "../middleware/error-handler.js";
import { secretRoutes } from "../routes/secrets.js";
import { secretService } from "../services/secrets.js";
import { createRunSecretRedactionRegistry } from "../services/run-secret-redaction.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
describeEmbeddedPostgres("agent secret routes", () => {
let stopDb: (() => Promise<void>) | null = null;
let db!: ReturnType<typeof createDb>;
const previousKeyFile = process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE;
const secretsTmpDir = path.join(os.tmpdir(), `paperclip-agent-secret-routes-${randomUUID()}`);
beforeAll(async () => {
mkdirSync(secretsTmpDir, { recursive: true });
process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = path.join(secretsTmpDir, "master.key");
const started = await startEmbeddedPostgresTestDatabase("agent-secret-routes");
stopDb = started.cleanup;
db = createDb(started.connectionString);
});
afterEach(async () => {
await db.delete(activityLog);
await db.delete(secretAccessEvents);
await db.delete(companySecretBindings);
await db.delete(companySecretVersions);
await db.delete(companySecrets);
await db.delete(companySecretProviderConfigs);
await db.delete(heartbeatRuns);
await db.delete(agents);
await db.delete(companies);
});
afterAll(async () => {
await stopDb?.();
if (previousKeyFile === undefined) delete process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE;
else process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = previousKeyFile;
rmSync(secretsTmpDir, { recursive: true, force: true });
});
async function seedAgentRun(permissions: Record<string, unknown> = {}) {
const companyId = randomUUID();
const agentId = randomUUID();
const heartbeatRunId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: "Agent secret routes",
issuePrefix: `S${companyId.slice(0, 7)}`.toUpperCase(),
status: "active",
});
await db.insert(agents).values({
id: agentId,
companyId,
name: "Secret reader",
role: "engineer",
adapterType: "codex_local",
adapterConfig: {},
permissions,
status: "idle",
});
await db.insert(heartbeatRuns).values({
id: heartbeatRunId,
companyId,
agentId,
status: "running",
contextSnapshot: {},
});
return { companyId, agentId, heartbeatRunId };
}
function createApp(
fixture: Awaited<ReturnType<typeof seedAgentRun>>,
keyScope: AgentApiKeyScope = { kind: "standard" },
source: "agent_jwt" | "agent_key" = "agent_jwt",
) {
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = {
type: "agent",
agentId: fixture.agentId,
companyId: fixture.companyId,
runId: fixture.heartbeatRunId,
keyScope,
keyId: source === "agent_key" ? randomUUID() : undefined,
source,
};
next();
});
app.use("/api", secretRoutes(db));
app.use(errorHandler);
return app;
}
it("lists metadata only, reads env and access grants, and audits success and failure", async () => {
const fixture = await seedAgentRun();
const svc = secretService(db);
const envSecret = await svc.create(fixture.companyId, {
key: "ENV_ONLY_KEY",
name: "Env only",
description: "Injected and API-readable",
provider: "local_encrypted",
value: "env-secret-value",
});
const apiSecret = await svc.create(fixture.companyId, {
key: "API_ONLY_KEY",
name: "API only",
provider: "local_encrypted",
value: "api-secret-value",
});
const unboundSecret = await svc.create(fixture.companyId, {
key: "UNBOUND_KEY",
name: "Unbound",
provider: "local_encrypted",
value: "unbound-secret-value",
});
const projectSecret = await svc.create(fixture.companyId, {
key: "PROJECT_KEY",
name: "Project layer",
provider: "local_encrypted",
value: "project-secret-value",
});
await svc.createBinding({
companyId: fixture.companyId,
secretId: envSecret.id,
targetType: "agent",
targetId: fixture.agentId,
configPath: "env.ENV_ONLY_KEY",
});
await svc.createBinding({
companyId: fixture.companyId,
secretId: apiSecret.id,
targetType: "agent",
targetId: fixture.agentId,
configPath: "access.API_ONLY_KEY",
projectionClass: "unclassified",
});
const projectBinding = await svc.createBinding({
companyId: fixture.companyId,
secretId: projectSecret.id,
targetType: "project",
targetId: randomUUID(),
configPath: "env.PROJECT_KEY",
});
await db.update(heartbeatRuns).set({
contextSnapshot: {
paperclipSecrets: {
manifest: [{
bindingId: projectBinding.id,
secretId: projectSecret.id,
configPath: projectBinding.configPath,
}],
},
},
}).where(eq(heartbeatRuns.id, fixture.heartbeatRunId));
const list = await request(createApp(fixture)).get("/api/agents/me/secrets");
expect(list.status).toBe(200);
expect(list.body.secrets).toEqual([
expect.objectContaining({ key: "api_only_key", delivery: "api", projectionClass: "unclassified" }),
expect.objectContaining({ key: "env_only_key", delivery: "env" }),
expect.objectContaining({ key: "project_key", delivery: "env" }),
]);
expect(JSON.stringify(list.body)).not.toContain("secret-value");
expect(await db.select().from(secretAccessEvents)).toEqual([]);
expect(await db.select().from(activityLog)).toEqual([
expect.objectContaining({ action: "secret.access.listed", runId: fixture.heartbeatRunId }),
]);
const fetched = await request(createApp(fixture)).post("/api/agents/me/secrets/env_only_key/value");
expect(fetched.status).toBe(200);
expect(fetched.headers["cache-control"]).toBe("no-store");
expect(fetched.body).toEqual({ key: "env_only_key", value: "env-secret-value", version: 1 });
const [registeredRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.heartbeatRunId));
expect(JSON.stringify(registeredRun.contextSnapshot)).not.toContain("env-secret-value");
expect(registeredRun.contextSnapshot).toMatchObject({
paperclipSecretRedactions: [expect.objectContaining({ fingerprintSha256: expect.any(String), material: expect.any(Object) })],
});
expect(await db.select().from(secretAccessEvents)).toEqual([
expect.objectContaining({ secretId: envSecret.id, outcome: "success", consumerType: "agent_api" }),
]);
expect(await db.select().from(activityLog)).toEqual(expect.arrayContaining([
expect.objectContaining({ action: "secret.value.read", entityId: envSecret.id }),
]));
const projectFetched = await request(createApp(fixture)).post("/api/agents/me/secrets/project_key/value");
expect(projectFetched.status).toBe(200);
expect(projectFetched.body).toEqual({ key: "project_key", value: "project-secret-value", version: 1 });
expect(await db.select().from(secretAccessEvents)).toEqual(expect.arrayContaining([
expect.objectContaining({ secretId: projectSecret.id, outcome: "success", consumerType: "agent_api" }),
]));
const denied = await request(createApp(fixture)).post("/api/agents/me/secrets/unbound_key/value");
expect(denied.status).toBe(403);
expect(await db.select().from(secretAccessEvents)).not.toEqual(expect.arrayContaining([
expect.objectContaining({ secretId: unboundSecret.id }),
]));
expect(await db.select().from(activityLog)).not.toEqual(expect.arrayContaining([
expect.objectContaining({ action: "secret.value.read", entityId: unboundSecret.id }),
]));
});
it("fails closed when run redaction registration cannot be persisted", async () => {
const fixture = await seedAgentRun();
await expect(createRunSecretRedactionRegistry(db).register(fixture.companyId, randomUUID(), "must-not-return"))
.rejects.toThrow("Heartbeat run redaction registration failed");
});
it("deduplicates concurrent redaction registrations for the same run and value", async () => {
const fixture = await seedAgentRun();
const registry = createRunSecretRedactionRegistry(db);
await Promise.all([
registry.register(fixture.companyId, fixture.heartbeatRunId, "duplicate-secret"),
registry.register(fixture.companyId, fixture.heartbeatRunId, "duplicate-secret"),
]);
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.heartbeatRunId));
expect(run.contextSnapshot).toMatchObject({
paperclipSecretRedactions: [expect.objectContaining({ fingerprintSha256: expect.any(String) })],
});
expect((run.contextSnapshot as { paperclipSecretRedactions: unknown[] }).paperclipSecretRedactions).toHaveLength(1);
});
it("redacts batched runs from projected registries and enforces company scope", async () => {
const first = await seedAgentRun();
const foreign = await seedAgentRun();
const registry = createRunSecretRedactionRegistry(db);
await registry.register(first.companyId, first.heartbeatRunId, "first-secret-value");
await registry.register(foreign.companyId, foreign.heartbeatRunId, "foreign-secret-value");
const runs = [
{ id: first.heartbeatRunId, text: "first-secret-value foreign-secret-value", createdAt: new Date() },
{ id: foreign.heartbeatRunId, text: "foreign-secret-value", createdAt: new Date() },
];
const redacted = await registry.redactForRuns(first.companyId, runs);
expect(redacted[0].text).toBe(`${REDACTED_EVENT_VALUE} foreign-secret-value`);
expect(redacted[0].createdAt).toEqual(runs[0].createdAt);
expect(redacted[1].text).toBe("foreign-secret-value");
expect(await registry.redactForRun(first.companyId, first.heartbeatRunId, runs[0].text))
.toBe(redacted[0].text);
});
it("drops SQL statement text from run errors on every run read", async () => {
const fixture = await seedAgentRun();
const registry = createRunSecretRedactionRegistry(db);
const legacy = { id: fixture.heartbeatRunId, status: "failed", errorCode: "adapter_failed",
error: 'Failed query: select "token" from "secrets" where "id" = $1\nparams: sk-secret', resultJson: { failureCause: "40001" } };
const [listed] = await registry.redactForRuns(fixture.companyId, [legacy]);
expect(listed).toMatchObject({ id: fixture.heartbeatRunId, error: "Database query failed (40001)", resultJson: { failureCause: "40001" } });
expect(await registry.redactForRun(fixture.companyId, fixture.heartbeatRunId, legacy))
.toMatchObject({ error: "Database query failed (40001)" });
const plain = { id: fixture.heartbeatRunId, error: "Adapter failed" };
expect((await registry.redactForRuns(fixture.companyId, [plain]))[0]).toEqual(plain);
});
it("denies low-trust, task-bridge, and skill-test callers on both routes", async () => {
const lowTrust = await seedAgentRun({
trustPreset: LOW_TRUST_REVIEW_PRESET,
authorizationPolicy: { trustBoundary: { mode: LOW_TRUST_REVIEW_PRESET, projectIds: [randomUUID()] } },
});
const standard = await seedAgentRun();
const cases = [
{ name: "low trust", fixture: lowTrust, scope: { kind: "standard" } as const, source: "agent_jwt" as const },
{ name: "task bridge", fixture: standard, scope: { kind: "task_bridge", parentIssueId: randomUUID() } as const, source: "agent_key" as const },
{ name: "skill test", fixture: standard, scope: { kind: "skill_test", issueId: randomUUID() } as const, source: "agent_jwt" as const },
];
for (const testCase of cases) {
expect(
(await request(createApp(testCase.fixture, testCase.scope, testCase.source)).get("/api/agents/me/secrets")).status,
`${testCase.name} list`,
).toBe(403);
expect(
(await request(createApp(testCase.fixture, testCase.scope, testCase.source)).post("/api/agents/me/secrets/ANY/value")).status,
`${testCase.name} fetch`,
).toBe(403);
}
});
});