mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
fix(redaction): preserve SigV4 presigned upload URLs in tool results (#22959)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Tool results flow through `validateToolContent`, `redactSensitiveText`, and `redactCommandText` before reaching the agent > - `COMMAND_ENV_SECRET_ASSIGNMENT_RE` matched `X-Amz-Credential` and `X-Amz-Security-Token` inside AWS SigV4 presigned URLs and consumed the rest of the URL, wiping `X-Amz-Signature` > - Agents received truncated upload URLs and could not execute signed S3/R2 `PUT` uploads returned by MCP tools > - This pull request extracts a focused SigV4 helper that temporarily sets aside validated `X-Amz-Credential` and `X-Amz-Security-Token` parameters inside complete HTTPS SigV4 presigned queries before command redaction, while keeping request-identity hashing and approval encryption sensitive for those URLs > - The benefit is that agents receive usable short-lived presigned upload links while percent-encoded or malformed secrets, other secret parameters, secret-named assignments, incomplete queries, placeholder collisions, and retried write idempotency keys remain safe ## Linked Issues or Issue Description - Refs #14014 ## What Changed - Extracted `packages/adapter-utils/src/sigv4-presigned-url.ts` to detect complete HTTPS SigV4 presigned queries (`X-Amz-Algorithm=AWS4-HMAC-SHA256`, valid SigV4 `X-Amz-Credential` scope, `X-Amz-Date`, numeric `X-Amz-Expires`, `X-Amz-SignedHeaders`, and 64-hex `X-Amz-Signature`), including single- and double-escaped `\u0026` query separators and trailing markdown/prose delimiters. - Validated raw and iteratively percent-decoded `X-Amz-Credential` and `X-Amz-Security-Token` values against canonical decoded shapes and shared standalone secret token patterns (`sk-`, `gh*_`, `github_pat_`, Stripe `sk_`/`rk_` keys, JWTs), failing closed on malformed/deeply nested percent-encoding and private-use placeholder collisions. - Updated `packages/adapter-utils/src/command-redaction.ts` to delegate SigV4 parameter protection to `protectSigV4PresignedUrlParameters` and keep `collectDiagnosticEnvironmentSecrets` treating SigV4 presigned URLs as private. - Updated `server/src/services/tool-content-guards.ts` (`containsSensitiveToolArguments`) to keep SigV4 presigned URLs classified as sensitive for `toolRequestIdentityHash` (preserving HMAC `side_effect:v2` idempotency keys across deploys) and `signToolArguments` (keeping v2 A256GCM encryption at rest). - Added unit and end-to-end tests in `packages/adapter-utils/src/command-redaction.test.ts` and `server/src/__tests__/tool-content-guards.test.ts` covering complete SigV4 URLs, percent-encoded/double-encoded/malformed smuggled secrets, sibling secret redaction, model-classifier parity, and HMAC identity/approval encryption stability. ## Verification - `pnpm vitest run packages/adapter-utils/src/command-redaction.test.ts server/src/__tests__/tool-content-guards.test.ts server/src/__tests__/redaction.test.ts server/src/__tests__/remote-mcp-redaction.test.ts` — passed (`4` files, `143` tests). - `pnpm --filter @paperclipai/adapter-utils typecheck && pnpm --filter @paperclipai/adapter-utils build && pnpm --filter @paperclipai/server typecheck` — passed (all 7 server typecheck layers). - `pnpm verify` — exited with code `2` because graph worker `@paperclipai/server` hit `SIGKILL` under local memory pressure; required CI covers the broad suite. - Verified end-to-end via `validateToolContent` (`server/src/services/tool-content-guards.ts`) with a realistic MCP presigned upload response: complete S3 SigV4 URLs arrive intact while sibling `apiKey`/`Authorization: Bearer` secrets and percent-encoded smuggled secrets are redacted, and `toolRequestIdentityHash` / `signToolArguments` remain HMAC-keyed and v2-encrypted. ## Risks - Complete HTTPS SigV4 presigned URLs remain visible in tool results, audit summaries, and transcripts until their short expiry window (`X-Amz-Expires`). Incomplete SigV4 queries, non-SigV4 parameters, secret-named assignments/CLI flags/JSON keys, percent-encoded/malformed smuggled tokens, and placeholder collisions fail closed. ## Model Used - Antigravity AI coding assistant (Google DeepMind agentic runtime, extended reasoning with local tool execution and verification). ## 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
This commit is contained in:
1 parent
7b446b4504
commit
bff0f6dab5
5 files changed
+371
-3
No files matched your search
@@ -252,3 +252,109 @@ describe("diagnostic environment secret selection", () => {
|
||||
.toEqual(new Set([url, "private%20password", "private password"]));
|
||||
});
|
||||
});
|
||||
|
||||
describe("SigV4 presigned URLs", () => {
|
||||
const signature = "0123456789abcdef".repeat(4);
|
||||
const query = [
|
||||
"X-Amz-Algorithm=AWS4-HMAC-SHA256",
|
||||
"X-Amz-Content-Sha256=UNSIGNED-PAYLOAD",
|
||||
"X-Amz-Credential=ASIAEXAMPLEKEYID0001%2F20261118%2Fus-east-1%2Fs3%2Faws4_request",
|
||||
"X-Amz-Date=20261118T063600Z",
|
||||
"X-Amz-Expires=900",
|
||||
"X-Amz-Security-Token=IQoJb3JpZ2luEXAMPLESESSION%2Ftoken%2Bvalue%3D",
|
||||
`X-Amz-Signature=${signature}`,
|
||||
"X-Amz-SignedHeaders=host",
|
||||
"x-id=PutObject",
|
||||
];
|
||||
const presignedUrl = `https://uploads-example.s3.us-east-1.amazonaws.com/receipts/r-1.pdf?${query.join("&")}`;
|
||||
|
||||
it("keeps an upload link from a JSON tool result, shell command, or markdown link usable", () => {
|
||||
const result = JSON.stringify({ receiptId: "r-1", uploadUrl: presignedUrl });
|
||||
expect(redactCommandText(result)).toBe(result);
|
||||
expect(redactDiagnosticText(result)).toBe(result);
|
||||
expect(redactCommandText(`curl -X PUT --upload-file r.pdf '${presignedUrl}'`))
|
||||
.toBe(`curl -X PUT --upload-file r.pdf '${presignedUrl}'`);
|
||||
expect(redactCommandText(`[upload receipt](${presignedUrl})`))
|
||||
.toBe(`[upload receipt](${presignedUrl})`);
|
||||
});
|
||||
|
||||
it("keeps a link whose query separators are JSON-escaped or double-escaped", () => {
|
||||
const escaped = presignedUrl.replaceAll("&", "\\u0026");
|
||||
expect(redactCommandText(`{"uploadUrl":"${escaped}"}`)).toBe(`{"uploadUrl":"${escaped}"}`);
|
||||
const doubleEscaped = presignedUrl.replaceAll("&", "\\\\u0026");
|
||||
expect(redactCommandText(`{\\"uploadUrl\\":\\"${doubleEscaped}\\"}`)).toBe(`{\\"uploadUrl\\":\\"${doubleEscaped}\\"}`);
|
||||
});
|
||||
|
||||
it("still redacts other secret parameters inside a presigned URL", () => {
|
||||
const url = presignedUrl.replace("&X-Amz-Signature", "&api_token=extra-secret&X-Amz-Signature");
|
||||
const output = redactCommandText(url);
|
||||
expect(output).not.toContain("extra-secret");
|
||||
expect(output).toContain("X-Amz-Credential=ASIAEXAMPLEKEYID0001");
|
||||
});
|
||||
|
||||
it("still hides a presigned URL assigned to a secret name", () => {
|
||||
for (const input of [`UPLOAD_TOKEN=${presignedUrl}`, `tool --token ${presignedUrl}`]) {
|
||||
const output = redactCommandText(input);
|
||||
expect(output).not.toContain("X-Amz-Security-Token=IQoJ");
|
||||
expect(output).not.toContain(signature);
|
||||
}
|
||||
expect(redactDiagnosticText(JSON.stringify({ token: presignedUrl }))).toBe(
|
||||
`{"token":"${REDACTED_COMMAND_TEXT_VALUE}"}`,
|
||||
);
|
||||
});
|
||||
|
||||
it("still redacts the credential parameters when the URL is not a complete SigV4 query or collides with placeholders", () => {
|
||||
const unsigned = presignedUrl.replace(`&X-Amz-Signature=${signature}`, "");
|
||||
expect(redactCommandText(unsigned)).not.toContain("X-Amz-Security-Token=IQoJ");
|
||||
const missingDate = presignedUrl.replace("&X-Amz-Date=20261118T063600Z", "");
|
||||
expect(redactCommandText(missingDate)).not.toContain("X-Amz-Security-Token=IQoJ");
|
||||
const missingSignedHeaders = presignedUrl.replace("&X-Amz-SignedHeaders=host", "");
|
||||
expect(redactCommandText(missingSignedHeaders)).not.toContain("X-Amz-Security-Token=IQoJ");
|
||||
const badScope = presignedUrl.replace(
|
||||
"X-Amz-Credential=ASIAEXAMPLEKEYID0001%2F20261118%2Fus-east-1%2Fs3%2Faws4_request",
|
||||
"X-Amz-Credential=not-a-sigv4-scope",
|
||||
);
|
||||
expect(redactCommandText(badScope)).not.toContain("not-a-sigv4-scope");
|
||||
const spoofed = `${presignedUrl} ${String.fromCharCode(0xe000)}0${String.fromCharCode(0xe001)}`;
|
||||
expect(redactCommandText(spoofed)).not.toContain("X-Amz-Security-Token=IQoJ");
|
||||
});
|
||||
|
||||
it("still redacts standalone, percent-encoded, or malformed secrets smuggled inside SigV4 parameters", () => {
|
||||
const jwt =
|
||||
"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
|
||||
const smuggledTokenValues = [
|
||||
["sk", "smuggledsecret123456"].join("-"),
|
||||
"%73k-smuggledsecret123456",
|
||||
"sk%2Dsmuggledsecret123456",
|
||||
"%2573k-smuggledsecret123456",
|
||||
["ghp", "smuggledtoken123456789012345"].join("_"),
|
||||
"ghp%5Fsmuggledtoken123456789012345",
|
||||
["github", "pat", "smuggledtoken123456789012345"].join("_"),
|
||||
["sk", "live", "smuggledstripekey12345678"].join("_"),
|
||||
"sk%5Flive%5Fsmuggledstripekey12345678",
|
||||
jwt,
|
||||
jwt.replaceAll(".", "%2E"),
|
||||
"Authorization%3A%20Bearer%20secretvalue",
|
||||
"%E0%A4%A",
|
||||
];
|
||||
for (const badValue of smuggledTokenValues) {
|
||||
const url = presignedUrl.replace(
|
||||
"X-Amz-Security-Token=IQoJb3JpZ2luEXAMPLESESSION%2Ftoken%2Bvalue%3D",
|
||||
`X-Amz-Security-Token=${badValue}`,
|
||||
);
|
||||
expect(redactCommandText(url)).not.toContain(badValue);
|
||||
}
|
||||
|
||||
for (const badKeyId of ["%73k-smuggledsecret123456", "ghp%5Fsmuggledtoken123456789012345", "%E0%A4%A"]) {
|
||||
const url = presignedUrl.replace(
|
||||
"X-Amz-Credential=ASIAEXAMPLEKEYID0001%2F20261118%2Fus-east-1%2Fs3%2Faws4_request",
|
||||
`X-Amz-Credential=${badKeyId}%2F20261118%2Fus-east-1%2Fs3%2Faws4_request`,
|
||||
);
|
||||
expect(redactCommandText(url)).not.toContain(badKeyId);
|
||||
}
|
||||
});
|
||||
|
||||
it("still collects a SigV4 presigned URL as private in diagnostic environment secrets", () => {
|
||||
expect(collectDiagnosticEnvironmentSecrets({ PUBLIC_KEY: presignedUrl })).toEqual([presignedUrl]);
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,9 @@
|
||||
import {
|
||||
containsSigV4PresignedUrl,
|
||||
protectSigV4PresignedUrlParameters,
|
||||
} from "./sigv4-presigned-url.js";
|
||||
|
||||
export { containsSigV4PresignedUrl };
|
||||
export const REDACTED_COMMAND_TEXT_VALUE = "***REDACTED***";
|
||||
|
||||
// Public Executor helper addresses retained for callers of this predicate.
|
||||
@@ -32,8 +38,13 @@ const COMMAND_ENV_SECRET_ASSIGNMENT_RE = new RegExp(
|
||||
);
|
||||
const COMMAND_AUTHORIZATION_BEARER_RE =
|
||||
/(\bAuthorization\s*:\s*Bearer\s+)[^\s"'`]+/gi;
|
||||
const COMMAND_OPENAI_KEY_RE = /\bsk-[A-Za-z0-9_-]{12,}\b/g;
|
||||
const COMMAND_GITHUB_TOKEN_RE = /\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g;
|
||||
const COMMAND_OPENAI_KEY_SOURCE = String.raw`\bsk-[A-Za-z0-9_-]{12,}\b`;
|
||||
const COMMAND_GITHUB_TOKEN_SOURCE = String.raw`\bgh[pousr]_[A-Za-z0-9_]{20,}\b`;
|
||||
const COMMAND_OPENAI_KEY_RE = new RegExp(COMMAND_OPENAI_KEY_SOURCE, "g");
|
||||
const COMMAND_GITHUB_TOKEN_RE = new RegExp(COMMAND_GITHUB_TOKEN_SOURCE, "g");
|
||||
const STANDALONE_SECRET_TOKEN_RE = new RegExp(
|
||||
`${COMMAND_OPENAI_KEY_SOURCE}|${COMMAND_GITHUB_TOKEN_SOURCE}|\\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\\b|\\bgithub_pat_[A-Za-z0-9_]{20,}\\b`,
|
||||
);
|
||||
const COMMAND_JWT_RE =
|
||||
/\b(?<![A-Za-z0-9_]-*)[A-Za-z0-9_-]{8,}(?:\.[A-Za-z0-9_-]{8,}){2}(?:\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,})?\b/g;
|
||||
/** Recognize encoded JSON headers, without treating dotted identifiers as tokens. */
|
||||
@@ -83,11 +94,25 @@ function maybeContainsSecretText(command: string) {
|
||||
);
|
||||
}
|
||||
|
||||
function containsStandaloneSecretToken(value: string): boolean {
|
||||
if (STANDALONE_SECRET_TOKEN_RE.test(value)) return true;
|
||||
const jwtMatches = value.match(COMMAND_JWT_RE);
|
||||
return jwtMatches !== null && jwtMatches.some(looksLikeCredentialJwt);
|
||||
}
|
||||
|
||||
export function redactCommandText(
|
||||
command: string,
|
||||
redactedValue = REDACTED_COMMAND_TEXT_VALUE,
|
||||
): string {
|
||||
if (!maybeContainsSecretText(command)) return command;
|
||||
const { text, restore } = protectSigV4PresignedUrlParameters(
|
||||
command,
|
||||
containsStandaloneSecretToken,
|
||||
);
|
||||
return restore(redactSetAsideCommandText(text, redactedValue));
|
||||
}
|
||||
|
||||
function redactSetAsideCommandText(command: string, redactedValue: string): string {
|
||||
return command
|
||||
.replace(COMMAND_AUTHORIZATION_BEARER_RE, `$1${redactedValue}`)
|
||||
.replace(COMMAND_CLI_SECRET_OPTION_RE, `$1${redactedValue}$3`)
|
||||
@@ -252,6 +277,7 @@ export function collectDiagnosticEnvironmentSecrets(
|
||||
for (const [key, value] of Object.entries(env)) {
|
||||
if (typeof value !== "string" || !value) continue;
|
||||
if (declared.has(key) || secretName.test(key) ||
|
||||
containsSigV4PresignedUrl(value) ||
|
||||
redactDiagnosticText(value) !== value || looksLikeCredentialJwt(value) ||
|
||||
/-----BEGIN (?:[A-Z]+ )*PRIVATE KEY-----/.test(value) ||
|
||||
(!isOrdinaryDiagnosticEnvSetting(key, value) && (!options.hostProcess || plausibleUndeclaredCredential(key, value)))) {
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
// An AWS SigV4 presigned URL is a short-lived capability for one operation on
|
||||
// one object, which a tool returns on purpose (for example a receipt upload
|
||||
// link). Its `X-Amz-Credential` (access key ID and scope) and
|
||||
// `X-Amz-Security-Token` (an STS session token, unusable without the secret
|
||||
// key) match the secret-name rule, and the unquoted value then hides the rest
|
||||
// of the URL, so the link cannot be used. Inside a complete SigV4 query only,
|
||||
// these two parameters are set aside before redaction and put back after it.
|
||||
// Every other parameter is redacted as before, and a URL that is itself the
|
||||
// value of a secret-named assignment or option is still hidden whole.
|
||||
const PRESIGNED_URL_RE = /https:\/\/(?:[^\s"'`<>\\]|\\{1,2}u0026)+/gi;
|
||||
const PRESIGNED_URL_TRAILING_DELIMITERS_RE = /[)\]}.,;]+$/;
|
||||
const PRESIGNED_QUERY_SEPARATOR_RE = /(&|\\{1,2}u0026)/i;
|
||||
|
||||
const SIGV4_CREDENTIAL_RAW_RE =
|
||||
/^X-Amz-Credential=(?:[A-Za-z0-9._~+-]|%(?!2[Ff])[0-9A-Fa-f]{2})+(?:%2F|\/)\d{8}(?:%2F|\/)[A-Za-z0-9_-]+(?:%2F|\/)[A-Za-z0-9_-]+(?:%2F|\/)aws4_request$/i;
|
||||
const SIGV4_CREDENTIAL_DECODED_VALUE_RE =
|
||||
/^[A-Za-z0-9._~+-]+\/\d{8}\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+\/aws4_request$/i;
|
||||
const SIGV4_SECURITY_TOKEN_RAW_RE =
|
||||
/^X-Amz-Security-Token=(?:[A-Za-z0-9+/._~-]|%[0-9A-Fa-f]{2})+=*$/i;
|
||||
const SIGV4_SECURITY_TOKEN_DECODED_VALUE_RE = /^[A-Za-z0-9+/._~-]+=*$/;
|
||||
|
||||
// Private-use placeholders. Text that already contains them is left to the normal rules.
|
||||
const KEPT_START = String.fromCharCode(0xe000);
|
||||
const KEPT_END = String.fromCharCode(0xe001);
|
||||
const KEPT_PLACEHOLDER_RE = new RegExp(`${KEPT_START}(\\d+)${KEPT_END}`, "g");
|
||||
|
||||
const MAX_PERCENT_DECODE_PASSES = 4;
|
||||
|
||||
function decodeQueryValueVariants(rawValue: string): string[] | null {
|
||||
const variants = [rawValue];
|
||||
let current = rawValue;
|
||||
for (let pass = 0; pass < MAX_PERCENT_DECODE_PASSES; pass += 1) {
|
||||
if (!current.includes("%")) return variants;
|
||||
let decoded: string;
|
||||
try {
|
||||
decoded = decodeURIComponent(current);
|
||||
} catch {
|
||||
// Malformed percent-encoding fails closed.
|
||||
return null;
|
||||
}
|
||||
if (decoded === current) return variants;
|
||||
variants.push(decoded);
|
||||
current = decoded;
|
||||
}
|
||||
// Reject deeply nested percent-encoding so obfuscated values fail closed.
|
||||
return current.includes("%") ? null : variants;
|
||||
}
|
||||
|
||||
export function isSigV4PresignedQuery(parameters: string[]): boolean {
|
||||
return (
|
||||
parameters.some((part) => /^X-Amz-Algorithm=AWS4-HMAC-SHA256$/i.test(part)) &&
|
||||
parameters.some((part) => SIGV4_CREDENTIAL_RAW_RE.test(part)) &&
|
||||
parameters.some((part) => /^X-Amz-Date=\d{8}T\d{6}Z$/i.test(part)) &&
|
||||
parameters.some((part) => /^X-Amz-Expires=\d+$/i.test(part)) &&
|
||||
parameters.some((part) => /^X-Amz-SignedHeaders=[^=&\s]+$/i.test(part)) &&
|
||||
parameters.some((part) => /^X-Amz-Signature=[0-9a-f]{64}$/i.test(part))
|
||||
);
|
||||
}
|
||||
|
||||
function isKeptSigV4Parameter(
|
||||
part: string,
|
||||
containsSecretToken: (value: string) => boolean,
|
||||
): boolean {
|
||||
const isCredential = SIGV4_CREDENTIAL_RAW_RE.test(part);
|
||||
const isSecurityToken = !isCredential && SIGV4_SECURITY_TOKEN_RAW_RE.test(part);
|
||||
if (!isCredential && !isSecurityToken) return false;
|
||||
|
||||
const rawValue = part.slice(part.indexOf("=") + 1);
|
||||
const variants = decodeQueryValueVariants(rawValue);
|
||||
if (!variants) return false;
|
||||
|
||||
const finalDecoded = variants[variants.length - 1];
|
||||
const decodedShapeOk = isCredential
|
||||
? SIGV4_CREDENTIAL_DECODED_VALUE_RE.test(finalDecoded)
|
||||
: SIGV4_SECURITY_TOKEN_DECODED_VALUE_RE.test(finalDecoded);
|
||||
if (!decodedShapeOk) return false;
|
||||
|
||||
return !variants.some(containsSecretToken);
|
||||
}
|
||||
|
||||
function splitPresignedUrlCandidate(match: string) {
|
||||
const trailingMatch = PRESIGNED_URL_TRAILING_DELIMITERS_RE.exec(match);
|
||||
const trailing = trailingMatch ? trailingMatch[0] : "";
|
||||
const url = trailing ? match.slice(0, -trailing.length) : match;
|
||||
const queryStart = url.indexOf("?");
|
||||
if (queryStart < 0) return null;
|
||||
// The capture group keeps each separator at an odd index.
|
||||
const parts = url.slice(queryStart + 1).split(PRESIGNED_QUERY_SEPARATOR_RE);
|
||||
if (!isSigV4PresignedQuery(parts.filter((_, index) => index % 2 === 0))) {
|
||||
return null;
|
||||
}
|
||||
return { url, queryStart, parts, trailing };
|
||||
}
|
||||
|
||||
export function containsSigV4PresignedUrl(text: string): boolean {
|
||||
if (!/X-Amz-Signature=/i.test(text)) return false;
|
||||
for (const match of text.matchAll(PRESIGNED_URL_RE)) {
|
||||
if (splitPresignedUrlCandidate(match[0]) !== null) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function protectSigV4PresignedUrlParameters(
|
||||
text: string,
|
||||
containsSecretToken: (value: string) => boolean,
|
||||
): { text: string; restore: (redacted: string) => string } {
|
||||
if (
|
||||
!/X-Amz-Signature=/i.test(text) ||
|
||||
text.includes(KEPT_START) ||
|
||||
text.includes(KEPT_END)
|
||||
) {
|
||||
return { text, restore: (redacted) => redacted };
|
||||
}
|
||||
const kept: string[] = [];
|
||||
const protectedText = text.replace(PRESIGNED_URL_RE, (match) => {
|
||||
const parsed = splitPresignedUrlCandidate(match);
|
||||
if (!parsed) return match;
|
||||
const { url, queryStart, parts, trailing } = parsed;
|
||||
return (
|
||||
url.slice(0, queryStart + 1) +
|
||||
parts
|
||||
.map((part, index) =>
|
||||
index % 2 === 0 && isKeptSigV4Parameter(part, containsSecretToken)
|
||||
? `${KEPT_START}${kept.push(part) - 1}${KEPT_END}`
|
||||
: part,
|
||||
)
|
||||
.join("") +
|
||||
trailing
|
||||
);
|
||||
});
|
||||
return {
|
||||
text: protectedText,
|
||||
restore: (redacted) =>
|
||||
kept.length === 0
|
||||
? redacted
|
||||
: redacted.replace(
|
||||
KEPT_PLACEHOLDER_RE,
|
||||
(match, index: string) => kept[Number(index)] ?? match,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -265,6 +265,93 @@ describe("tool content guards", () => {
|
||||
expect(result.findings).toContain("sensitive_value");
|
||||
});
|
||||
|
||||
it("returns a SigV4 presigned upload link from an MCP tool result unchanged while redacting sibling secrets", async () => {
|
||||
const uploadUrl = "https://uploads-example.s3.us-east-1.amazonaws.com/receipts/r-1.pdf?" + [
|
||||
"X-Amz-Algorithm=AWS4-HMAC-SHA256",
|
||||
"X-Amz-Content-Sha256=UNSIGNED-PAYLOAD",
|
||||
"X-Amz-Credential=ASIAEXAMPLEKEYID0001%2F20261118%2Fus-east-1%2Fs3%2Faws4_request",
|
||||
"X-Amz-Date=20261118T063600Z",
|
||||
"X-Amz-Expires=900",
|
||||
"X-Amz-Security-Token=IQoJb3JpZ2luEXAMPLESESSION%2Ftoken%2Bvalue%3D",
|
||||
`X-Amz-Signature=${"0123456789abcdef".repeat(4)}`,
|
||||
"X-Amz-SignedHeaders=host",
|
||||
"x-id=PutObject",
|
||||
].join("&");
|
||||
const value = { content: [{ type: "text", text: JSON.stringify({ receiptId: "r-1", uploadUrl }) }] };
|
||||
|
||||
const classifier = vi.fn(async (_content: string) => safeModel);
|
||||
const result = await validateToolContent({
|
||||
value,
|
||||
direction: "result",
|
||||
sensitiveMode: "redact",
|
||||
promptInjectionMode: "block",
|
||||
classifier,
|
||||
});
|
||||
|
||||
expect(result.value).toEqual(value);
|
||||
expect(result.findings).not.toContain("sensitive_value");
|
||||
expect(result.detectorMetadata?.detector).toBe("model");
|
||||
expect(classifier).toHaveBeenCalledTimes(1);
|
||||
|
||||
// JSON-escaped query separators also survive double serialization in summaries.
|
||||
const escapedValue = {
|
||||
content: [{ type: "text", text: `{"receiptId":"r-1","uploadUrl":"${uploadUrl.replaceAll("&", "\\u0026")}"}` }],
|
||||
};
|
||||
const escapedResult = await validateToolContent({
|
||||
value: escapedValue,
|
||||
direction: "result",
|
||||
sensitiveMode: "redact",
|
||||
promptInjectionMode: "block",
|
||||
});
|
||||
expect(escapedResult.value).toEqual(escapedValue);
|
||||
expect(escapedResult.findings).not.toContain("sensitive_value");
|
||||
|
||||
// Sibling secrets in the same MCP tool result remain redacted.
|
||||
const mixed = {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: JSON.stringify({ receiptId: "r-1", uploadUrl, apiKey: "sk-sibling-secret-123456" }),
|
||||
}],
|
||||
};
|
||||
const mixedResult = await validateToolContent({
|
||||
value: mixed,
|
||||
direction: "result",
|
||||
sensitiveMode: "redact",
|
||||
promptInjectionMode: "block",
|
||||
});
|
||||
const delivered = JSON.parse((mixedResult.value as { content: Array<{ text: string }> }).content[0].text);
|
||||
expect(delivered.uploadUrl).toBe(uploadUrl);
|
||||
expect(delivered.apiKey).toBe("***REDACTED***");
|
||||
expect(mixedResult.findings).toContain("sensitive_value");
|
||||
|
||||
// Request identity hashing and approval encryption stay keyed/encrypted for
|
||||
// arguments containing a SigV4 presigned URL so retried side-effecting calls
|
||||
// preserve their HMAC-based idempotency keys across deploys.
|
||||
const argsWithPresignedUrl = { uploadUrl };
|
||||
const canonical = canonicalToolArguments(argsWithPresignedUrl);
|
||||
const expectedHmac = createHmac("sha256", signingSecret)
|
||||
.update("paperclip:tool-request-identity:v1\0")
|
||||
.update(canonical)
|
||||
.digest("hex");
|
||||
expect(toolRequestIdentityHash(argsWithPresignedUrl, signingSecret)).toBe(expectedHmac);
|
||||
expect(toolRequestIdentityHash(argsWithPresignedUrl, signingSecret)).not.toBe(
|
||||
createHash("sha256").update(canonical).digest("hex"),
|
||||
);
|
||||
const signed = signToolArguments({
|
||||
invocationId: "invocation-sigv4",
|
||||
toolName: "upload_receipt",
|
||||
canonicalArguments: canonical,
|
||||
signingSecret,
|
||||
});
|
||||
expect(JSON.parse(Buffer.from(signed, "base64url").toString("utf8")).version).toBe(2);
|
||||
expect(readSignedToolArguments({
|
||||
signedArguments: signed,
|
||||
invocationId: "invocation-sigv4",
|
||||
toolName: "upload_receipt",
|
||||
signingSecret,
|
||||
})).toEqual(argsWithPresignedUrl);
|
||||
});
|
||||
|
||||
it("blocks prompt injection in tool results before returning to the agent", async () => {
|
||||
await expect(
|
||||
validateToolContent({
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { containsSigV4PresignedUrl } from "@paperclipai/adapter-utils/command-redaction";
|
||||
import type { PromptInjectionModelOutcome, PromptInjectionDetectorMetadata } from "@paperclipai/shared";
|
||||
import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { redactEventPayload, redactSensitiveText, REDACTED_EVENT_VALUE } from "../redaction.js";
|
||||
@@ -114,7 +115,14 @@ function containsSensitiveToolArguments(canonicalArguments: string) {
|
||||
const value: unknown = JSON.parse(canonicalArguments);
|
||||
// Wrapping preserves recursive redaction for root arrays and strings too.
|
||||
const redacted = redactEventPayload({ value })?.value;
|
||||
return redactSensitiveText(stableSerialize(redacted)) !== stableSerialize(value);
|
||||
const serialized = stableSerialize(value);
|
||||
// Keep SigV4 presigned URLs classified as sensitive for request identity
|
||||
// hashing and approval encryption so side-effect idempotency keys stay
|
||||
// stable across display-redaction changes and bearer URLs stay encrypted.
|
||||
return (
|
||||
containsSigV4PresignedUrl(serialized) ||
|
||||
redactSensitiveText(stableSerialize(redacted)) !== serialized
|
||||
);
|
||||
} catch {
|
||||
// Canonical arguments normally come from canonicalToolArguments. Never
|
||||
// persist an unparseable caller-supplied string as an unencrypted fallback.
|
||||
|
||||
Reference in new issue
Block a user