Files
PaperClipAI/packages/adapter-utils/src/command-redaction.test.ts
T
DottaandPaperclip 6ec4180ea1 fix: preserve ordinary diagnostic text during environment secret redaction (#19461)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Run diagnostics help operators find the cause of a failed agent run.
> - The failure reporter treated unknown environment settings as
credentials.
> - It replaced every use of those values in diagnostic text.
> - A flag set to `1`, `2`, or `safe` removed parts of dates, model
names, versions, and normal words.
> - This pull request preserves explicit ordinary settings and keeps
unknown values private.
> - Operators can read the failure details while real credentials stay
masked.

## Linked Issues or Issue Description

**What happened?**

Run-failure contexts contained redaction markers inside timestamps,
model names, driver versions, and the word "safely". Provider failure
diagnostics used the same broad environment-value rule.

**Expected behavior**

Ordinary flags, counts, paths, regions, and mode labels leave diagnostic
text readable. API keys, URL passwords, and declared secret bindings
remain masked.

**Steps to reproduce**

1. Set ordinary environment settings to `1`, `2`, and `safe`.
2. Report a failed native run with a timestamp, `gpt-6.1-sol`,
`phase6-v2`, and "safely" in its details.
3. Inspect the run failure report. Before this fix, unrelated fragments
are replaced.

Related work: #13668 addresses a separate model-ID false positive.
#11311 and #15524 address credential capture at other boundaries. This
change keeps the existing command scanner and registered-secret
replacement.

## What Changed

- Add a shared environment selector in adapter-utils. Keep unknown
values private. Exempt explicit ordinary process settings, typed flags
and counts, mode labels, and key selectors.
- Use the same selector for run-failure reports and inherited provider
failure environments. Keep one policy for both consumers.
- Keep configured provider bindings private because that API does not
carry separate secret-reference metadata.
- Preserve short declared secrets, unknown opaque values, encoded
credentials, and inherited Bedrock tokens. Add regressions for ordinary
`SORT_KEY` values and both Bedrock consumers.
- Add screenshot-shaped regressions, real database reporter coverage,
and credential tests.
- Document the policy in `doc/observability.md`. The optional monitoring
gate stays in place.

## Verification

Linux, Node v25.9.0, pnpm 9.15.4. The published tree matches the tested
local tree `cb236f072cca195e4c2cfb4034c7cc06ea7adbc5`.

- Before the fix, four diagnostic regressions failed. The output
reproduced the damaged timestamp, model, version, and word.
- Review regressions: six tests failed on the first revision. They
proved the missed Bedrock token, opaque inherited-value exposure, and
key-selector false positive. All pass after the correction.
- 555 focused tests pass on the final source tree.
- `cd server && pnpm exec vitest run
src/services/__tests__/run-failure-diagnostics.test.ts
src/__tests__/redaction.test.ts src/__tests__/redact-sensitive.test.ts
src/__tests__/run-secret-redaction.test.ts`: 206 passed.
- `cd server && pnpm exec vitest run
src/services/__tests__/run-failure-report.test.ts`: 289 passed, with
real embedded PostgreSQL.
- `pnpm exec vitest run
packages/adapter-utils/src/command-redaction.test.ts
packages/adapter-utils/src/acpx-engine/terminal-session-failure.test.ts`:
60 passed.
- `pnpm --filter @paperclipai/adapter-utils typecheck`: passed.
- `git diff --check`: passed.
- The first reporter attempt could not load the unbuilt plugin SDK. It
passed after `pnpm --filter @paperclipai/plugin-sdk ensure-build-deps`.
- The filtered install omitted the CLI tsx loader, so `pnpm verify
--explain` could not start. The equivalent verifier entry points ran
with the installed server loader and returned exit 2: broader CI
coverage is required for the observability document.
- Full local build/typecheck and browser suites were not duplicated.
[Final-revision
CI](https://github.com/paperclipai/paperclip/actions/runs/42231412547)
passed on `013960a4c6fa6279e1f28b0f6af5f036d7cad5a7`, attempt 1. This
includes typecheck, build, general/server/chat tests, serialized suites,
Runner checks, eight E2E shards, and the canary dry run.
- [Greptile
review](https://github.com/paperclipai/paperclip/pull/19461#issuecomment-6686592783)
scored this head 5/5 with zero new findings. All four inline threads are
resolved. The security rescan and Snyk status passed. The PR has no
merge conflicts.

## Risks

- Ordinary-setting exemptions need a known name or a name/value type
rule. Unknown opaque values remain private. Declared secret bindings and
recognizable credentials override these exemptions.
- A real short secret still masks matching fragments. Removing that
protection would expose the secret.
- Existing stored redaction markers cannot restore their original text.
This fix applies when new diagnostics are produced.
- No migration, dependency, workflow, authorization, or default
monitoring changes.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. This change is a focused bug
fix.

## Model Used

OpenAI GPT-6, through Codex, with shell execution and file tools. The
host does not expose the exact runtime variant or context window size.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-06 09:01:55 -06:00

231 lines
10 KiB
TypeScript

import { describe, expect, it } from "vitest";
describe("explicit diagnostic credential forms", () => {
it("masks suffixed CLI options and encoded JSON headers with whitespace", () => {
const jwt = `${Buffer.from(' {"alg":"HS256","typ":"JWT"}').toString("base64url")}.abcdefghijk.abcdefghijkl`;
expect(redactCommandText("tool --api-key-prod sensitivevalue --token-policy readable"))
.not.toContain("sensitivevalue");
expect(redactCommandText(`provider ${jwt}`)).not.toContain(jwt);
expect(redactCommandText("plan.security.credentials.md")).toBe("plan.security.credentials.md");
});
});
import {
REDACTED_COMMAND_TEXT_VALUE,
collectDiagnosticEnvironmentSecrets,
looksLikeCredentialJwt,
redactDiagnosticText,
redactCommandText,
} from "./command-redaction.js";
describe("looksLikeCredentialJwt", () => {
it("recognizes encoded headers even with short payloads and signatures", () => {
const header = Buffer.from('{"alg":"HS256"}').toString("base64url");
expect(looksLikeCredentialJwt(`${header}.e30.c2ln`)).toBe(true);
});
it("recognizes direct-encryption JWTs with an empty encrypted-key segment", () => {
const header = Buffer.from('{"alg":"dir","enc":"A256GCM"}').toString("base64url");
expect(looksLikeCredentialJwt(`${header}..abcdefghijk.abcdefghijkl.abcdefghijk`)).toBe(true);
});
it.each([
"eyJ..signature",
"eyJ.key..ciphertext.tag",
"eyJ.key.iv..tag",
"eyJ.key.iv.ciphertext.",
])("rejects empty segments outside the JWE encrypted key: %s", (input) => {
expect(looksLikeCredentialJwt(input)).toBe(false);
});
it.each([
"api.openai.com",
"agents.staging.example.com",
"deployment.credentials.example.md",
"paperclip.native-model-envelope.v3",
])("rejects public dotted identifiers: %s", (input) => {
expect(looksLikeCredentialJwt(input)).toBe(false);
});
});
describe("redactDiagnosticText", () => {
it("preserves credential metadata and dotted identifiers", () => {
for (const text of [
'"tokenBudget":4000 --token-budget 4000 SECRET_STORAGE=vault',
'{"credentialHandling":"harness","authorizationRequired":true}',
"executor.customTools.integrations.list deployment.credentials.example.md api.openai.com",
"Use a private key and secret manager with credential handling.",
"Use bearer tokens and bearer authentication.",
]) expect(redactDiagnosticText(text)).toBe(text);
});
it("redacts a JSON secret field value", () => {
const input = '{"token":"opaque-value","status":"error"}';
const output = redactDiagnosticText(input);
expect(output).not.toContain("opaque-value");
expect(output).toContain(`"token":"${REDACTED_COMMAND_TEXT_VALUE}"`);
// The non-secret field keeps its value.
expect(output).toContain('"status":"error"');
});
it("redacts an api_key JSON field with whitespace around the colon", () => {
const input = '{ "api_key" : "sk-secret-123" }';
const output = redactDiagnosticText(input);
expect(output).not.toContain("sk-secret-123");
expect(output).toContain(REDACTED_COMMAND_TEXT_VALUE);
});
it("redacts an escaped-JSON secret field value", () => {
// A diagnostic can carry a JSON string, so the double quotes appear as `\"`.
const input = '{\\"token\\":\\"opaque-value\\"}';
const output = redactDiagnosticText(input);
expect(output).not.toContain("opaque-value");
expect(output).toContain(
`\\"token\\":\\"${REDACTED_COMMAND_TEXT_VALUE}\\"`,
);
});
it("still redacts a shell KEY=value secret", () => {
const input = "ANTHROPIC_API_KEY=super-secret-value claude --print";
const output = redactDiagnosticText(input);
expect(output).not.toContain("super-secret-value");
expect(output).toContain(REDACTED_COMMAND_TEXT_VALUE);
});
it("redacts an escaped quoted assignment across a literal newline", () => {
const input = String.raw`authorization=\"Bearer first-line
second-line\" status=401`;
const expected = String.raw`authorization=\"***REDACTED***\" status=401`;
const output = redactDiagnosticText(input);
expect(output).toBe(expected);
expect(redactDiagnosticText(output)).toBe(expected);
});
it("keeps non-secret text and non-secret JSON fields intact", () => {
const input = '{"status":"ok","message":"probe finished"}';
expect(redactDiagnosticText(input)).toBe(input);
});
it("redacts the secret but keeps a non-secret marker in the same string", () => {
const input = 'DIAGMARKER1234 said {"authorization":"Bearer opaque"}';
const output = redactDiagnosticText(input);
expect(output).toContain("DIAGMARKER1234");
expect(output).not.toContain("opaque");
});
it("redacts a JSON secret value that contains an escaped quote", () => {
// The value holds an escaped quote, so a naive matcher stops at the `\"` and
// leaves the rest of the credential. The marker sits after the escaped quote.
const input = '{"token":"pre\\"MARKERQUOTE_A"}';
const output = redactDiagnosticText(input);
expect(output).not.toContain("MARKERQUOTE_A");
expect(output).toContain(`"token":"${REDACTED_COMMAND_TEXT_VALUE}"`);
});
it("redacts a JSON secret value that contains an escaped backslash", () => {
const input = '{"secret":"pre\\\\MARKERBACKSLASH_A"}';
const output = redactDiagnosticText(input);
expect(output).not.toContain("MARKERBACKSLASH_A");
expect(output).toContain(`"secret":"${REDACTED_COMMAND_TEXT_VALUE}"`);
});
it("redacts an escaped-JSON secret value that contains an escaped quote", () => {
// A diagnostic can carry a serialized JSON string, so the whole JSON is
// escaped a second time. The inner value still holds an escaped quote.
const innerJson = '{"token":"pre\\"MARKERQUOTE_B"}';
const input = JSON.stringify(innerJson);
const output = redactDiagnosticText(input);
expect(output).not.toContain("MARKERQUOTE_B");
expect(output).toContain(REDACTED_COMMAND_TEXT_VALUE);
});
it("redacts an escaped-JSON secret value that contains an escaped backslash", () => {
const innerJson = '{"password":"pre\\\\MARKERBACKSLASH_B"}';
const input = JSON.stringify(innerJson);
const output = redactDiagnosticText(input);
expect(output).not.toContain("MARKERBACKSLASH_B");
expect(output).toContain(REDACTED_COMMAND_TEXT_VALUE);
});
});
describe("redactCommandText on long runs", () => {
const jwt =
"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
function redactWithinTimeBudget(input: string) {
const startedAt = performance.now();
const output = redactCommandText(input);
expect(performance.now() - startedAt).toBeLessThan(1_000);
return output;
}
it("keeps redacting options, assignments, and tokens inside dash-separated runs", () => {
const cases = [
["x--token flag-secret", `x--token ${REDACTED_COMMAND_TEXT_VALUE}`],
["--x--token flag-secret", `--x--token ${REDACTED_COMMAND_TEXT_VALUE}`],
[
"a-b--api-key=assigned-secret --password 'quoted-secret'",
`a-b--api-key=${REDACTED_COMMAND_TEXT_VALUE} --password '${REDACTED_COMMAND_TEXT_VALUE}'`,
],
["prefix-MY_API_KEY=env-secret", `prefix-MY_API_KEY=${REDACTED_COMMAND_TEXT_VALUE}`],
[`--${jwt}`, `--${REDACTED_COMMAND_TEXT_VALUE}`],
[`session=${jwt}`, `session=${REDACTED_COMMAND_TEXT_VALUE}`],
["my-token is here", "my-token is here"],
];
for (const [input, expected] of cases) {
expect(redactCommandText(input)).toBe(expected);
}
});
it("scans long letter/digit and dash-separated runs in linear time", () => {
const base64Url = Buffer.from(Array.from({ length: 90_000 }, (_, index) => (index * 7919) % 256)).toString("base64url");
for (const run of ["a".repeat(120_000), "a-".repeat(60_000), "a--".repeat(40_000), base64Url]) {
expect(redactWithinTimeBudget(`${run} --token run-secret`)).toBe(`${run} --token ${REDACTED_COMMAND_TEXT_VALUE}`);
expect(redactWithinTimeBudget(`${run}--token run-secret`)).toBe(`${run}--token ${REDACTED_COMMAND_TEXT_VALUE}`);
}
});
});
describe("diagnostic environment secret selection", () => {
it("does not infer secrets from ordinary configuration values", () => {
expect(collectDiagnosticEnvironmentSecrets({
FEATURE_FLAG: "1", WORKER_COUNT: "2", MODE: "safe", REGION: "us-east-1",
NODE_ENV: "production", HOME: "/home/operator", PORT: "3100", MAX_TOKENS: "4096",
PUBLIC_KEY_PATH: "/workspace/key.pem", KEYBOARD_LAYOUT: "us",
SORT_KEY: "created_at", CACHE_KEY: "cache-v1", ROUTING_KEY: "jobs",
PARTITION_KEY: "tenant_id", IDEMPOTENCY_KEY: "operation-123", PUBLIC_KEY: "public-material",
})).toEqual([]);
});
it.each(["API_KEY", "KEY", "ACCESS_TOKEN", "AWS_SECRET_ACCESS_KEY", "AWS_ACCESS_KEY_ID",
"CLIENT_SECRET", "PASSWORD", "AUTHORIZATION", "PRIVATE_KEY", "API_KEY_PRODUCTION", "AWS_BEARER_TOKEN_BEDROCK"])(
"keeps short credentials private under %s", key => {
expect(collectDiagnosticEnvironmentSecrets({ [key]: "1" })).toEqual(["1"]);
},
);
it("recognizes credential content and declared bindings under arbitrary names", () => {
const jwt = `${Buffer.from('{"alg":"HS256"}').toString("base64url")}.e30.c2ln`;
const pem = "-----BEGIN PRIVATE KEY-----\nprivate-canary\n-----END PRIVATE KEY-----";
const key = "sk-fixturecredential12345";
const selected = collectDiagnosticEnvironmentSecrets({ A: jwt, B: pem, C: key, D: "safe", FEATURE_FLAG: "false" }, ["D"]);
expect(new Set(selected)).toEqual(new Set([jwt, pem, key, "safe"]));
});
it("keeps unknown opaque values private without declarations", () => {
expect(collectDiagnosticEnvironmentSecrets({ CUSTOM_BINDING: "opaque-host-secret" })).toEqual(["opaque-host-secret"]);
});
it("does not exempt credentials on ordinary-setting names", () => {
expect(collectDiagnosticEnvironmentSecrets({ SORT_KEY: "opaque-secret", FEATURE_FLAG: "1" }, ["SORT_KEY", "FEATURE_FLAG"]))
.toEqual(["opaque-secret", "1"]);
});
it("extracts encoded URL passwords and deduplicates selected values", () => {
const url = "postgres://user:private%20password@db.test/database";
expect(new Set(collectDiagnosticEnvironmentSecrets({ DATABASE_URL: url, PASSWORD: "private password" })))
.toEqual(new Set([url, "private%20password", "private password"]));
});
});