-
-
Notifications
You must be signed in to change notification settings - Fork 14
fix(telemetry): redact credentials from CLI diagnostics #1640
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| /** | ||
| * Stateless credential redaction for CLI diagnostics and telemetry. | ||
| * Kept free of SDK imports for CLI startup and the completion fast path. | ||
| * Successful API responses are not passed through this redactor. | ||
| */ | ||
|
|
||
| const INVALID_BEARER_HEADER_START = | ||
| /(\bHeaders\.(?:set|append):[ \t]*)(\\*["'])Bearer[ \t]+/gi; | ||
| const INVALID_HEADER_END = /(?<!\\)(\\*["']) is an invalid header value/gi; | ||
| // Header validation errors quote the entire value, including invalid newlines. | ||
| // The end-of-string alternative also covers messages truncated by the SDK. | ||
| const QUOTED_CREDENTIAL = | ||
| /(?<!\\)(\\*["'])(Bearer[ \t]+|sntry[su]_)[\s\S]*?(?:\1|$)/gi; | ||
| /** Control characters can also appear escaped in serialized diagnostics. */ | ||
| const ESCAPED_CONTROL = /\\+(?:[nrtbfv]|u00[01][\da-f]|u007f|u202[89])/.source; | ||
| const BEARER_PART = String.raw`(?:${ESCAPED_CONTROL}[ \t]*|\\+[^"'\s\\]|[^\s"'\\])`; | ||
| // An explicit Bearer context can contain opaque tokens with punctuation. | ||
| // Quotes (including JSON-escaped quotes) delimit the diagnostic string. | ||
| const BEARER_CREDENTIAL = new RegExp( | ||
| String.raw`\bBearer[ \t]+${BEARER_PART}+(?:(?:\r\n|(?! )[\s\x00-\x1f\x7f-\x9f])[ \t]*${BEARER_PART}+)*`, | ||
| "gi" | ||
| ); | ||
| const SENTRY_CREDENTIAL = new RegExp( | ||
| String.raw`\bsntry[su]_[A-Za-z0-9._~+/=-]+(?:(?:\r\n|(?! )[\s\x00-\x1f\x7f-\x9f]|${ESCAPED_CONTROL})[ \t]*[A-Za-z0-9._~+/=-]+)*`, | ||
| "gi" | ||
| ); | ||
|
|
||
| /** | ||
| * Use the runtime's final delimiter because an invalid token can contain quotes. | ||
| * This may also hide text between concatenated diagnostics with the same quote: | ||
| * the runtime does not distinguish a delimiter inside a token from its end. | ||
| * Index suffixes once so repeated header prefixes cannot cause quadratic scans. | ||
| */ | ||
| function redactInvalidBearerHeaders(text: string): string { | ||
| const lastEnds = new Map<string, number>(); | ||
| for (const match of text.matchAll(INVALID_HEADER_END)) { | ||
| const quote = match[1]; | ||
| if (quote) { | ||
| lastEnds.set(quote, match.index); | ||
| } | ||
| } | ||
| if (lastEnds.size === 0) { | ||
| return text; | ||
| } | ||
|
|
||
| const parts: string[] = []; | ||
| let cursor = 0; | ||
| for (const match of text.matchAll(INVALID_BEARER_HEADER_START)) { | ||
| if (match.index < cursor) { | ||
| continue; | ||
| } | ||
| const [, prefix, quote] = match; | ||
| if (!(prefix && quote)) { | ||
| continue; | ||
| } | ||
| const end = lastEnds.get(quote); | ||
| if (end === undefined || end < match.index + match[0].length) { | ||
| continue; | ||
| } | ||
| parts.push( | ||
| text.slice(cursor, match.index), | ||
| `${prefix}${quote}Bearer [REDACTED]${quote}` | ||
| ); | ||
| cursor = end + quote.length; | ||
| } | ||
| parts.push(text.slice(cursor)); | ||
| return parts.join(""); | ||
| } | ||
|
|
||
| /** Remove recognizable credentials from diagnostics without retaining secrets. */ | ||
| export function redactCredentialText(text: string): string { | ||
| return redactInvalidBearerHeaders(text) | ||
| .replace(QUOTED_CREDENTIAL, (_match, quote: string, prefix: string) => | ||
| prefix.toLowerCase().startsWith("bearer") | ||
| ? `${quote}Bearer [REDACTED]${quote}` | ||
| : `${quote}[REDACTED]${quote}` | ||
| ) | ||
| .replace(BEARER_CREDENTIAL, "Bearer [REDACTED]") | ||
| .replace(SENTRY_CREDENTIAL, "[REDACTED]"); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| /** Redact outgoing SDK envelopes without modifying live scopes or caller data. */ | ||
|
|
||
| import { type Envelope, normalize } from "@sentry/core"; | ||
| import { redactCredentialText } from "../credential-redaction.js"; | ||
|
|
||
| /** Materialize the same JSON as the SDK before redacting a detached copy. */ | ||
| function redactJson<T>(value: T): T { | ||
| let serialized: string | undefined; | ||
| try { | ||
| serialized = JSON.stringify(value); | ||
| } catch { | ||
| // This is the SDK's envelope serialization fallback for cycles and BigInt. | ||
| serialized = JSON.stringify(normalize(value)); | ||
| } | ||
| const copy: T = JSON.parse(serialized ?? "null"); | ||
| if (typeof copy === "string") { | ||
| return redactCredentialText(copy) as T; | ||
| } | ||
| const pending: unknown[] = [copy]; | ||
| while (pending.length > 0) { | ||
| const current = pending.pop(); | ||
| if (current === null || typeof current !== "object") { | ||
| continue; | ||
| } | ||
| for (const [key, nested] of Object.entries(current)) { | ||
| if (typeof nested === "string") { | ||
| (current as Record<string, unknown>)[key] = | ||
| redactCredentialText(nested); | ||
| } else { | ||
| pending.push(nested); | ||
| } | ||
| } | ||
| } | ||
| return copy; | ||
| } | ||
|
|
||
| /** | ||
| * Scrub the final envelope, after SDK metadata and log attributes are resolved. | ||
| * JSON materialization preserves boxed values/toJSON without mutating live | ||
| * scopes, client options, or caller-owned objects. Binary attachments stay intact. | ||
| */ | ||
| export function redactTelemetryEnvelope(envelope: Envelope): Envelope { | ||
| return [ | ||
| redactJson(envelope[0]), | ||
| envelope[1].map(([headers, payload]) => { | ||
| const safeHeaders = redactJson(headers); | ||
| const safePayload = | ||
| payload instanceof Uint8Array ? payload : redactJson(payload); | ||
| if (typeof safePayload === "string" && headers.length !== undefined) { | ||
| safeHeaders.length = Buffer.byteLength(safePayload, "utf8"); | ||
| } | ||
| return [safeHeaders, safePayload]; | ||
| }), | ||
| ] as Envelope; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| import { expect, test, vi } from "vitest"; | ||
| import { startCli } from "../../src/cli.js"; | ||
| // biome-ignore lint/performance/noNamespaceImport: spy on the startup dependency | ||
| import * as upgrade from "../../src/lib/upgrade.js"; | ||
| import { useTestConfigDir } from "../helpers.js"; | ||
|
|
||
| useTestConfigDir("cli-startup-"); | ||
|
|
||
| test("fatal errors preserve their name while redacting credentials", async () => { | ||
| const argv = process.argv; | ||
| const exitCode = process.exitCode; | ||
| const stderr = vi | ||
| .spyOn(process.stderr, "write") | ||
| .mockImplementation(() => true); | ||
| const cleanup = vi | ||
| .spyOn(upgrade, "startCleanupOldBinary") | ||
| .mockImplementation(() => { | ||
| throw new TypeError( | ||
| 'Headers.set: "Bearer SYNTHETIC_PREFIX\nSYNTHETIC_SECRET" is an invalid header value.' | ||
| ); | ||
| }); | ||
|
|
||
| try { | ||
| process.argv = ["node", "sentry", "--help"]; | ||
| await startCli(); | ||
|
|
||
| expect(cleanup).toHaveBeenCalledOnce(); | ||
| expect(stderr).toHaveBeenLastCalledWith( | ||
| 'Fatal: TypeError: Headers.set: "Bearer [REDACTED]" is an invalid header value.\n' | ||
| ); | ||
| expect(process.exitCode).toBe(1); | ||
| } finally { | ||
| process.argv = argv; | ||
| process.exitCode = exitCode; | ||
| vi.restoreAllMocks(); | ||
| } | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.