Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(logs): redact credentials from logs MCP responses (#119426)

posthog[bot]0abc7a975714
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
index 1f0ccf8e3461..3059da1020af 100644
--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md
@@ -639,6 +639,8 @@ Product teams own their definitions and control which operations are exposed as
`src/tools/featureFlags/updateFeatureFlagHooks.ts` is the reference.
Do not shadow a generated tool with a hand-written tool of the same name.
+ The Logs tools use `logs/redactCredentialsHooks` to mask credentials in response strings and structured fields. This covers credential parameters, JSON and header values, URL passwords, bearer tokens, and private PostHog tokens. Nested URL encoding and JSON escaping do not bypass masking. The hook preserves unrelated text, except that strings with more than eight encoding layers are masked in full to bound parsing work. It does not change stored logs or responses outside MCP.
+
#### Typed-confirm paradigm for destructive tools
For destructive or security-sensitive tools (account changes, key revocation, bulk deletes),
diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yaml
index 422d536d5608..7f2c9732fb3c 100644
--- a/products/logs/mcp/tools.yaml
+++ b/products/logs/mcp/tools.yaml
@@ -347,6 +347,7 @@ tools:
Defaults to attribute_type "log" (log-level attributes). To get values for resource-level attributes (e.g.
service.name, k8s.pod.name), you MUST explicitly pass attribute_type: "resource". Accepts optional
serviceNames, dateRange, and filterGroup to narrow which logs are scanned.
+ hooks: logs/redactCredentialsHooks
response:
include:
- results
@@ -412,6 +413,7 @@ tools:
idempotent: true
title: Facet log counts
description_file: ./prompts/logs-facet-values.md
+ hooks: logs/redactCredentialsHooks
response:
include:
- results
@@ -441,6 +443,7 @@ tools:
idempotent: true
title: Mine log patterns
description_file: ./prompts/logs-patterns.md
+ hooks: logs/redactCredentialsHooks
response:
exclude:
- patterns.*.examples
@@ -459,6 +462,7 @@ tools:
idempotent: true
title: Diff log patterns between two windows
description_file: ./prompts/logs-patterns-diff.md
+ hooks: logs/redactCredentialsHooks
response:
exclude:
- entries.*.pattern.pattern
@@ -508,6 +512,7 @@ tools:
title: Query logs
description_file: ./prompts/query-logs.md
system_prompt_hint: Log filtering by severity/service/attribute
+ hooks: logs/redactCredentialsHooks
reads_ingested_data: events
response:
include:
diff --git a/services/mcp/src/lib/credential-redaction.ts b/services/mcp/src/lib/credential-redaction.ts
new file mode 100644
index 000000000000..3b7a8e31e1ef
--- /dev/null
+++ b/services/mcp/src/lib/credential-redaction.ts
@@ -0,0 +1,172 @@
+import { assignKey, isRecord } from '@/lib/plain-object'
+
+const REDACTED_VALUE = '[REDACTED]'
+const MAX_ENCODING_LAYERS = 8
+const CREDENTIAL_NAME_FRAGMENTS = ['apikey', 'token', 'secret', 'password', 'passwd', 'credential', 'signature']
+const CREDENTIAL_NAMES = new Set(['key', 'pwd', 'auth', 'authorization', 'sig', 'code', 'jwt', 'session', 'sessionid'])
+
+const ASSIGNMENT_PATTERN =
+ /(?:^|(?<=[?&;\s{,("'\\]))(?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'|([A-Za-z0-9_%.[\]-]+))\s*([=:])\s*/g
+const QUOTED_VALUE_PATTERN = /^("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/
+const URL_PASSWORD_PATTERN = /\b[a-z][a-z\d+.-]*:\/\/[^\s/"'<>\\]*@/gi
+// Project tokens (phc_) are public; these prefixes identify private tokens in posthog/models/utils.py.
+const POSTHOG_TOKEN_PATTERN = /\b(?:phx|phs|pha|phr)_([A-Za-z0-9_-]{16,})/g
+const BEARER_PATTERN = /\bBearer\s+([^\s"'\\,;}]+)/gi
+const ESCAPE_PATTERN = /%([0-9a-f]{2})|\\u([0-9a-f]{4})|\\(["'\\/])/gi
+
+function decodeEscape(
+ _match: string,
+ percent: string | undefined,
+ unicode: string | undefined,
+ escaped: string
+): string {
+ return percent || unicode ? String.fromCharCode(Number.parseInt(percent || unicode!, 16)) : escaped
+}
+
+function isCredentialName(name: string): boolean {
+ let decoded = name
+ let layers = 0
+ for (;;) {
+ const next = decoded.replace(ESCAPE_PATTERN, decodeEscape)
+ if (next === decoded) {
+ break
+ }
+ if (++layers > MAX_ENCODING_LAYERS) {
+ return true
+ }
+ decoded = next
+ }
+ const normalized = decoded.toLowerCase().replace(/[^a-z0-9]/g, '')
+ return CREDENTIAL_NAMES.has(normalized) || CREDENTIAL_NAME_FRAGMENTS.some((part) => normalized.includes(part))
+}
+
+interface RedactionRange {
+ start: number
+ end: number
+}
+
+function containerLength(text: string): number {
+ let depth = 0
+ for (const match of text.matchAll(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[{}[\]]/g)) {
+ if (match[0] === '{' || match[0] === '[') {
+ depth++
+ } else if (match[0] === '}' || match[0] === ']') {
+ if (--depth === 0) {
+ return match.index + 1
+ }
+ }
+ }
+ return text.length
+}
+
+function findCredentialRanges(text: string): RedactionRange[] {
+ const ranges: RedactionRange[] = []
+ for (const match of text.matchAll(ASSIGNMENT_PATTERN)) {
+ if (!isCredentialName(match[1] ?? match[2] ?? match[3]!)) {
+ continue
+ }
+ const start = match.index + match[0].length
+ const rest = text.slice(start)
+ const quoted = rest.match(QUOTED_VALUE_PATTERN)
+ if (quoted) {
+ ranges.push({ start: start + 1, end: start + quoted[0].length - 1 })
+ } else if (/^[{[]/.test(rest)) {
+ ranges.push({ start, end: start + containerLength(rest) })
+ } else {
+ const value = rest.startsWith(REDACTED_VALUE)
+ ? REDACTED_VALUE
+ : rest.match(match[4] === '=' ? /^(?:\\(?!["'])|[^&;\s"'\\#<>])+/ : /^[^\r\n,}\]]+/)?.[0].trimEnd()
+ if (value) {
+ ranges.push({ start, end: start + value.length })
+ }
+ }
+ }
+ for (const match of text.matchAll(URL_PASSWORD_PATTERN)) {
+ const userInfoStart = match.index + match[0].indexOf('://') + 3
+ const passwordStart = text.indexOf(':', userInfoStart)
+ const end = match.index + match[0].length - 1
+ if (passwordStart >= userInfoStart && passwordStart < end) {
+ ranges.push({ start: passwordStart + 1, end })
+ }
+ }
+ for (const pattern of [POSTHOG_TOKEN_PATTERN, BEARER_PATTERN]) {
+ for (const match of text.matchAll(pattern)) {
+ const end = match.index + match[0].length
+ ranges.push({ start: end - match[1]!.length, end })
+ }
+ }
+ return ranges
+}
+
+export function redactCredentialsInText(text: string): string {
+ const ranges: RedactionRange[] = []
+ let decoded = text
+ let offsets = Array.from({ length: text.length + 1 }, (_, index) => index)
+ let layers = 0
+ for (;;) {
+ for (const range of findCredentialRanges(decoded)) {
+ ranges.push({ start: offsets[range.start]!, end: offsets[range.end]! })
+ }
+
+ // Keep original offsets so decoding reveals nested credentials without rewriting unrelated log content.
+ const nextOffsets: number[] = []
+ let previous = 0
+ const next = decoded.replace(ESCAPE_PATTERN, (match, percent, unicode, escaped, index: number) => {
+ for (let i = previous; i <= index; i++) {
+ nextOffsets.push(offsets[i]!)
+ }
+ previous = index + match.length
+ return decodeEscape(match, percent, unicode, escaped)
+ })
+ if (next === decoded) {
+ break
+ }
+ // Bound decoding work on untrusted logs; excessive nesting must not expose credentials.
+ if (++layers > MAX_ENCODING_LAYERS) {
+ return REDACTED_VALUE
+ }
+ for (let i = previous; i < offsets.length; i++) {
+ nextOffsets.push(offsets[i]!)
+ }
+ decoded = next
+ offsets = nextOffsets
+ }
+
+ const merged: RedactionRange[] = []
+ for (const range of ranges.sort((a, b) => a.start - b.start)) {
+ const last = merged.at(-1)
+ if (last && range.start <= last.end) {
+ last.end = Math.max(last.end, range.end)
+ } else {
+ merged.push({ ...range })
+ }
+ }
+ let result = ''
+ let previous = 0
+ for (const { start, end } of merged) {
+ result += text.slice(previous, start) + REDACTED_VALUE
+ previous = end
+ }
+ return result + text.slice(previous)
+}
+
+export function redactCredentials(value: unknown): unknown {
+ if (typeof value === 'string') {
+ return redactCredentialsInText(value)
+ }
+ if (Array.isArray(value)) {
+ return value.map(redactCredentials)
+ }
+ if (isRecord(value)) {
+ const redacted: Record<string, unknown> = {}
+ for (const [key, entry] of Object.entries(value)) {
+ assignKey(
+ redacted,
+ redactCredentialsInText(key),
+ isCredentialName(key) ? REDACTED_VALUE : redactCredentials(entry)
+ )
+ }
+ return redacted
+ }
+ return value
+}
diff --git a/services/mcp/src/tools/generated/logs.ts b/services/mcp/src/tools/generated/logs.ts
index d7d02d02ca94..663a902e499e 100644
--- a/services/mcp/src/tools/generated/logs.ts
+++ b/services/mcp/src/tools/generated/logs.ts
@@ -3,6 +3,12 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/logs/api'
+import hooks_logsAttributeValuesList from '@/tools/logs/redactCredentialsHooks'
+import hooks_logsFacetValuesCreate from '@/tools/logs/redactCredentialsHooks'
+import hooks_logsPatterns from '@/tools/logs/redactCredentialsHooks'
+import hooks_logsPatternsDiff from '@/tools/logs/redactCredentialsHooks'
+import hooks_queryLogs from '@/tools/logs/redactCredentialsHooks'
+import { withToolHooks } from '@/tools/tool-hooks'
import { withPostHogUrl, pickResponseFields, omitResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
@@ -559,23 +565,26 @@ const logsAttributeValuesList = (): ToolBase<
> => ({
name: 'logs-attribute-values-list',
schema: LogsAttributeValuesListSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof LogsAttributeValuesListSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas._LogsValuesResponse>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/values/`,
- query: {
- attribute_type: params.attribute_type,
- dateRange: params.dateRange,
- filterGroup: params.filterGroup,
- key: params.key,
- serviceNames: params.serviceNames,
- value: params.value,
- },
- })
- const filtered = pickResponseFields(result, ['results']) as typeof result
- return filtered
- },
+ handler: withToolHooks(
+ hooks_logsAttributeValuesList,
+ async (context: Context, params: z.infer<ReturnType<typeof LogsAttributeValuesListSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas._LogsValuesResponse>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/values/`,
+ query: {
+ attribute_type: params.attribute_type,
+ dateRange: params.dateRange,
+ filterGroup: params.filterGroup,
+ key: params.key,
+ serviceNames: params.serviceNames,
+ value: params.value,
+ },
+ })
+ const filtered = pickResponseFields(result, ['results']) as typeof result
+ return filtered
+ }
+ ),
})
const LogsAttributesListSchema = () => {
@@ -670,20 +679,23 @@ const logsFacetValuesCreate = (): ToolBase<
> => ({
name: 'logs-facet-values-create',
schema: LogsFacetValuesCreateSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof LogsFacetValuesCreateSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.query !== undefined) {
- body['query'] = params.query
- }
- const result = await context.api.request<Schemas._LogsFacetValuesResponse>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/facet_values/`,
- body,
- })
- const filtered = pickResponseFields(result, ['results']) as typeof result
- return filtered
- },
+ handler: withToolHooks(
+ hooks_logsFacetValuesCreate,
+ async (context: Context, params: z.infer<ReturnType<typeof LogsFacetValuesCreateSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.query !== undefined) {
+ body['query'] = params.query
+ }
+ const result = await context.api.request<Schemas._LogsFacetValuesResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/facet_values/`,
+ body,
+ })
+ const filtered = pickResponseFields(result, ['results']) as typeof result
+ return filtered
+ }
+ ),
})
const LogsGroupBySchema = () => {
@@ -718,26 +730,29 @@ const LogsPatternsSchema = () => {
const logsPatterns = (): ToolBase<ReturnType<typeof LogsPatternsSchema>, Schemas._LogsPatternsResponse> => ({
name: 'logs-patterns',
schema: LogsPatternsSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof LogsPatternsSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.query !== undefined) {
- body['query'] = params.query
- }
- const result = await context.api.request<Schemas._LogsPatternsResponse>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/patterns/`,
- body,
- })
- const filtered = omitResponseFields(result, [
- 'patterns.*.examples',
- 'patterns.*.sparkline',
- 'patterns.*.count',
- 'patterns.*.error_count',
- 'sparkline_buckets',
- ]) as typeof result
- return filtered
- },
+ handler: withToolHooks(
+ hooks_logsPatterns,
+ async (context: Context, params: z.infer<ReturnType<typeof LogsPatternsSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.query !== undefined) {
+ body['query'] = params.query
+ }
+ const result = await context.api.request<Schemas._LogsPatternsResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/patterns/`,
+ body,
+ })
+ const filtered = omitResponseFields(result, [
+ 'patterns.*.examples',
+ 'patterns.*.sparkline',
+ 'patterns.*.count',
+ 'patterns.*.error_count',
+ 'sparkline_buckets',
+ ]) as typeof result
+ return filtered
+ }
+ ),
})
const LogsPatternsDiffSchema = () => {
@@ -751,30 +766,33 @@ const logsPatternsDiff = (): ToolBase<
> => ({
name: 'logs-patterns-diff',
schema: LogsPatternsDiffSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof LogsPatternsDiffSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.query !== undefined) {
- body['query'] = params.query
- }
- if (params.baselineDateRange !== undefined) {
- body['baselineDateRange'] = params.baselineDateRange
- }
- const result = await context.api.request<Schemas._LogsPatternsDiffResponse>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/patterns_diff/`,
- body,
- })
- const filtered = omitResponseFields(result, [
- 'entries.*.pattern.pattern',
- 'entries.*.pattern.services',
- 'entries.*.pattern.examples',
- 'entries.*.pattern.sparkline',
- 'entries.*.pattern.count',
- 'entries.*.pattern.error_count',
- ]) as typeof result
- return filtered
- },
+ handler: withToolHooks(
+ hooks_logsPatternsDiff,
+ async (context: Context, params: z.infer<ReturnType<typeof LogsPatternsDiffSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.query !== undefined) {
+ body['query'] = params.query
+ }
+ if (params.baselineDateRange !== undefined) {
+ body['baselineDateRange'] = params.baselineDateRange
+ }
+ const result = await context.api.request<Schemas._LogsPatternsDiffResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/patterns_diff/`,
+ body,
+ })
+ const filtered = omitResponseFields(result, [
+ 'entries.*.pattern.pattern',
+ 'entries.*.pattern.services',
+ 'entries.*.pattern.examples',
+ 'entries.*.pattern.sparkline',
+ 'entries.*.pattern.count',
+ 'entries.*.pattern.error_count',
+ ]) as typeof result
+ return filtered
+ }
+ ),
})
const LogsServicesCreateSchema = () => {
@@ -847,20 +865,23 @@ const QueryLogsSchema = () => {
const queryLogs = (): ToolBase<ReturnType<typeof QueryLogsSchema>, Schemas._LogsQueryResponse> => ({
name: 'query-logs',
schema: QueryLogsSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof QueryLogsSchema>>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.query !== undefined) {
- body['query'] = params.query
- }
- const result = await context.api.request<Schemas._LogsQueryResponse>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/query/`,
- body,
- })
- const filtered = pickResponseFields(result, ['results']) as typeof result
- return filtered
- },
+ handler: withToolHooks(
+ hooks_queryLogs,
+ async (context: Context, params: z.infer<ReturnType<typeof QueryLogsSchema>>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.query !== undefined) {
+ body['query'] = params.query
+ }
+ const result = await context.api.request<Schemas._LogsQueryResponse>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/logs/query/`,
+ body,
+ })
+ const filtered = pickResponseFields(result, ['results']) as typeof result
+ return filtered
+ }
+ ),
})
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
diff --git a/services/mcp/src/tools/logs/redactCredentialsHooks.ts b/services/mcp/src/tools/logs/redactCredentialsHooks.ts
new file mode 100644
index 000000000000..04cca53bcdd8
--- /dev/null
+++ b/services/mcp/src/tools/logs/redactCredentialsHooks.ts
@@ -0,0 +1,10 @@
+import { redactCredentials } from '@/lib/credential-redaction'
+import type { ToolHooks } from '@/tools/tool-hooks'
+import type { Context } from '@/tools/types'
+
+// Log bodies and attribute values are application text, so they can carry credentials the field filters cannot reach.
+function afterResponse(_context: Context, _params: unknown, result: unknown): unknown {
+ return redactCredentials(result)
+}
+
+export default { afterResponse } satisfies ToolHooks<unknown>
diff --git a/services/mcp/tests/unit/credential-redaction.test.ts b/services/mcp/tests/unit/credential-redaction.test.ts
new file mode 100644
index 000000000000..3551641d1102
--- /dev/null
+++ b/services/mcp/tests/unit/credential-redaction.test.ts
@@ -0,0 +1,214 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { redactCredentials, redactCredentialsInText } from '@/lib/credential-redaction'
+import { GENERATED_TOOLS } from '@/tools/generated/logs'
+import redactCredentialsHooks from '@/tools/logs/redactCredentialsHooks'
+import type { Context } from '@/tools/types'
+
+// Invented values. None of them is a real credential.
+const PERSONAL_KEY = 'phx_INVENTEDpersonalKEY0000000000000000'
+const OTHER_SECRET = 'INVENTEDsecret1111'
+
+describe('credential redaction', () => {
+ it.each([
+ {
+ name: 'a query parameter in a URL',
+ input: `GET https://app.example.com/api/flags?personal_api_key=${OTHER_SECRET}&limit=10`,
+ expected: 'GET https://app.example.com/api/flags?personal_api_key=[REDACTED]&limit=10',
+ },
+ {
+ name: 'a request URL inside a JSON-encoded body',
+ input: `{"request":"https://app.example.com/decide?v=3&access_token=${OTHER_SECRET}","status":200}`,
+ expected: '{"request":"https://app.example.com/decide?v=3&access_token=[REDACTED]","status":200}',
+ },
+ {
+ name: 'an escaped JSON string',
+ input: `{\\"url\\":\\"/hook?Client_Secret=${OTHER_SECRET}\\"}`,
+ expected: '{\\"url\\":\\"/hook?Client_Secret=[REDACTED]\\"}',
+ },
+ {
+ name: 'a percent-encoded nested URL',
+ input: `/login?next=https%3A%2F%2Fexample.com%2Fcb%3Fstate%3D1%26token%3D${OTHER_SECRET}%26a%3Db`,
+ expected: '/login?next=https%3A%2F%2Fexample.com%2Fcb%3Fstate%3D1%26token%3D[REDACTED]%26a%3Db',
+ },
+ {
+ name: 'a bare form body',
+ input: `body: password=${OTHER_SECRET}&user=jo`,
+ expected: 'body: password=[REDACTED]&user=jo',
+ },
+ {
+ name: 'a PostHog personal API key outside a parameter',
+ input: `Authorization: Bearer ${PERSONAL_KEY}`,
+ expected: 'Authorization: [REDACTED]',
+ },
+ {
+ name: 'the first parameter in a nested URL',
+ input: `/login?next=https%3A%2F%2Fexample.com%2Fcb%3Ftoken%3D${OTHER_SECRET}`,
+ expected: '/login?next=https%3A%2F%2Fexample.com%2Fcb%3Ftoken%3D[REDACTED]',
+ },
+ {
+ name: 'complete values containing encoded separators and commas',
+ input: `/cb?password=INVENTED%26secret,1111&limit=10`,
+ expected: '/cb?password=[REDACTED]&limit=10',
+ },
+ {
+ name: 'encoded parameter names',
+ input: `/cb?access%5Ftoken=${OTHER_SECRET}&safe=1`,
+ expected: '/cb?access%5Ftoken=[REDACTED]&safe=1',
+ },
+ {
+ name: 'multiple nested encoding levels',
+ input: `/cb?next=https%253A%252F%252Fexample.com%252F%253Faccess%255Ftoken%253Dsecret%252526suffix%2526safe%253D1`,
+ expected:
+ '/cb?next=https%253A%252F%252Fexample.com%252F%253Faccess%255Ftoken%253D[REDACTED]%2526safe%253D1',
+ },
+ {
+ name: 'JSON credentials including escaped quotes',
+ input: String.raw`{"api_key":"secret\"suffix","safe":"keep","credentials.password":"another secret"}`,
+ expected: '{"api_key":"[REDACTED]","safe":"keep","credentials.password":"[REDACTED]"}',
+ },
+ {
+ name: 'JSON credentials inside an escaped JSON string',
+ input: JSON.stringify({ body: JSON.stringify({ password: 'secret with spaces', safe: 'keep' }) }),
+ expected: JSON.stringify({ body: JSON.stringify({ password: '[REDACTED]', safe: 'keep' }) }),
+ },
+ {
+ name: 'JSON unicode escapes in credential names',
+ input: String.raw`{"access\u005ftoken":"secret","safe":true}`,
+ expected: String.raw`{"access\u005ftoken":"[REDACTED]","safe":true}`,
+ },
+ {
+ name: 'headers and YAML credential fields',
+ input: 'Authorization: Bearer generic-secret\r\nX-Api-Key: key with spaces\nclient_secret: yaml-secret\nsafe: keep',
+ expected: 'Authorization: [REDACTED]\r\nX-Api-Key: [REDACTED]\nclient_secret: [REDACTED]\nsafe: keep',
+ },
+ {
+ name: 'a form body inside a JSON string',
+ input: '{"body":"password=secret&safe=1"}',
+ expected: '{"body":"password=[REDACTED]&safe=1"}',
+ },
+ {
+ name: 'backslashes inside a parameter value',
+ input: '/?password=secret\\suffix&safe=1',
+ expected: '/?password=[REDACTED]&safe=1',
+ },
+ {
+ name: 'whitespace around a form assignment',
+ input: 'password = secret&safe=1',
+ expected: 'password = [REDACTED]&safe=1',
+ },
+ {
+ name: 'URL passwords with encoded and literal delimiters',
+ input: 'postgres://service:secret%26suffix,[email protected]/db https://user:[email protected]/path',
+ expected: 'postgres://service:[REDACTED]@example.com/db https://user:[REDACTED]@example.com/path',
+ },
+ {
+ name: 'a bearer token outside a header',
+ input: 'request failed with Bearer generic-secret',
+ expected: 'request failed with Bearer [REDACTED]',
+ },
+ {
+ name: 'a private PostHog token outside a header',
+ input: `key supplied: ${PERSONAL_KEY}`,
+ expected: 'key supplied: phx_[REDACTED]',
+ },
+ {
+ name: 'credential containers without masking adjacent JSON fields',
+ input: '{"credentials":{"password":"secret","nested":["another"]},"safe":"keep"}',
+ expected: '{"credentials":[REDACTED],"safe":"keep"}',
+ },
+ {
+ name: 'an existing redaction marker',
+ input: 'Authorization: [REDACTED]\n/?password=[REDACTED]&safe=1',
+ expected: 'Authorization: [REDACTED]\n/?password=[REDACTED]&safe=1',
+ },
+ {
+ name: 'excessively nested encoding',
+ input: Array.from({ length: 10 }).reduce<string>((value) => encodeURIComponent(value), '/?token=secret'),
+ expected: '[REDACTED]',
+ },
+ {
+ name: 'unrelated text and encoding',
+ input: String.raw`{"message":"keyword=shoes monkey=1","url":"https://example.com/a%2Fb?next=hello%20world&limit=10","safe":"a\"b"}`,
+ expected: String.raw`{"message":"keyword=shoes monkey=1","url":"https://example.com/a%2Fb?next=hello%20world&limit=10","safe":"a\"b"}`,
+ },
+ {
+ name: 'safe parameters and a public project token',
+ input: '/e?ip=1&ver=1.2&keyword=shoes&monkey=1&api_host=phc_INVENTEDprojectTOKEN00000',
+ expected: '/e?ip=1&ver=1.2&keyword=shoes&monkey=1&api_host=phc_INVENTEDprojectTOKEN00000',
+ },
+ ])('masks $name', ({ input, expected }) => {
+ expect(redactCredentialsInText(input)).toBe(expected)
+ })
+
+ it('masks structured credential fields without mutating the response', () => {
+ const input = { attributes: { authorization: 'Bearer secret', password: ['secret'], safe: 42 }, body: null }
+
+ expect(redactCredentials(input)).toEqual({
+ attributes: { authorization: '[REDACTED]', password: '[REDACTED]', safe: 42 },
+ body: null,
+ })
+ expect(input.attributes.authorization).toBe('Bearer secret')
+ })
+
+ it('masks credentials in every string of a logs response', async () => {
+ const result = {
+ results: [
+ {
+ uuid: 'log-1',
+ body: JSON.stringify({ url: `https://example.com/api?personal_api_key=${PERSONAL_KEY}` }),
+ attributes: { 'http.url': `/v1?apikey=${OTHER_SECRET}` },
+ },
+ ],
+ entries: [{ pattern: { template: `GET /api?token=${OTHER_SECRET} <*>` } }],
+ }
+
+ const redacted = await redactCredentialsHooks.afterResponse({} as Context, {}, result)
+
+ expect(redacted).toEqual({
+ results: [
+ {
+ uuid: 'log-1',
+ body: '{"url":"https://example.com/api?personal_api_key=[REDACTED]"}',
+ attributes: { 'http.url': '/v1?apikey=[REDACTED]' },
+ },
+ ],
+ entries: [{ pattern: { template: 'GET /api?token=[REDACTED] <*>' } }],
+ })
+ })
+
+ it.each([
+ {
+ tool: 'query-logs',
+ response: { results: [{ body: 'Authorization: Bearer secret' }] },
+ expected: { results: [{ body: 'Authorization: [REDACTED]' }] },
+ },
+ {
+ tool: 'logs-patterns',
+ response: { patterns: [{ template: '/?token=secret' }] },
+ expected: { patterns: [{ template: '/?token=[REDACTED]' }] },
+ },
+ {
+ tool: 'logs-patterns-diff',
+ response: { entries: [{ pattern: { template: 'https://user:[email protected]/' } }] },
+ expected: { entries: [{ pattern: { template: 'https://user:[REDACTED]@example.com/' } }] },
+ },
+ {
+ tool: 'logs-attribute-values-list',
+ response: { results: ['/?access%5Ftoken=secret'] },
+ expected: { results: ['/?access%5Ftoken=[REDACTED]'] },
+ },
+ {
+ tool: 'logs-facet-values-create',
+ response: { results: [{ value: '{"password":"secret"}', count: 2 }] },
+ expected: { results: [{ value: '{"password":"[REDACTED]"}', count: 2 }] },
+ },
+ ])('redacts responses through the generated $tool handler', async ({ tool, response, expected }) => {
+ const context = {
+ stateManager: { getProjectId: vi.fn().mockResolvedValue(1) },
+ api: { request: vi.fn().mockResolvedValue(response) },
+ } as unknown as Context
+
+ expect(await GENERATED_TOOLS[tool]!().handler(context, {})).toEqual(expected)
+ })
+})