From 4a6b1f007506c6673184ead5d18844e011081306 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 28 Oct 2026 15:04:12 +0500 Subject: [PATCH 01/12] fix(performance): tokenise SQL literal redaction (comments, backslash escapes, dollar quotes) (#109) Co-Authored-By: Claude Sonnet 5.5 --- .../performance/src/span-sanitizer.test.ts | 65 +++++++++++++- packages/performance/src/span-sanitizer.ts | 88 +++++++++++++++---- 2 files changed, 136 insertions(+), 17 deletions(-) diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index f6efb0a4..5486bf01 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -240,11 +240,72 @@ describe('redactSqlLiterals on a statement that was CUT inside a literal', () => it('handles closed literals followed by an unterminated one, and a doubled quote before the cut', () => { expect(redactSqlLiterals("a = 'x' AND b = 'cd")).toBe('a = ? AND b = ?'); - // `'it'` closes at the first quote and `'s a sec` is the open tail: both are data, both go. - expect(redactSqlLiterals("a = 'it''s a sec")).toBe('a = ??'); + // `it''s a sec` is ONE literal (doubled quote = escape) that never closes: all of it goes. + expect(redactSqlLiterals("a = 'it''s a sec")).toBe('a = ?'); }); it('leaves a statement without any quote alone', () => { expect(redactSqlLiterals('SELECT x FROM t')).toBe('SELECT x FROM t'); }); }); + +describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () => { + const clean = (sql: string): string => redactSqlLiterals(sql); + + it('ignores an apostrophe in a block comment and drops the comment', () => { + expect(clean("/* don't */ SELECT * FROM t WHERE a = 'secretA'")).toBe( + ' SELECT * FROM t WHERE a = ?', + ); + expect(clean('SELECT/* x */1')).toBe('SELECT ?'); + }); + + it('fails closed on an unterminated block comment', () => { + expect(clean("SELECT 1 /* it's 'secret")).toBe('SELECT ? '); + }); + + it('ignores an apostrophe in a line comment, keeping the newline', () => { + expect(clean("-- it's\nSELECT * FROM t WHERE a = 'secretB'")).toBe( + ' \nSELECT * FROM t WHERE a = ?', + ); + expect(clean("SELECT 1 -- it's")).toBe('SELECT ? '); + }); + + it('honours backslash-escaped quotes', () => { + expect(clean("INSERT INTO t VALUES ('O\\'Brien','secretC')")).toBe( + 'INSERT INTO t VALUES (?,?)', + ); + expect(clean('SELECT "a\\"b secret"')).toBe('SELECT ?'); + }); + + it('treats dollar-quoted bodies as one literal, tagged or not', () => { + expect(clean("SELECT $$it's$$, 'secretD'")).toBe('SELECT ?, ?'); + expect(clean("SELECT $q$it's $$ x$q$, 'secretE'")).toBe('SELECT ?, ?'); + }); + + it('fails closed on an unterminated dollar quote', () => { + expect(clean("SELECT $$it's secret")).toBe('SELECT ?'); + }); + + it('does not open a dollar quote on a positional parameter or inside an identifier', () => { + // (the digit after `$` is still a numeric literal, as before: harmless, and it groups) + expect(clean('SELECT * FROM t WHERE a = $1 AND b = $2')).toBe( + 'SELECT * FROM t WHERE a = $? AND b = $?', + ); + expect(clean('SELECT a$b$ FROM t')).toBe('SELECT a$b$ FROM t'); + expect(clean('SELECT $ FROM t')).toBe('SELECT $ FROM t'); + }); + + it('keeps a backtick identifier whole, even with a quote inside it', () => { + expect(clean("SELECT `it's` FROM t WHERE a = 'secretF'")).toBe( + "SELECT `it's` FROM t WHERE a = ?", + ); + }); + + it('fails closed on an unterminated backtick identifier', () => { + expect(clean("SELECT `it's 'secret")).toBe('SELECT ?'); + }); + + it('does not treat a lone dash or slash as a comment', () => { + expect(clean('SELECT a-b, c/d FROM t')).toBe('SELECT a-b, c/d FROM t'); + }); +}); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index d35befeb..3a72c5e0 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -36,28 +36,86 @@ const CONTENT_KEYS = new Set([ /** Keys carrying a database statement, across the OTel conventions that have named it differently. */ const STATEMENT_KEYS = new Set(['db.statement', 'db.query.text']); +/** Can this character be part of an identifier (so a `$` right after it is not a dollar-quote opener)? */ +const isWordChar = (ch: string | undefined): boolean => + ch !== undefined && /[A-Za-z0-9_$]/.test(ch); + +/** End index (exclusive) of a quoted run opening at `start`; `-1` when it never closes. Backslash escapes too. */ +function quotedEnd(sql: string, start: number): number { + const quote = sql[start]; + for (let i = start + 1; i < sql.length; i++) { + const ch = sql[i]; + if (ch === '\\') { + i++; // a backslash escape (MySQL, or Postgres with standard_conforming_strings = off) + } else if (ch === quote) { + if (sql[i + 1] !== quote) return i + 1; + i++; // doubled quote: SQL's own escape + } + } + return -1; +} + /** * Replace the LITERALS in a SQL statement with placeholders, keeping its shape. * * `SELECT * FROM users WHERE email = 'a@b.com'` becomes `SELECT * FROM users WHERE email = ?`, which is * the form that is actually useful in a report: it groups (every execution of one query looks the same) - * and it carries no customer data. Quoted strings go first so a number inside a string is not treated as - * a number, and doubled quotes — SQL's own escape — are consumed as part of the string they sit in. + * and it carries no customer data. + * + * It TOKENISES rather than pairing quotes, because a quote that is not a string delimiter shifts the pairing + * and leaves the next literal in the clear. Line and block comments are dropped (they can carry data and + * their apostrophes are not delimiters); `'..'` and `".."` strings honour both doubled quotes and backslash + * escapes; backtick identifiers are kept whole; `$tag$..$tag$` bodies are one literal. Anything that never + * closes (including a statement cut by a length cap) fails CLOSED: it is redacted to the end. A backslash is + * always treated as an escape, which over-redacts in dialects where it is not one: that is the safe side. */ export function redactSqlLiterals(statement: string): string { - return ( - statement - // '...' with '' escapes, and "..." with "" escapes - .replace(/'(?:[^']|'')*'/g, '?') - .replace(/"(?:[^"]|"")*"/g, '?') - // A literal still OPEN at the end: the statement was cut by a length cap (which runs before this), and - // everything after the opening quote is literal data. (After the closed passes at most one lone quote is - // left, so no doubled-quote alternative is needed here.) - .replace(/'[^']*$/, '?') - .replace(/"[^"]*$/, '?') - // numeric literals, but never the digits inside an identifier like `column2` - .replace(/\b\d+(?:\.\d+)?\b/g, '?') - ); + let out = ''; + let i = 0; + while (i < statement.length) { + const ch = statement[i] as string; + const next = statement[i + 1]; + if (ch === '-' && next === '-') { + const eol = statement.indexOf('\n', i); + out += ' '; + if (eol === -1) break; + i = eol; // keep the newline itself + } else if (ch === '/' && next === '*') { + const close = statement.indexOf('*/', i + 2); + out += ' '; + if (close === -1) break; + i = close + 2; + } else if (ch === "'" || ch === '"') { + const end = quotedEnd(statement, i); + out += '?'; + if (end === -1) break; + i = end; + } else if (ch === '`') { + const end = quotedEnd(statement, i); + if (end === -1) { + out += '?'; + break; + } + out += statement.slice(i, end); + i = end; + } else if (ch === '$' && !isWordChar(statement[i - 1])) { + const tag = /^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/.exec(statement.slice(i, i + 130))?.[0]; + if (tag === undefined) { + out += ch; + i++; + continue; + } + const close = statement.indexOf(tag, i + tag.length); + out += '?'; + if (close === -1) break; + i = close + tag.length; + } else { + out += ch; + i++; + } + } + // numeric literals, but never the digits inside an identifier like `column2` + return out.replace(/\b\d+(?:\.\d+)?\b/g, '?'); } /** From 4edf935296ea5e8d1b7df9d595733deb229e9797 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 28 Oct 2026 15:06:16 +0500 Subject: [PATCH 02/12] fix(performance): fail closed on ambiguous backslash literals, nested/# comments, long dollar tags, hex/exp numbers (#109) Co-Authored-By: Claude Sonnet 5.5 --- .../performance/src/span-sanitizer.test.ts | 40 +++++++++++- packages/performance/src/span-sanitizer.ts | 63 ++++++++++++++----- 2 files changed, 85 insertions(+), 18 deletions(-) diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index 5486bf01..8221d3c5 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -271,9 +271,8 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = }); it('honours backslash-escaped quotes', () => { - expect(clean("INSERT INTO t VALUES ('O\\'Brien','secretC')")).toBe( - 'INSERT INTO t VALUES (?,?)', - ); + // A backslash-escaped quote makes the literal's end dialect-dependent: fail closed, nothing survives. + expect(clean("INSERT INTO t VALUES ('O\\'Brien','secretC')")).toBe('INSERT INTO t VALUES (?'); expect(clean('SELECT "a\\"b secret"')).toBe('SELECT ?'); }); @@ -308,4 +307,39 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = it('does not treat a lone dash or slash as a comment', () => { expect(clean('SELECT a-b, c/d FROM t')).toBe('SELECT a-b, c/d FROM t'); }); + + it('fails closed on a literal ending in a backslash (standard SQL: complete; MySQL: escape)', () => { + expect(clean("SELECT * FROM t WHERE a = 'C:\\' AND b = 'secretP'")).toBe( + 'SELECT * FROM t WHERE a = ?', + ); + expect(clean("a = 'C:\\temp\\' AND b = 'secretQ' AND c = 1")).toBe('a = ?'); + }); + + it('does not read a backslash in a backtick identifier as an escape', () => { + expect(clean("SELECT `a\\` = 'secretB' AND `x` FROM t")).toBe( + 'SELECT `a\\` = ? AND `x` FROM t', + ); + }); + + it('drops a MySQL # comment', () => { + expect(clean("SELECT 1 # it's\nFROM t WHERE x = 'secretH'")).toBe( + 'SELECT ? \nFROM t WHERE x = ?', + ); + }); + + it('honours nested block comments', () => { + expect(clean("/* outer /* inner */ it's */ SELECT * FROM t WHERE x = 'secretN'")).toBe( + ' SELECT * FROM t WHERE x = ?', + ); + expect(clean("SELECT 1 /* a /* b */ 'secret")).toBe('SELECT ? '); + }); + + it('recognises a dollar-quote tag of any length', () => { + const tag = `$${'a'.repeat(140)}$`; + expect(clean(`SELECT ${tag}it's${tag}, 'secretT'`)).toBe('SELECT ?, ?'); + }); + + it('redacts exponent and hex numeric literals', () => { + expect(clean('SELECT 1e10, 2.5E-3, 0xDEADBEEF, c1 FROM t1')).toBe('SELECT ?, ?, ?, c1 FROM t1'); + }); }); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index 3a72c5e0..ef3d4475 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -40,13 +40,32 @@ const STATEMENT_KEYS = new Set(['db.statement', 'db.query.text']); const isWordChar = (ch: string | undefined): boolean => ch !== undefined && /[A-Za-z0-9_$]/.test(ch); -/** End index (exclusive) of a quoted run opening at `start`; `-1` when it never closes. Backslash escapes too. */ -function quotedEnd(sql: string, start: number): number { +const DOLLAR_TAG = /\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/y; + +/** End (exclusive) of the block comment opening at `start`, honouring nesting; `-1` when it never closes. */ +function blockCommentEnd(sql: string, start: number): number { + let depth = 0; + for (let i = start; i < sql.length - 1; i++) { + const pair = sql.slice(i, i + 2); + if (pair === '/*') { + depth++; + i++; + } else if (pair === '*/') { + depth--; + i++; + if (depth === 0) return i + 1; + } + } + return -1; +} + +/** End of a quoted run opening at `start`, reading a backslash as an escape or as a plain character. */ +function runEnd(sql: string, start: number, backslashEscapes: boolean): number { const quote = sql[start]; for (let i = start + 1; i < sql.length; i++) { const ch = sql[i]; - if (ch === '\\') { - i++; // a backslash escape (MySQL, or Postgres with standard_conforming_strings = off) + if (backslashEscapes && ch === '\\') { + i++; } else if (ch === quote) { if (sql[i + 1] !== quote) return i + 1; i++; // doubled quote: SQL's own escape @@ -55,6 +74,19 @@ function quotedEnd(sql: string, start: number): number { return -1; } +/** + * End index (exclusive) of a quoted run opening at `start`; `-1` when it never closes OR when it is AMBIGUOUS. + * + * Whether a backslash escapes the next character depends on the dialect (MySQL, Postgres with + * `standard_conforming_strings = off`: yes; standard SQL, SQLite, SQL Server, Oracle: no) and the statement + * does not say which. When the two readings disagree about where the literal ends, any guess can mis-pair the + * quotes that follow and leave a later literal in the clear, so the run fails closed (redacted to the end). + */ +function quotedEnd(sql: string, start: number): number { + const escaped = runEnd(sql, start, true); + return escaped === runEnd(sql, start, false) ? escaped : -1; +} + /** * Replace the LITERALS in a SQL statement with placeholders, keeping its shape. * @@ -63,11 +95,11 @@ function quotedEnd(sql: string, start: number): number { * and it carries no customer data. * * It TOKENISES rather than pairing quotes, because a quote that is not a string delimiter shifts the pairing - * and leaves the next literal in the clear. Line and block comments are dropped (they can carry data and + * and leaves the next literal in the clear. Line (`--`, MySQL `#`) and block (nested, as Postgres) comments are dropped (they can carry data and * their apostrophes are not delimiters); `'..'` and `".."` strings honour both doubled quotes and backslash - * escapes; backtick identifiers are kept whole; `$tag$..$tag$` bodies are one literal. Anything that never - * closes (including a statement cut by a length cap) fails CLOSED: it is redacted to the end. A backslash is - * always treated as an escape, which over-redacts in dialects where it is not one: that is the safe side. + * escapes (a literal whose end depends on the dialect's backslash rule is ambiguous); backtick identifiers + * are kept whole; `$tag$..$tag$` bodies are one literal. Anything that never closes or cannot be classified + * (including a statement cut by a length cap) fails CLOSED: it is redacted to the end. */ export function redactSqlLiterals(statement: string): string { let out = ''; @@ -75,23 +107,23 @@ export function redactSqlLiterals(statement: string): string { while (i < statement.length) { const ch = statement[i] as string; const next = statement[i + 1]; - if (ch === '-' && next === '-') { + if ((ch === '-' && next === '-') || ch === '#') { const eol = statement.indexOf('\n', i); out += ' '; if (eol === -1) break; i = eol; // keep the newline itself } else if (ch === '/' && next === '*') { - const close = statement.indexOf('*/', i + 2); out += ' '; + const close = blockCommentEnd(statement, i); if (close === -1) break; - i = close + 2; + i = close; } else if (ch === "'" || ch === '"') { const end = quotedEnd(statement, i); out += '?'; if (end === -1) break; i = end; } else if (ch === '`') { - const end = quotedEnd(statement, i); + const end = runEnd(statement, i, false); // backticks never take a backslash escape if (end === -1) { out += '?'; break; @@ -99,7 +131,8 @@ export function redactSqlLiterals(statement: string): string { out += statement.slice(i, end); i = end; } else if (ch === '$' && !isWordChar(statement[i - 1])) { - const tag = /^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/.exec(statement.slice(i, i + 130))?.[0]; + DOLLAR_TAG.lastIndex = i; + const tag = DOLLAR_TAG.exec(statement)?.[0]; if (tag === undefined) { out += ch; i++; @@ -114,8 +147,8 @@ export function redactSqlLiterals(statement: string): string { i++; } } - // numeric literals, but never the digits inside an identifier like `column2` - return out.replace(/\b\d+(?:\.\d+)?\b/g, '?'); + // numeric literals (decimal, exponent, hex), but never the digits inside an identifier like `column2` + return out.replace(/\b(?:0x[0-9a-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)\b/gi, '?'); } /** From d02eaeb70f8629c179d1a0fa40a6a5a311615ed2 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 28 Oct 2026 15:10:33 +0500 Subject: [PATCH 03/12] fix(performance): scan SQL under every dialect and fail closed where readings disagree (#109) Co-Authored-By: Claude Sonnet 5.5 --- .../performance/src/span-sanitizer.test.ts | 53 ++++--- packages/performance/src/span-sanitizer.ts | 138 +++++++++++++----- 2 files changed, 137 insertions(+), 54 deletions(-) diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index 8221d3c5..f2f9e261 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -272,13 +272,13 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = it('honours backslash-escaped quotes', () => { // A backslash-escaped quote makes the literal's end dialect-dependent: fail closed, nothing survives. - expect(clean("INSERT INTO t VALUES ('O\\'Brien','secretC')")).toBe('INSERT INTO t VALUES (?'); - expect(clean('SELECT "a\\"b secret"')).toBe('SELECT ?'); + expect(clean("INSERT INTO t VALUES ('O\\'Brien','secretC')")).toBe('INSERT INTO t VALUES (??'); + expect(clean('SELECT "a\\"b secret"')).toBe('SELECT ??'); }); - it('treats dollar-quoted bodies as one literal, tagged or not', () => { - expect(clean("SELECT $$it's$$, 'secretD'")).toBe('SELECT ?, ?'); - expect(clean("SELECT $q$it's $$ x$q$, 'secretE'")).toBe('SELECT ?, ?'); + it('fails closed on dollar-quoted bodies (only some dialects have them), keeping the agreed prefix', () => { + expect(clean("SELECT $$it's$$, 'secretD'")).toBe('SELECT ?'); + expect(clean("SELECT $q$it's $$ x$q$, 'secretE'")).toBe('SELECT ?'); }); it('fails closed on an unterminated dollar quote', () => { @@ -310,9 +310,9 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = it('fails closed on a literal ending in a backslash (standard SQL: complete; MySQL: escape)', () => { expect(clean("SELECT * FROM t WHERE a = 'C:\\' AND b = 'secretP'")).toBe( - 'SELECT * FROM t WHERE a = ?', + 'SELECT * FROM t WHERE a = ??', ); - expect(clean("a = 'C:\\temp\\' AND b = 'secretQ' AND c = 1")).toBe('a = ?'); + expect(clean("a = 'C:\\temp\\' AND b = 'secretQ' AND c = 1")).toBe('a = ??'); }); it('does not read a backslash in a backtick identifier as an escape', () => { @@ -321,25 +321,42 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = ); }); - it('drops a MySQL # comment', () => { - expect(clean("SELECT 1 # it's\nFROM t WHERE x = 'secretH'")).toBe( - 'SELECT ? \nFROM t WHERE x = ?', - ); + it('fails closed on a # (a MySQL comment, a Postgres operator)', () => { + expect(clean("SELECT 1 # it's\nFROM t WHERE x = 'secretH'")).toBe('SELECT ? ?'); }); - it('honours nested block comments', () => { - expect(clean("/* outer /* inner */ it's */ SELECT * FROM t WHERE x = 'secretN'")).toBe( - ' SELECT * FROM t WHERE x = ?', - ); - expect(clean("SELECT 1 /* a /* b */ 'secret")).toBe('SELECT ? '); + it('handles nested block comments', () => { + // MySQL ends the comment at the first `*/`, Postgres at the second: the readings disagree, so cut. + expect(clean("/* outer /* inner */ it's */ SELECT * FROM t WHERE x = 'secretN'")).toBe(' ?'); + // ...and when nesting makes no difference the comment is simply dropped. + expect(clean("/* a */ SELECT 'secretM' /* b */")).toBe(' SELECT ? '); + expect(clean("SELECT 1 /* a /* b */ 'secret")).toBe('SELECT ? ?'); }); - it('recognises a dollar-quote tag of any length', () => { + it('does not let a dollar-quote tag of any length slip through', () => { const tag = `$${'a'.repeat(140)}$`; - expect(clean(`SELECT ${tag}it's${tag}, 'secretT'`)).toBe('SELECT ?, ?'); + expect(clean(`SELECT ${tag}it's${tag}, 'secretT'`)).toBe('SELECT ?'); }); it('redacts exponent and hex numeric literals', () => { expect(clean('SELECT 1e10, 2.5E-3, 0xDEADBEEF, c1 FROM t1')).toBe('SELECT ?, ?, ?, c1 FROM t1'); }); + + it.each([ + // each leaked under a one-dialect reading of `#`, `--`, nested comments or dollar quotes + ["SELECT data #>> '{a}' FROM t WHERE note = 'line1\nsecretline2'", 'secretline2'], + ["UPDATE t SET flags = flags # 4, note = 'Dear J,\nSSN hunter'", 'hunter'], + ["SELECT 1--'abc\nsecret'", 'secret'], + ["SELECT /* a /* b */ x = 'p */ secret'", 'secret'], + ["SELECT $a$ FROM t WHERE x = 'p$a$ ' AND y = 'secret'", 'secret'], + ])('never lets literal data through under any dialect reading: %j', (sql, secret) => { + expect(clean(sql)).not.toContain(secret); + }); + + it('keeps `--` followed by whitespace as an ordinary comment in every dialect', () => { + expect(clean("SELECT 1 -- it's\nFROM t WHERE x = 'secret'")).toBe( + 'SELECT ? \nFROM t WHERE x = ?', + ); + expect(clean('SELECT 1 --\nFROM t')).toBe('SELECT ? \nFROM t'); + }); }); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index ef3d4475..f1e9d647 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -42,12 +42,66 @@ const isWordChar = (ch: string | undefined): boolean => const DOLLAR_TAG = /\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/y; -/** End (exclusive) of the block comment opening at `start`, honouring nesting; `-1` when it never closes. */ -function blockCommentEnd(sql: string, start: number): number { +/** How a SQL dialect reads the constructs whose extent decides where the string literals are. */ +interface Dialect { + /** `#` starts a line comment (MySQL; in Postgres it is an operator). */ + hashComment: boolean; + /** `--` is a comment only when followed by whitespace (MySQL; elsewhere it always is). */ + dashNeedsSpace: boolean; + /** Block comments nest (Postgres). */ + nestedComments: boolean; + /** `$tag$ .. $tag$` is a quoted body (Postgres). */ + dollarQuotes: boolean; + /** A backslash escapes the next character inside a string (MySQL, Postgres with standard_conforming_strings off). */ + backslashEscapes: boolean; +} + +/** + * The dialects a statement could be in. The statement does not say which, and a wrong guess shifts the quote + * pairing and leaves a later literal in the clear, so the statement is read under EACH of these and anything + * the readings disagree about fails closed (see `redactSqlLiterals`). + */ +const DIALECTS: readonly Dialect[] = [ + // MySQL / MariaDB + { + hashComment: true, + dashNeedsSpace: true, + nestedComments: false, + dollarQuotes: false, + backslashEscapes: true, + }, + // Postgres, standard_conforming_strings on + { + hashComment: false, + dashNeedsSpace: false, + nestedComments: true, + dollarQuotes: true, + backslashEscapes: false, + }, + // Postgres, standard_conforming_strings off + { + hashComment: false, + dashNeedsSpace: false, + nestedComments: true, + dollarQuotes: true, + backslashEscapes: true, + }, + // standard SQL, SQLite, SQL Server, Oracle + { + hashComment: false, + dashNeedsSpace: false, + nestedComments: false, + dollarQuotes: false, + backslashEscapes: false, + }, +]; + +/** End (exclusive) of the block comment opening at `start`; `-1` when it never closes. */ +function blockCommentEnd(sql: string, start: number, nested: boolean): number { let depth = 0; for (let i = start; i < sql.length - 1; i++) { const pair = sql.slice(i, i + 2); - if (pair === '/*') { + if (pair === '/*' && (nested || depth === 0)) { depth++; i++; } else if (pair === '*/') { @@ -59,7 +113,7 @@ function blockCommentEnd(sql: string, start: number): number { return -1; } -/** End of a quoted run opening at `start`, reading a backslash as an escape or as a plain character. */ +/** End (exclusive) of a quoted run opening at `start`; `-1` when it never closes. */ function runEnd(sql: string, start: number, backslashEscapes: boolean): number { const quote = sql[start]; for (let i = start + 1; i < sql.length; i++) { @@ -74,51 +128,31 @@ function runEnd(sql: string, start: number, backslashEscapes: boolean): number { return -1; } -/** - * End index (exclusive) of a quoted run opening at `start`; `-1` when it never closes OR when it is AMBIGUOUS. - * - * Whether a backslash escapes the next character depends on the dialect (MySQL, Postgres with - * `standard_conforming_strings = off`: yes; standard SQL, SQLite, SQL Server, Oracle: no) and the statement - * does not say which. When the two readings disagree about where the literal ends, any guess can mis-pair the - * quotes that follow and leave a later literal in the clear, so the run fails closed (redacted to the end). - */ -function quotedEnd(sql: string, start: number): number { - const escaped = runEnd(sql, start, true); - return escaped === runEnd(sql, start, false) ? escaped : -1; -} - -/** - * Replace the LITERALS in a SQL statement with placeholders, keeping its shape. - * - * `SELECT * FROM users WHERE email = 'a@b.com'` becomes `SELECT * FROM users WHERE email = ?`, which is - * the form that is actually useful in a report: it groups (every execution of one query looks the same) - * and it carries no customer data. - * - * It TOKENISES rather than pairing quotes, because a quote that is not a string delimiter shifts the pairing - * and leaves the next literal in the clear. Line (`--`, MySQL `#`) and block (nested, as Postgres) comments are dropped (they can carry data and - * their apostrophes are not delimiters); `'..'` and `".."` strings honour both doubled quotes and backslash - * escapes (a literal whose end depends on the dialect's backslash rule is ambiguous); backtick identifiers - * are kept whole; `$tag$..$tag$` bodies are one literal. Anything that never closes or cannot be classified - * (including a statement cut by a length cap) fails CLOSED: it is redacted to the end. - */ -export function redactSqlLiterals(statement: string): string { +/** One pass over the statement under one dialect: comments dropped, literals replaced by `?`. */ +function scan(statement: string, dialect: Dialect): string { let out = ''; let i = 0; while (i < statement.length) { const ch = statement[i] as string; const next = statement[i + 1]; - if ((ch === '-' && next === '-') || ch === '#') { + const afterDash = statement[i + 2]; + if ( + (ch === '-' && + next === '-' && + (!dialect.dashNeedsSpace || afterDash === undefined || afterDash <= ' ')) || + (ch === '#' && dialect.hashComment) + ) { const eol = statement.indexOf('\n', i); out += ' '; if (eol === -1) break; i = eol; // keep the newline itself } else if (ch === '/' && next === '*') { out += ' '; - const close = blockCommentEnd(statement, i); + const close = blockCommentEnd(statement, i, dialect.nestedComments); if (close === -1) break; i = close; } else if (ch === "'" || ch === '"') { - const end = quotedEnd(statement, i); + const end = runEnd(statement, i, dialect.backslashEscapes); out += '?'; if (end === -1) break; i = end; @@ -130,7 +164,7 @@ export function redactSqlLiterals(statement: string): string { } out += statement.slice(i, end); i = end; - } else if (ch === '$' && !isWordChar(statement[i - 1])) { + } else if (ch === '$' && dialect.dollarQuotes && !isWordChar(statement[i - 1])) { DOLLAR_TAG.lastIndex = i; const tag = DOLLAR_TAG.exec(statement)?.[0]; if (tag === undefined) { @@ -147,6 +181,38 @@ export function redactSqlLiterals(statement: string): string { i++; } } + return out; +} + +/** + * Replace the LITERALS in a SQL statement with placeholders, keeping its shape. + * + * `SELECT * FROM users WHERE email = 'a@b.com'` becomes `SELECT * FROM users WHERE email = ?`, which is + * the form that is actually useful in a report: it groups (every execution of one query looks the same) + * and it carries no customer data. + * + * It TOKENISES rather than pairing quotes, because a quote that is not a string delimiter shifts the pairing + * and leaves the next literal in the clear. Comments are dropped (they can carry data and their apostrophes + * are not delimiters), `'..'` / `".."` strings honour doubled quotes, backtick identifiers are kept whole and + * `$tag$..$tag$` bodies are one literal. Which of these constructs a statement uses depends on its dialect + * (`#` comments, `--` spacing, nested comments, dollar quotes and backslash escapes all differ) and the + * statement does not say which, so it is scanned under every dialect in `DIALECTS` and the result is cut + * where the readings first disagree: the agreed prefix is kept, the rest is redacted. Anything that never + * closes (including a statement cut by a length cap) likewise fails CLOSED to the end. The price is shape: + * a statement using a dialect-specific construct may lose its tail, which is the safe side of the trade. + */ +export function redactSqlLiterals(statement: string): string { + const [first, ...rest] = DIALECTS.map((dialect) => scan(statement, dialect)) as [ + string, + ...string[], + ]; + let out = first; + for (const other of rest) { + if (other === out) continue; + let k = 0; + while (k < out.length && k < other.length && out[k] === other[k]) k++; + out = `${out.slice(0, k)}?`; + } // numeric literals (decimal, exponent, hex), but never the digits inside an identifier like `column2` return out.replace(/\b(?:0x[0-9a-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)\b/gi, '?'); } From b9c181ad3aca690e6bc100e8150b0fb68cc40ebb Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 28 Oct 2026 15:17:28 +0500 Subject: [PATCH 04/12] fix(performance): E-string-only backslash escapes, CR comment ends, unicode dollar tags (#109) Co-Authored-By: Claude Sonnet 5.5 --- .../performance/src/span-sanitizer.test.ts | 15 ++++++++ packages/performance/src/span-sanitizer.ts | 34 +++++++++++++------ 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index f2f9e261..688a9e65 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -359,4 +359,19 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = ); expect(clean('SELECT 1 --\nFROM t')).toBe('SELECT ? \nFROM t'); }); + + it.each([ + ["SELECT 1 -- c\r, 'x\nsecret1', 'secret2'", 'secret'], + [ + "INSERT INTO u (note, dir, email) VALUES (E'x\\', ', 'alice\\', 'alice@example.com')", + 'alice', + ], + ['SELECT $é$secret data$é$, $tag$ok$tag$', 'secret'], + ])('never lets literal data through: %j', (sql, secret) => { + expect(clean(sql)).not.toContain(secret); + }); + + it('ends a -- comment at a lone carriage return', () => { + expect(clean("SELECT 1 -- it's\r, 'secret'")).toBe('SELECT ? \r, ?'); + }); }); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index f1e9d647..2521ef78 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -40,7 +40,10 @@ const STATEMENT_KEYS = new Set(['db.statement', 'db.query.text']); const isWordChar = (ch: string | undefined): boolean => ch !== undefined && /[A-Za-z0-9_$]/.test(ch); -const DOLLAR_TAG = /\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/y; +const DOLLAR_TAG = /\$(?:[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_\u0080-\uFFFF]*)?\$/y; + +/** A line comment ends at either line terminator (Postgres ends it at a lone CR too). */ +const LINE_END = /[\r\n]/g; /** How a SQL dialect reads the constructs whose extent decides where the string literals are. */ interface Dialect { @@ -52,8 +55,11 @@ interface Dialect { nestedComments: boolean; /** `$tag$ .. $tag$` is a quoted body (Postgres). */ dollarQuotes: boolean; - /** A backslash escapes the next character inside a string (MySQL, Postgres with standard_conforming_strings off). */ - backslashEscapes: boolean; + /** + * Which strings a backslash escapes the next character in: every one (MySQL), only `E'..'` ones (Postgres, + * standard_conforming_strings on), every single-quoted one (Postgres, it off), or none (standard SQL, SQLite..). + */ + backslashEscapes: 'all' | 'e' | 'single' | 'none'; } /** @@ -68,7 +74,7 @@ const DIALECTS: readonly Dialect[] = [ dashNeedsSpace: true, nestedComments: false, dollarQuotes: false, - backslashEscapes: true, + backslashEscapes: 'all', }, // Postgres, standard_conforming_strings on { @@ -76,7 +82,7 @@ const DIALECTS: readonly Dialect[] = [ dashNeedsSpace: false, nestedComments: true, dollarQuotes: true, - backslashEscapes: false, + backslashEscapes: 'e', }, // Postgres, standard_conforming_strings off { @@ -84,7 +90,7 @@ const DIALECTS: readonly Dialect[] = [ dashNeedsSpace: false, nestedComments: true, dollarQuotes: true, - backslashEscapes: true, + backslashEscapes: 'single', }, // standard SQL, SQLite, SQL Server, Oracle { @@ -92,7 +98,7 @@ const DIALECTS: readonly Dialect[] = [ dashNeedsSpace: false, nestedComments: false, dollarQuotes: false, - backslashEscapes: false, + backslashEscapes: 'none', }, ]; @@ -142,17 +148,25 @@ function scan(statement: string, dialect: Dialect): string { (!dialect.dashNeedsSpace || afterDash === undefined || afterDash <= ' ')) || (ch === '#' && dialect.hashComment) ) { - const eol = statement.indexOf('\n', i); + LINE_END.lastIndex = i; + const eol = LINE_END.exec(statement)?.index ?? -1; out += ' '; if (eol === -1) break; - i = eol; // keep the newline itself + i = eol; // keep the terminator itself } else if (ch === '/' && next === '*') { out += ' '; const close = blockCommentEnd(statement, i, dialect.nestedComments); if (close === -1) break; i = close; } else if (ch === "'" || ch === '"') { - const end = runEnd(statement, i, dialect.backslashEscapes); + const escapes = + dialect.backslashEscapes === 'all' || + (ch === "'" && + (dialect.backslashEscapes === 'single' || + (dialect.backslashEscapes === 'e' && + /[eE]/.test(statement[i - 1] ?? '') && + !isWordChar(statement[i - 2])))); + const end = runEnd(statement, i, escapes); out += '?'; if (end === -1) break; i = end; From 12f6c18d904dd0288b85cf2c14aa2eec160acc7b Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 28 Oct 2026 15:22:47 +0500 Subject: [PATCH 05/12] fix(performance): MySQL executable comments, per-dialect line ends, more numeric forms (#109) Co-Authored-By: Claude Sonnet 5.5 --- .../performance/src/span-sanitizer.test.ts | 24 +++++++++- packages/performance/src/span-sanitizer.ts | 44 ++++++++++++++++--- 2 files changed, 60 insertions(+), 8 deletions(-) diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index 688a9e65..f5c5df7a 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -371,7 +371,27 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = expect(clean(sql)).not.toContain(secret); }); - it('ends a -- comment at a lone carriage return', () => { - expect(clean("SELECT 1 -- it's\r, 'secret'")).toBe('SELECT ? \r, ?'); + it('cuts at a lone carriage return after a -- comment (Postgres ends it there, MySQL does not)', () => { + expect(clean("SELECT 1 -- it's\r, 'secret'")).toBe('SELECT ? ?'); + }); + + it('lexes a MySQL executable comment body as code, so a `*/` inside its string cannot hide a literal', () => { + expect(clean("SELECT /*!50000 'a*/b' */ x FROM t WHERE p = 'secret'")).not.toContain('secret'); + expect(clean("SELECT 1 /*M!100000 + LENGTH('*/z') */ AS y, 'secret2'")).not.toContain( + 'secret2', + ); + expect(clean("SELECT /*+ SET_VAR(x='*/y') */ 1, 'secret3'")).not.toContain('secret3'); + }); + + it('ends # and -- comments at LF only for MySQL and SQLite, so a CR cannot hide a literal', () => { + expect(clean("SELECT c FROM t -- see\r it's\n WHERE a = 'k' AND p = 'secret'")).not.toContain( + 'secret', + ); + }); + + it('redacts underscore-separated, binary and octal numeric literals', () => { + expect(clean('SELECT 1 WHERE a = 4111_1111_1111_1111 OR b = 0b1010 OR c = 0o777')).toBe( + 'SELECT ? WHERE a = ? OR b = ? OR c = ?', + ); }); }); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index 2521ef78..dca29495 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -42,13 +42,18 @@ const isWordChar = (ch: string | undefined): boolean => const DOLLAR_TAG = /\$(?:[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_\u0080-\uFFFF]*)?\$/y; -/** A line comment ends at either line terminator (Postgres ends it at a lone CR too). */ -const LINE_END = /[\r\n]/g; +/** Where a line comment ends: Postgres at CR or LF, MySQL and SQLite at LF only. */ +const LF = /\n/g; +const CR_OR_LF = /[\r\n]/g; /** How a SQL dialect reads the constructs whose extent decides where the string literals are. */ interface Dialect { /** `#` starts a line comment (MySQL; in Postgres it is an operator). */ hashComment: boolean; + /** The line terminators that end a line comment. */ + lineEnd: RegExp; + /** Version-conditional and hint comments (`/*!`, `/*M!`, `/*+`) are executed as SQL, so quotes inside them delimit strings (MySQL). */ + executableComments: boolean; /** `--` is a comment only when followed by whitespace (MySQL; elsewhere it always is). */ dashNeedsSpace: boolean; /** Block comments nest (Postgres). */ @@ -71,6 +76,8 @@ const DIALECTS: readonly Dialect[] = [ // MySQL / MariaDB { hashComment: true, + lineEnd: LF, + executableComments: true, dashNeedsSpace: true, nestedComments: false, dollarQuotes: false, @@ -79,6 +86,8 @@ const DIALECTS: readonly Dialect[] = [ // Postgres, standard_conforming_strings on { hashComment: false, + lineEnd: CR_OR_LF, + executableComments: false, dashNeedsSpace: false, nestedComments: true, dollarQuotes: true, @@ -87,6 +96,8 @@ const DIALECTS: readonly Dialect[] = [ // Postgres, standard_conforming_strings off { hashComment: false, + lineEnd: CR_OR_LF, + executableComments: false, dashNeedsSpace: false, nestedComments: true, dollarQuotes: true, @@ -95,6 +106,8 @@ const DIALECTS: readonly Dialect[] = [ // standard SQL, SQLite, SQL Server, Oracle { hashComment: false, + lineEnd: LF, + executableComments: false, dashNeedsSpace: false, nestedComments: false, dollarQuotes: false, @@ -138,6 +151,7 @@ function runEnd(sql: string, start: number, backslashEscapes: boolean): number { function scan(statement: string, dialect: Dialect): string { let out = ''; let i = 0; + let executableDepth = 0; while (i < statement.length) { const ch = statement[i] as string; const next = statement[i + 1]; @@ -148,11 +162,26 @@ function scan(statement: string, dialect: Dialect): string { (!dialect.dashNeedsSpace || afterDash === undefined || afterDash <= ' ')) || (ch === '#' && dialect.hashComment) ) { - LINE_END.lastIndex = i; - const eol = LINE_END.exec(statement)?.index ?? -1; + dialect.lineEnd.lastIndex = i; + const eol = dialect.lineEnd.exec(statement)?.index ?? -1; out += ' '; if (eol === -1) break; i = eol; // keep the terminator itself + } else if ( + dialect.executableComments && + ch === '/' && + next === '*' && + /^\/\*(?:M?!|\+)/.test(statement.slice(i, i + 4)) + ) { + // Lex the body as code: skip only the opener (and the version digits) and remember to swallow its `*/`. + i += statement[i + 2] === 'M' ? 4 : 3; + while (statement[i] !== undefined && statement[i]! >= '0' && statement[i]! <= '9') i++; + executableDepth++; + out += ' '; + } else if (ch === '*' && next === '/' && executableDepth > 0) { + executableDepth--; + i += 2; + out += ' '; } else if (ch === '/' && next === '*') { out += ' '; const close = blockCommentEnd(statement, i, dialect.nestedComments); @@ -227,8 +256,11 @@ export function redactSqlLiterals(statement: string): string { while (k < out.length && k < other.length && out[k] === other[k]) k++; out = `${out.slice(0, k)}?`; } - // numeric literals (decimal, exponent, hex), but never the digits inside an identifier like `column2` - return out.replace(/\b(?:0x[0-9a-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)\b/gi, '?'); + // numeric literals (decimal, exponent, hex/binary/octal, underscore-separated), but never the digits inside an identifier like `column2` + return out.replace( + /\b(?:0x[0-9a-f_]+|0b[01_]+|0o[0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d+)?)\b/gi, + '?', + ); } /** From b3fb40fbedc618fab45104de99a161307d2bc520 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 28 Oct 2026 15:30:59 +0500 Subject: [PATCH 06/12] fix(performance): fail closed on quotes inside backtick runs, drop redundant profile, pin edge outputs (#109) Co-Authored-By: Claude Sonnet 5.5 --- .../performance/src/span-sanitizer.test.ts | 21 +++++++++++-- packages/performance/src/span-sanitizer.ts | 30 ++++++++----------- 2 files changed, 30 insertions(+), 21 deletions(-) diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index f5c5df7a..65d6e934 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -294,9 +294,16 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = expect(clean('SELECT $ FROM t')).toBe('SELECT $ FROM t'); }); - it('keeps a backtick identifier whole, even with a quote inside it', () => { - expect(clean("SELECT `it's` FROM t WHERE a = 'secretF'")).toBe( - "SELECT `it's` FROM t WHERE a = ?", + it('keeps a backtick identifier whole', () => { + expect(clean("SELECT `a b` FROM t WHERE a = 'secretF'")).toBe( + 'SELECT `a b` FROM t WHERE a = ?', + ); + }); + + it('fails closed on a backtick run containing a quote (a quote delimiter in other dialects)', () => { + expect(clean("SELECT `it's` FROM t WHERE a = 'secretF'")).toBe('SELECT ?'); + expect(clean("SELECT * FROM t WHERE a = `x AND b = 'secret' AND c = `")).toBe( + 'SELECT * FROM t WHERE a = ?', ); }); @@ -394,4 +401,12 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = 'SELECT ? WHERE a = ? OR b = ? OR c = ?', ); }); + + it('pins the exact output of truncated and minimal executable comments', () => { + expect(clean('/*!')).toBe(' '); + expect(clean('/*M')).toBe(' '); + expect(clean('/*M!')).toBe(' '); + expect(clean('/*!12')).toBe(' '); + expect(clean('a$$$')).toBe('a$$$'); + }); }); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index dca29495..48a012ff 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -62,9 +62,11 @@ interface Dialect { dollarQuotes: boolean; /** * Which strings a backslash escapes the next character in: every one (MySQL), only `E'..'` ones (Postgres, - * standard_conforming_strings on), every single-quoted one (Postgres, it off), or none (standard SQL, SQLite..). + * standard_conforming_strings on), or none (standard SQL, SQLite..). Postgres with the setting off would be + * 'every single-quoted one', but wherever that differs from the readings below, MySQL and Postgres-on already + * disagree at the same point, so it adds nothing and is not scanned. */ - backslashEscapes: 'all' | 'e' | 'single' | 'none'; + backslashEscapes: 'all' | 'e' | 'none'; } /** @@ -93,16 +95,6 @@ const DIALECTS: readonly Dialect[] = [ dollarQuotes: true, backslashEscapes: 'e', }, - // Postgres, standard_conforming_strings off - { - hashComment: false, - lineEnd: CR_OR_LF, - executableComments: false, - dashNeedsSpace: false, - nestedComments: true, - dollarQuotes: true, - backslashEscapes: 'single', - }, // standard SQL, SQLite, SQL Server, Oracle { hashComment: false, @@ -191,21 +183,23 @@ function scan(statement: string, dialect: Dialect): string { const escapes = dialect.backslashEscapes === 'all' || (ch === "'" && - (dialect.backslashEscapes === 'single' || - (dialect.backslashEscapes === 'e' && - /[eE]/.test(statement[i - 1] ?? '') && - !isWordChar(statement[i - 2])))); + dialect.backslashEscapes === 'e' && + /[eE]/.test(statement[i - 1] ?? '') && + !isWordChar(statement[i - 2])); const end = runEnd(statement, i, escapes); out += '?'; if (end === -1) break; i = end; } else if (ch === '`') { const end = runEnd(statement, i, false); // backticks never take a backslash escape - if (end === -1) { + // Only MySQL and SQLite read a backtick as a quote; elsewhere it is a stray character and a quote inside + // the run is a real delimiter. A quote in the run is therefore ambiguous: fail closed. + const run = end === -1 ? undefined : statement.slice(i, end); + if (run === undefined || /['"]/.test(run)) { out += '?'; break; } - out += statement.slice(i, end); + out += run; i = end; } else if (ch === '$' && dialect.dollarQuotes && !isWordChar(statement[i - 1])) { DOLLAR_TAG.lastIndex = i; From d4d47ed15590531e10294a09a8529eabdb2c251c Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 28 Oct 2026 15:37:02 +0500 Subject: [PATCH 07/12] fix(performance): dollar quotes after backticks and digits fail closed (#109) Co-Authored-By: Claude Sonnet 5.5 --- packages/performance/src/span-sanitizer.test.ts | 9 +++++++++ packages/performance/src/span-sanitizer.ts | 10 +++++++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index 65d6e934..92317487 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -402,6 +402,15 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = ); }); + it.each([ + ['SELECT `$$`, secret, `$$` FROM t', 'secret'], + ['SELECT a `$$secret$$` b FROM t', 'secret'], + ['SELECT 1$$secret$$', 'secret'], + ['SELECT * FROM t WHERE a = $1$$secret$$', 'secret'], + ])('fails closed on a dollar quote after a backtick or a digit: %j', (sql, secret) => { + expect(clean(sql)).not.toContain(secret); + }); + it('pins the exact output of truncated and minimal executable comments', () => { expect(clean('/*!')).toBe(' '); expect(clean('/*M')).toBe(' '); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index 48a012ff..156c6e4a 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -36,7 +36,11 @@ const CONTENT_KEYS = new Set([ /** Keys carrying a database statement, across the OTel conventions that have named it differently. */ const STATEMENT_KEYS = new Set(['db.statement', 'db.query.text']); -/** Can this character be part of an identifier (so a `$` right after it is not a dollar-quote opener)? */ +/** Could a `$` right after this character be part of an identifier? A DIGIT does not count (`1$$x$$` opens a quote). */ +const isIdentifierTail = (ch: string | undefined): boolean => + ch !== undefined && /[A-Za-z_$\u0080-￿]/.test(ch); + +/** Is this an identifier character, digits included (for the `E` string prefix check)? */ const isWordChar = (ch: string | undefined): boolean => ch !== undefined && /[A-Za-z0-9_$]/.test(ch); @@ -195,13 +199,13 @@ function scan(statement: string, dialect: Dialect): string { // Only MySQL and SQLite read a backtick as a quote; elsewhere it is a stray character and a quote inside // the run is a real delimiter. A quote in the run is therefore ambiguous: fail closed. const run = end === -1 ? undefined : statement.slice(i, end); - if (run === undefined || /['"]/.test(run)) { + if (run === undefined || /['"$]/.test(run)) { out += '?'; break; } out += run; i = end; - } else if (ch === '$' && dialect.dollarQuotes && !isWordChar(statement[i - 1])) { + } else if (ch === '$' && dialect.dollarQuotes && !isIdentifierTail(statement[i - 1])) { DOLLAR_TAG.lastIndex = i; const tag = DOLLAR_TAG.exec(statement)?.[0]; if (tag === undefined) { From a85b5a78d1928a12e0d2a1f01a183fd342c612c5 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 28 Oct 2026 15:46:33 +0500 Subject: [PATCH 08/12] fix(performance): backtick runs with comment/dollar openers fail closed; underscore exponents; document cut cases (#109) Co-Authored-By: Claude Sonnet 5.5 --- packages/performance/src/span-sanitizer.test.ts | 13 +++++++++++++ packages/performance/src/span-sanitizer.ts | 6 ++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index 92317487..394c4413 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -411,6 +411,19 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = expect(clean(sql)).not.toContain(secret); }); + it.each([ + ['SELECT `a $$ secret ` $$', 'secret'], + ["SELECT ` -- secret `\n FROM t WHERE a = 'x'", 'secret'], + ['SELECT ` /* secret */ ` FROM t', 'secret'], + ["SELECT ` # secret `\n FROM t WHERE a = 'x'", 'secret'], + ])('fails closed on a comment or dollar opener inside a backtick run: %j', (sql, secret) => { + expect(clean(sql)).not.toContain(secret); + }); + + it('redacts an exponent with underscore separators', () => { + expect(clean('SELECT 1e1_000')).toBe('SELECT ?'); + }); + it('pins the exact output of truncated and minimal executable comments', () => { expect(clean('/*!')).toBe(' '); expect(clean('/*M')).toBe(' '); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index 156c6e4a..98f76506 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -199,7 +199,7 @@ function scan(statement: string, dialect: Dialect): string { // Only MySQL and SQLite read a backtick as a quote; elsewhere it is a stray character and a quote inside // the run is a real delimiter. A quote in the run is therefore ambiguous: fail closed. const run = end === -1 ? undefined : statement.slice(i, end); - if (run === undefined || /['"$]/.test(run)) { + if (run === undefined || /['"$#]|--|\/\*/.test(run)) { out += '?'; break; } @@ -241,6 +241,8 @@ function scan(statement: string, dialect: Dialect): string { * where the readings first disagree: the agreed prefix is kept, the rest is redacted. Anything that never * closes (including a statement cut by a length cap) likewise fails CLOSED to the end. The price is shape: * a statement using a dialect-specific construct may lose its tail, which is the safe side of the trade. + * Examples that cut: `#` (MySQL comment, Postgres JSON operator `#>`, SQL Server `#tmp`), `$$` bodies, + * a backslash-escaped quote, and MySQL-style `/*!` / `/*+` comments (so Oracle-style hints cut too). */ export function redactSqlLiterals(statement: string): string { const [first, ...rest] = DIALECTS.map((dialect) => scan(statement, dialect)) as [ @@ -256,7 +258,7 @@ export function redactSqlLiterals(statement: string): string { } // numeric literals (decimal, exponent, hex/binary/octal, underscore-separated), but never the digits inside an identifier like `column2` return out.replace( - /\b(?:0x[0-9a-f_]+|0b[01_]+|0o[0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d+)?)\b/gi, + /\b(?:0x[0-9a-f_]+|0b[01_]+|0o[0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d[\d_]*)?)\b/gi, '?', ); } From 8fbab997054eeb42f5d602364632bf798130ea0c Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 28 Oct 2026 21:07:19 +0500 Subject: [PATCH 09/12] test(performance): pin cross-dialect cut shape losses, CR line-comment output and bracket-identifier gap (#109) Co-Authored-By: Claude Sonnet 5.5 --- .../performance/src/span-sanitizer.test.ts | 33 +++++++++++++++++-- packages/performance/src/span-sanitizer.ts | 2 +- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index 394c4413..a784101a 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -307,6 +307,10 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = ); }); + it('fails closed on a double quote inside a backtick run', () => { + expect(clean('SELECT `a"b` FROM t WHERE x = "secretD"')).toBe('SELECT ?'); + }); + it('fails closed on an unterminated backtick identifier', () => { expect(clean("SELECT `it's 'secret")).toBe('SELECT ?'); }); @@ -391,8 +395,17 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = }); it('ends # and -- comments at LF only for MySQL and SQLite, so a CR cannot hide a literal', () => { - expect(clean("SELECT c FROM t -- see\r it's\n WHERE a = 'k' AND p = 'secret'")).not.toContain( - 'secret', + expect(clean("SELECT c FROM t -- see\r it's\n WHERE a = 'k' AND p = 'secret'")).toBe( + 'SELECT c FROM t ?', + ); + }); + + it('documents the unmodelled dialect gaps: bracket identifiers and q-quotes are not tokenised', () => { + // Known, pre-existing (the old regex leaked these too) and out of scope for #109: an apostrophe inside + // `[..]` or `q'[..]'` shifts the pairing identically in every reading, so nothing is cut. Pinned so a + // future fix has to change this test on purpose. + expect(clean("SELECT [it's] FROM t WHERE a = 'secret1' AND b = 'x'")).toBe( + 'SELECT [it?secret1?x?', ); }); @@ -420,6 +433,22 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = expect(clean(sql)).not.toContain(secret); }); + it('pins the known shape losses of the cross-dialect cut (safe side: no literal survives)', () => { + expect(clean("SELECT data #> '{a}' FROM t WHERE id = 5")).toBe('SELECT data ?'); + expect(clean("SELECT * FROM #tmp WHERE id = 5 AND n = 'x'")).toBe('SELECT * FROM ?'); + expect(clean("SELECT 1 /*+ IndexScan(t) */ FROM t WHERE a = 'x'")).toBe('SELECT ? ?'); + }); + + it('cuts at the first differing OUTPUT position; what is kept is a prefix of every reading own output', () => { + // MySQL: `'a\'secretZ'` is one literal and `tail` an alias; Postgres/standard: `'a\'`, code `secretZ`, then an + // unterminated literal. The readings print `?tail` and `?secretZ?`, so the cut is after the first `?`. + expect(clean("SELECT 'a\\'secretZ'tail")).toBe('SELECT ??'); + // Text that every reading prints as code stays, even though the readings map it to different input ranges + // (MySQL: the trailing word; Postgres: the one inside the quotes). Each kept character is part of each + // reading's own redacted output, so it discloses nothing any single reading would not. + expect(clean("SELECT 'a\\'PASSWORD'PASSWORD")).toBe('SELECT ?PASSWORD?'); + }); + it('redacts an exponent with underscore separators', () => { expect(clean('SELECT 1e1_000')).toBe('SELECT ?'); }); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index 98f76506..a58f6754 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -99,7 +99,7 @@ const DIALECTS: readonly Dialect[] = [ dollarQuotes: true, backslashEscapes: 'e', }, - // standard SQL, SQLite, SQL Server, Oracle + // standard SQL and SQLite. SQL Server `[..]` identifiers and Oracle `q'..'` quoting are NOT modelled (known gap) { hashComment: false, lineEnd: LF, From a2e31a648a27624c9f21e43e9b27f0a6143bffcf Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 28 Oct 2026 21:18:59 +0500 Subject: [PATCH 10/12] fix(performance): compare SQL dialect readings by source position, not printed text (#109) A suffix that printed identically but came from different input (literal content in one reading, code in another) was kept as agreed. Co-Authored-By: Claude Sonnet 5.5 --- .../performance/src/span-sanitizer.test.ts | 21 +++---- packages/performance/src/span-sanitizer.ts | 59 +++++++++++++------ 2 files changed, 51 insertions(+), 29 deletions(-) diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index a784101a..06e6c5e6 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -338,7 +338,7 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = it('handles nested block comments', () => { // MySQL ends the comment at the first `*/`, Postgres at the second: the readings disagree, so cut. - expect(clean("/* outer /* inner */ it's */ SELECT * FROM t WHERE x = 'secretN'")).toBe(' ?'); + expect(clean("/* outer /* inner */ it's */ SELECT * FROM t WHERE x = 'secretN'")).toBe(' ?'); // ...and when nesting makes no difference the comment is simply dropped. expect(clean("/* a */ SELECT 'secretM' /* b */")).toBe(' SELECT ? '); expect(clean("SELECT 1 /* a /* b */ 'secret")).toBe('SELECT ? ?'); @@ -436,17 +436,18 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = it('pins the known shape losses of the cross-dialect cut (safe side: no literal survives)', () => { expect(clean("SELECT data #> '{a}' FROM t WHERE id = 5")).toBe('SELECT data ?'); expect(clean("SELECT * FROM #tmp WHERE id = 5 AND n = 'x'")).toBe('SELECT * FROM ?'); - expect(clean("SELECT 1 /*+ IndexScan(t) */ FROM t WHERE a = 'x'")).toBe('SELECT ? ?'); + expect(clean("SELECT 1 /*+ IndexScan(t) */ FROM t WHERE a = 'x'")).toBe('SELECT ? ?'); }); - it('cuts at the first differing OUTPUT position; what is kept is a prefix of every reading own output', () => { + it('compares the readings by SOURCE position, so a suffix that only prints the same is cut', () => { // MySQL: `'a\'secretZ'` is one literal and `tail` an alias; Postgres/standard: `'a\'`, code `secretZ`, then an // unterminated literal. The readings print `?tail` and `?secretZ?`, so the cut is after the first `?`. expect(clean("SELECT 'a\\'secretZ'tail")).toBe('SELECT ??'); - // Text that every reading prints as code stays, even though the readings map it to different input ranges - // (MySQL: the trailing word; Postgres: the one inside the quotes). Each kept character is part of each - // reading's own redacted output, so it discloses nothing any single reading would not. - expect(clean("SELECT 'a\\'PASSWORD'PASSWORD")).toBe('SELECT ?PASSWORD?'); + // Here the readings print the SAME word, but it comes from different parts of the input (MySQL: the trailing + // word, where the first is literal content; Postgres: the first). Comparing printed text alone kept it. + expect(clean("SELECT 'a\\'PASSWORD'PASSWORD")).toBe('SELECT ??'); + expect(clean("SELECT 'x\\'SECRET'SECRET FROM t")).toBe('SELECT ??'); + expect(clean("SELECT 'a\\'hunter2'hunter2 FROM t WHERE id = 5")).toBe('SELECT ??'); }); it('redacts an exponent with underscore separators', () => { @@ -454,10 +455,10 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = }); it('pins the exact output of truncated and minimal executable comments', () => { - expect(clean('/*!')).toBe(' '); + expect(clean('/*!')).toBe('?'); expect(clean('/*M')).toBe(' '); - expect(clean('/*M!')).toBe(' '); - expect(clean('/*!12')).toBe(' '); + expect(clean('/*M!')).toBe('?'); + expect(clean('/*!12')).toBe('?'); expect(clean('a$$$')).toBe('a$$$'); }); }); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index a58f6754..b9242266 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -143,9 +143,22 @@ function runEnd(sql: string, start: number, backslashEscapes: boolean): number { return -1; } +/** One reading's output and, per output character, the source offset it came from. */ +interface Scan { + out: string; + pos: number[]; +} + /** One pass over the statement under one dialect: comments dropped, literals replaced by `?`. */ -function scan(statement: string, dialect: Dialect): string { +function scan(statement: string, dialect: Dialect): Scan { let out = ''; + const pos: number[] = []; + // `pos` records the SOURCE offset every output character came from, so readings are compared by where in the + // input a character came from, not just by what it prints (see redactSqlLiterals). + const put = (text: string, at: number): void => { + out += text; + for (let j = 0; j < text.length; j++) pos.push(at + j); + }; let i = 0; let executableDepth = 0; while (i < statement.length) { @@ -160,7 +173,7 @@ function scan(statement: string, dialect: Dialect): string { ) { dialect.lineEnd.lastIndex = i; const eol = dialect.lineEnd.exec(statement)?.index ?? -1; - out += ' '; + put(' ', i); if (eol === -1) break; i = eol; // keep the terminator itself } else if ( @@ -173,13 +186,13 @@ function scan(statement: string, dialect: Dialect): string { i += statement[i + 2] === 'M' ? 4 : 3; while (statement[i] !== undefined && statement[i]! >= '0' && statement[i]! <= '9') i++; executableDepth++; - out += ' '; + put(' ', i); } else if (ch === '*' && next === '/' && executableDepth > 0) { executableDepth--; i += 2; - out += ' '; + put(' ', i); } else if (ch === '/' && next === '*') { - out += ' '; + put(' ', i); const close = blockCommentEnd(statement, i, dialect.nestedComments); if (close === -1) break; i = close; @@ -191,7 +204,7 @@ function scan(statement: string, dialect: Dialect): string { /[eE]/.test(statement[i - 1] ?? '') && !isWordChar(statement[i - 2])); const end = runEnd(statement, i, escapes); - out += '?'; + put('?', i); if (end === -1) break; i = end; } else if (ch === '`') { @@ -200,29 +213,29 @@ function scan(statement: string, dialect: Dialect): string { // the run is a real delimiter. A quote in the run is therefore ambiguous: fail closed. const run = end === -1 ? undefined : statement.slice(i, end); if (run === undefined || /['"$#]|--|\/\*/.test(run)) { - out += '?'; + put('?', i); break; } - out += run; + put(run, i); i = end; } else if (ch === '$' && dialect.dollarQuotes && !isIdentifierTail(statement[i - 1])) { DOLLAR_TAG.lastIndex = i; const tag = DOLLAR_TAG.exec(statement)?.[0]; if (tag === undefined) { - out += ch; + put(ch, i); i++; continue; } const close = statement.indexOf(tag, i + tag.length); - out += '?'; + put('?', i); if (close === -1) break; i = close + tag.length; } else { - out += ch; + put(ch, i); i++; } } - return out; + return { out, pos }; } /** @@ -245,16 +258,24 @@ function scan(statement: string, dialect: Dialect): string { * a backslash-escaped quote, and MySQL-style `/*!` / `/*+` comments (so Oracle-style hints cut too). */ export function redactSqlLiterals(statement: string): string { - const [first, ...rest] = DIALECTS.map((dialect) => scan(statement, dialect)) as [ - string, - ...string[], - ]; - let out = first; + const [first, ...rest] = DIALECTS.map((dialect) => scan(statement, dialect)) as [Scan, ...Scan[]]; + let out = first.out; + let outPos = first.pos; for (const other of rest) { - if (other === out) continue; + // Compare by SOURCE position as well as by character: a suffix that prints the same but comes from a + // different part of the input is literal content in one reading and code in another (`'a\'X'X`). let k = 0; - while (k < out.length && k < other.length && out[k] === other[k]) k++; + while ( + k < out.length && + k < other.out.length && + out[k] === other.out[k] && + outPos[k] === other.pos[k] + ) { + k++; + } + if (k === out.length && k === other.out.length) continue; out = `${out.slice(0, k)}?`; + outPos = [...outPos.slice(0, k), -1]; } // numeric literals (decimal, exponent, hex/binary/octal, underscore-separated), but never the digits inside an identifier like `column2` return out.replace( From 8a12fadd497f87efc2fc4275ef83316eb70b5fc9 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 28 Oct 2026 21:22:12 +0500 Subject: [PATCH 11/12] docs(performance): clarify source-offset bookkeeping in redactSqlLiterals scan (#109) Co-Authored-By: Claude Sonnet 5.5 --- packages/performance/src/span-sanitizer.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index b9242266..fbe2844e 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -153,7 +153,8 @@ interface Scan { function scan(statement: string, dialect: Dialect): Scan { let out = ''; const pos: number[] = []; - // `pos` records the SOURCE offset every output character came from, so readings are compared by where in the + // `pos` records the SOURCE offset every output character came from (for the space an executable-comment + // opener or closer prints, the offset just past it; only MySQL reads those, so it never matches), so readings are compared by where in the // input a character came from, not just by what it prints (see redactSqlLiterals). const put = (text: string, at: number): void => { out += text; From d11fc5903ea8a83f4f3b9ff22a6e3c3744de67f0 Mon Sep 17 00:00:00 2001 From: Alexey Karimov Date: Wed, 28 Oct 2026 21:51:56 +0500 Subject: [PATCH 12/12] fix(performance): redact an exponent after a decimal point with no fraction digits (1.e5) (#109) Co-Authored-By: Claude Sonnet 5.5 --- packages/performance/src/span-sanitizer.test.ts | 7 +++++++ packages/performance/src/span-sanitizer.ts | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index 06e6c5e6..8c18a95a 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -450,6 +450,13 @@ describe('redactSqlLiterals: quotes that are not string delimiters (#109)', () = expect(clean("SELECT 'a\\'hunter2'hunter2 FROM t WHERE id = 5")).toBe('SELECT ??'); }); + it('redacts an exponent after a decimal point with no fraction digits', () => { + expect(clean('SELECT 1.e5 FROM t')).toBe('SELECT ? FROM t'); + expect(clean('SELECT 123.e45, .5e3, 1.5e+3 FROM t')).toBe('SELECT ?, .?, ? FROM t'); + expect(clean('SELECT 12.E-7')).toBe('SELECT ?'); + expect(clean('SELECT 1..2, a1.e FROM t')).toBe('SELECT ?..?, a1.e FROM t'); + }); + it('redacts an exponent with underscore separators', () => { expect(clean('SELECT 1e1_000')).toBe('SELECT ?'); }); diff --git a/packages/performance/src/span-sanitizer.ts b/packages/performance/src/span-sanitizer.ts index fbe2844e..958ba3d3 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -280,7 +280,7 @@ export function redactSqlLiterals(statement: string): string { } // numeric literals (decimal, exponent, hex/binary/octal, underscore-separated), but never the digits inside an identifier like `column2` return out.replace( - /\b(?:0x[0-9a-f_]+|0b[01_]+|0o[0-7_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d[\d_]*)?)\b/gi, + /\b(?:0x[0-9a-f_]+|0b[01_]+|0o[0-7_]+|\d[\d_]*(?:\.(?:\d[\d_]*)?)?(?:e[+-]?\d[\d_]*)?)\b/gi, '?', ); }