diff --git a/packages/performance/src/span-sanitizer.test.ts b/packages/performance/src/span-sanitizer.test.ts index f6efb0a4..8c18a95a 100644 --- a/packages/performance/src/span-sanitizer.test.ts +++ b/packages/performance/src/span-sanitizer.test.ts @@ -240,11 +240,232 @@ 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', () => { + // 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 ??'); + }); + + 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', () => { + 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', () => { + 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 = ?', + ); + }); + + 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 ?'); + }); + + 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('fails closed on a # (a MySQL comment, a Postgres operator)', () => { + expect(clean("SELECT 1 # it's\nFROM t WHERE x = 'secretH'")).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('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 ?'); + }); + + 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'); + }); + + 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('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'")).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?', + ); + }); + + 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 = ?', + ); + }); + + 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.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('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('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 ??'); + // 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 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 ?'); + }); + + 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 d35befeb..958ba3d3 100644 --- a/packages/performance/src/span-sanitizer.ts +++ b/packages/performance/src/span-sanitizer.ts @@ -36,27 +36,252 @@ 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']); +/** 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); + +const DOLLAR_TAG = /\$(?:[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_\u0080-\uFFFF]*)?\$/y; + +/** 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). */ + nestedComments: boolean; + /** `$tag$ .. $tag$` is a quoted body (Postgres). */ + dollarQuotes: boolean; + /** + * Which strings a backslash escapes the next character in: every one (MySQL), only `E'..'` ones (Postgres, + * 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' | 'none'; +} + +/** + * 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, + lineEnd: LF, + executableComments: true, + dashNeedsSpace: true, + nestedComments: false, + dollarQuotes: false, + backslashEscapes: 'all', + }, + // Postgres, standard_conforming_strings on + { + hashComment: false, + lineEnd: CR_OR_LF, + executableComments: false, + dashNeedsSpace: false, + nestedComments: true, + dollarQuotes: true, + backslashEscapes: 'e', + }, + // standard SQL and SQLite. SQL Server `[..]` identifiers and Oracle `q'..'` quoting are NOT modelled (known gap) + { + hashComment: false, + lineEnd: LF, + executableComments: false, + dashNeedsSpace: false, + nestedComments: false, + dollarQuotes: false, + backslashEscapes: 'none', + }, +]; + +/** 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 === '/*' && (nested || depth === 0)) { + depth++; + i++; + } else if (pair === '*/') { + depth--; + i++; + if (depth === 0) return i + 1; + } + } + return -1; +} + +/** 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++) { + const ch = sql[i]; + if (backslashEscapes && ch === '\\') { + i++; + } else if (ch === quote) { + if (sql[i + 1] !== quote) return i + 1; + i++; // doubled quote: SQL's own escape + } + } + 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): Scan { + let out = ''; + const pos: number[] = []; + // `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; + for (let j = 0; j < text.length; j++) pos.push(at + j); + }; + let i = 0; + let executableDepth = 0; + while (i < statement.length) { + const ch = statement[i] as string; + const next = statement[i + 1]; + const afterDash = statement[i + 2]; + if ( + (ch === '-' && + next === '-' && + (!dialect.dashNeedsSpace || afterDash === undefined || afterDash <= ' ')) || + (ch === '#' && dialect.hashComment) + ) { + dialect.lineEnd.lastIndex = i; + const eol = dialect.lineEnd.exec(statement)?.index ?? -1; + put(' ', i); + 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++; + put(' ', i); + } else if (ch === '*' && next === '/' && executableDepth > 0) { + executableDepth--; + i += 2; + put(' ', i); + } else if (ch === '/' && next === '*') { + put(' ', i); + const close = blockCommentEnd(statement, i, dialect.nestedComments); + if (close === -1) break; + i = close; + } else if (ch === "'" || ch === '"') { + const escapes = + dialect.backslashEscapes === 'all' || + (ch === "'" && + dialect.backslashEscapes === 'e' && + /[eE]/.test(statement[i - 1] ?? '') && + !isWordChar(statement[i - 2])); + const end = runEnd(statement, i, escapes); + put('?', i); + if (end === -1) break; + i = end; + } else if (ch === '`') { + const end = runEnd(statement, i, false); // backticks never take a backslash escape + // 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)) { + put('?', i); + break; + } + 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) { + put(ch, i); + i++; + continue; + } + const close = statement.indexOf(tag, i + tag.length); + put('?', i); + if (close === -1) break; + i = close + tag.length; + } else { + put(ch, i); + i++; + } + } + return { out, pos }; +} + /** * 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. 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. + * 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 { - 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, '?') + 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) { + // 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.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( + /\b(?:0x[0-9a-f_]+|0b[01_]+|0o[0-7_]+|\d[\d_]*(?:\.(?:\d[\d_]*)?)?(?:e[+-]?\d[\d_]*)?)\b/gi, + '?', ); }