:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(logs): close five under-masking gaps in log patterns (#93844)
Jimmy Zhudc564fc48327
diff --git a/nodejs/src/logs/log-pattern-mask.test.ts b/nodejs/src/logs/log-pattern-mask.test.tsindex bb1688094153..5cad6adeef22 100644--- a/nodejs/src/logs/log-pattern-mask.test.ts+++ b/nodejs/src/logs/log-pattern-mask.test.ts@@ -33,10 +33,16 @@ describe('log-pattern-mask', () => {],['klogtime warning severity', 'W0101 00:00:00 rotating', 'W<KLOGTIME> rotating'],['klogtime at the MMDD upper bound', 'F1231 23:59:59 shutdown', 'F<KLOGTIME> shutdown'],+ ['clftime', '10.0.0.1 - - [02/Jan/2026:03:04:05 +0000] "GET /a"', '<IP> - - [<TIMESTAMP>] "GET /a"'],+ ['ctime with a zone', 'booted Mon Jan 2 03:04:05 UTC 2026 ok', 'booted <TIMESTAMP> ok'],+ ['ctime without a zone', 'booted Mon Jan 12 03:04:05 2026 ok', 'booted <TIMESTAMP> ok'],+ ['httpdate', 'expires Mon, 02 Jan 2026 03:04:05 GMT now', 'expires <TIMESTAMP> now'],+ ['syslogtime', 'Jan 2 03:04:05 host sshd: accepted', '<TIMESTAMP> host sshd: accepted'],['uuid', 'request 0f2d6faf-07e3-4cff-bf47-7efa1024aee2 failed', 'request <UUID> failed'],['email', 'user [email protected] rejected', 'user <EMAIL> rejected'],['hex0x', 'fault at 0xdeadBEEF handler', 'fault at <HEX> handler'],['hex long run', 'trace deadbeefdeadbeef00 end', 'trace <HEX> end'],+ ['hex at the short floor', 'built sha a3f9c1d2 ok', 'built sha <HEX> ok'],['ipv4', 'connection from 10.0.0.1 refused', 'connection from <IP> refused'],['num', 'retry 5 of 7', 'retry <N> of <N>'],])('rule %s masks the token and leaves neighbouring text intact', (_name, input, expected) => {@@ -66,10 +72,73 @@ describe('log-pattern-mask', () => {'processed 1234 12:34:56 rows','processed <N> <N>:<N>:<N> rows',],+ [+ 'a ctime line loses its weekday, which the month rule alone would strand',+ 'Mon Jan 2 03:04:05 UTC 2026 boot',+ '<TIMESTAMP> boot',+ ],+ ['an http date loses its weekday too', 'Mon, 02 Jan 2026 03:04:05 GMT boot', '<TIMESTAMP> boot'],])('ordering: %s', (_name, input, expected) => {expect(maskString(input).masked).toEqual(expected)})+ // Each name-carrying date rule needs a real date around the name, for the same reason the+ // klog guards are asserted from the negative side: a bare month or weekday is ordinary+ // English, and masking it would merge lines that have nothing to do with each other.+ it.each([+ ['a bare month name in prose', 'May retry 3 times', 'May retry <N> times'],+ ['a bare weekday in prose', 'Mon deploy window 2', 'Mon deploy window <N>'],+ ['a month name without a time', 'Jan 2 rows written', 'Jan <N> rows written'],+ ['a weekday with a time but no date', 'Mon 03:04:05 tick', 'Mon <N>:<N>:<N> tick'],+ ['a day of month above 31', 'Jan 32 03:04:05 x', 'Jan <N> <N>:<N>:<N> x'],+ // A severity word has the shape of a zone, and a count has the shape of a year, so an+ // open zone or year lets `ctime` take both out of the pattern and merge an ERROR line+ // with a WARN one. The count here sits inside the year range the rule accepts, which is+ // where an open zone alone still loses it.+ [+ 'a severity word and the count behind it',+ 'Mon Jan 2 03:04:05 ERROR 2341 connections',+ '<TIMESTAMP> ERROR <N> connections',+ ],+ [+ 'a count that reads exactly like this year',+ 'Mon Jan 2 03:04:05 WARN 2026 connections',+ '<TIMESTAMP> WARN <N> connections',+ ],+ // An unlisted zone costs grouping, not correctness: the date still masks, and the zone+ // and year stay rather than disappearing with it.+ [+ 'a zone outside the known set, which falls to the month rule',+ 'booted Mon Jan 2 03:04:05 XYZQ 2026 ok',+ 'booted <TIMESTAMP> XYZQ <N> ok',+ ],+ [+ 'an impossible day in an http date',+ 'Mon, 99 Jan 2026 03:04:05 GMT open',+ 'Mon, <N> Jan <N> <N>:<N>:<N> GMT open',+ ],+ ])('date rules do not claim %s', (_name, input, expected) => {+ expect(maskString(input).masked).toEqual(expected)+ })++ it.each([+ ['shared object files are not hosts', 'loading libssl.so failed', 'loading libssl.so failed'],+ ['shell scripts are not hosts', 'running deploy.sh in 2s', 'running deploy.sh in <N>s'],+ ])('%s', (_name, input, expected) => {+ expect(maskString(input).masked).toEqual(expected)+ })++ // The hex rule needs a letter, which is what keeps its 8-char floor off plain numbers. Without+ // the letter, every id, epoch, and byte count of 8 or more digits would read as `<HEX>`.+ it.each([+ ['a short digit run stays a number', 'offset 1724495000 read', 'offset <N> read'],+ ['a long digit run stays a number', 'id 1234567890123456 seen', 'id <N> seen'],+ ['a hex run under the floor is left alone', 'code abc12 seen', 'code abc12 seen'],+ ['a hex run inside an identifier is left alone', 'key deadbeef_1 seen', 'key deadbeef_1 seen'],+ ])('hex letter requirement: %s', (_name, input, expected) => {+ expect(maskString(input).masked).toEqual(expected)+ })+// The klog rule reaches text `\b\d+` cannot, so each guard is asserted from the negative// side too: a near-miss must fall through to `num` and keep its digits, which is what stops// two unrelated messages from collapsing onto one pattern.@@ -112,6 +181,10 @@ describe('log-pattern-mask', () => {expect(byName).toEqual({timestamp: 0,klogtime: 1,+ clftime: 0,+ ctime: 0,+ httpdate: 0,+ syslogtime: 0,uuid: 0,email: 2,host: 1,@@ -213,10 +286,22 @@ describe('log-pattern-mask', () => {expect(patternOf('{"outer":{"inner":1},"other":[1,2]}')).toEqual('<JSON:other,outer>')})- it('never masks keys, so value-shaped keys stay verbatim', () => {- expect(patternOf('{"10.0.0.1":1,"7141":2,"[email protected]":3}')).toEqual(- '<JSON:10.0.0.1,7141,[email protected]>'+ it('masks keys, so a value-shaped key becomes its placeholder', () => {+ expect(patternOf('{"10.0.0.1":1,"7141":2,"[email protected]":3}')).toEqual('<JSON:<EMAIL>,<IP>,<N>>')+ })++ it('deduplicates masked keys, so an object keyed by data is one key wide', () => {+ const body = JSON.stringify(+ Object.fromEntries(Array.from({ length: 50 }, (_unused, index) => [`10.0.0.${index}`, 1])))+ // Deduplicating before the cap is what drops the overflow suffix too: a `+18` here+ // would carry the raw key count back into the pattern.+ expect(patternOf(body)).toEqual('<JSON:<IP>>')+ })++ it('counts key masking in the rule fires, so the rule metric still matches what shipped', () => {+ const ipv4 = MASK_RULES.findIndex((rule) => rule.name === 'ipv4')+ expect(patternResult('{"10.0.0.1":1,"10.0.0.2":2}').ruleFires[ipv4]).toEqual(2)})})})@@ -236,9 +321,14 @@ describe('log-pattern-mask', () => {'started at 2026-08-24T10:20:45.123Z ok','I0827 11:39:40.307946 1 proxier.go:1484] reloading','W0101 00:00:00 rotate E0102 01:02:03 retry F0103 02:03:04 exit',+ '10.0.0.1 - - [02/Jan/2026:03:04:05 +0000] "GET /a" 200',+ 'booted Mon Jan 2 03:04:05 UTC 2026, expires Mon, 02 Jan 2026 04:05:06 GMT',+ 'Jan 2 03:04:05 host sshd: accepted','request 0f2d6faf-07e3-4cff-bf47-7efa1024aee2 took 7141ms','mail [email protected] via api.example.com at 10.0.0.7 slot 0xdeadbeef','checksum deadbeefdeadbeef00 verified',+ 'built sha a3f9c1d2 from 1724495000',+ '{"10.0.0.1":1,"10.0.0.2":2}',...MESSAGE_KEYS.map((key) => JSON.stringify({ [key]: 'served 3 requests', level: 'info' })),'{"msg":"loses 2","message":"wins 1"}',// Reach `extractJsonMessage` itself, not just the keys it reads. Widening it to accept a@@ -270,6 +360,7 @@ describe('log-pattern-mask', () => {*/const SHAPE_DIGESTS: Record<number, string> = {3: 'd7b045b1054244d1',+ 4: '357baaab19f622df',}/**@@ -361,6 +452,13 @@ describe('log-pattern-mask', () => {'batch 5 7 11 done at 2026-08-24 10:20:45,001','no variable parts in this line at all','mixed [email protected] then 192.168.0.1 then [email protected]',+ // A weekday form and the month form overlap: the chain would let `syslogtime` cut the+ // line first and strand the weekday, unless the weekday rules are listed ahead of it.+ 'Mon Jan 2 03:04:05 UTC 2026 boot complete',+ 'expires Mon, 02 Jan 2026 03:04:05 GMT',+ '10.0.0.1 - - [02/Jan/2026:03:04:05 +0000] "GET /v0/export" 200 35',+ 'Jan 2 03:04:05 host sshd: accepted from 10.0.0.1',+ 'built sha a3f9c1d2 at 1724495000 into deadbeefdeadbeef00',]it.each(corpus.map((line) => [line] as const))('%s', (line) => {diff --git a/nodejs/src/logs/log-pattern-mask.ts b/nodejs/src/logs/log-pattern-mask.tsindex 5dbca5b393d0..c9d10e4b0dd3 100644--- a/nodejs/src/logs/log-pattern-mask.ts+++ b/nodejs/src/logs/log-pattern-mask.ts@@ -2,7 +2,7 @@ import { createTrackedRE2 } from '~/common/utils/tracked-re2'import { parseLogBodyForIngestion } from './log-body-parse'-export const PATTERN_VERSION = 3+export const PATTERN_VERSION = 4/*** Everything here shapes the emitted pattern, so it sits inside `PATTERN_VERSION`: two records may@@ -28,7 +28,20 @@ export const PATTERN_CAPS: PatternCaps = Object.freeze({maxOutputChars: 1024,})-export type MaskRuleName = 'timestamp' | 'klogtime' | 'uuid' | 'email' | 'host' | 'hex0x' | 'hex' | 'ipv4' | 'num'+export type MaskRuleName =+ | 'timestamp'+ | 'klogtime'+ | 'clftime'+ | 'ctime'+ | 'httpdate'+ | 'syslogtime'+ | 'uuid'+ | 'email'+ | 'host'+ | 'hex0x'+ | 'hex'+ | 'ipv4'+ | 'num'export type MaskRule = {name: MaskRuleName@@ -36,10 +49,25 @@ export type MaskRule = {replacement: string}+const MONTH = '(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)'+const WEEKDAY = '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)'+const DAY_OF_MONTH = '(?:0?[1-9]|[12]\\d|3[01])'+const TIME_OF_DAY = '\\d{2}:\\d{2}:\\d{2}'+const YEAR = '(?:19|20)\\d{2}'+// `ctime` ends on an optional zone and a year, which is the same shape as an uppercase word and a+// count. Both fields are spelled out so the rule cannot take the second reading: a severity word is+// not a zone, and a count is not a year. Leaving either open merges an ERROR line with a WARN one,+// because the zone and the count both leave the pattern with the date.+//+// `httpdate` already enumerates its zone. A zone missing from this list costs grouping, not+// correctness: the line falls to `syslogtime`, which masks the date and leaves the zone and year.+const ZONE =+ '(?:UT|UTC|GMT|Z|E[SD]T|C[SD]T|M[SD]T|P[SD]T|AK[SD]T|H[SD]T|A[SD]T|N[SD]T|CES?T|EES?T|WES?T|BST|IST|MSK|JST|KST|HKT|SGT|ICT|AE[SD]T|AC[SD]T|AWST|NZ[SD]T|SAST|WAT|CAT|EAT|BRT|ART|GST|PKT)'+export const MASK_RULES: readonly MaskRule[] = [{name: 'timestamp',- pattern: '\\b\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}:\\d{2}(?:[.,]\\d+)?(?:Z|[+-]\\d{2}:?\\d{2})?',+ pattern: `\\b\\d{4}-\\d{2}-\\d{2}[T ]${TIME_OF_DAY}(?:[.,]\\d+)?(?:Z|[+-]\\d{2}:?\\d{2})?`,replacement: '<TIMESTAMP>',},// klog / glog headers ("I0827 11:39:40.307946") carry no year and no separators, so the@@ -65,24 +93,69 @@ export const MASK_RULES: readonly MaskRule[] = [// ("<time> stderr F I0827 ..."), so the header is mid-string in the most common real source....(['I', 'W', 'E', 'F'] as const).map((letter) => ({name: 'klogtime' as const,- pattern: `\\b${letter}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\\d|3[01]) \\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?`,+ pattern: `\\b${letter}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\\d|3[01]) ${TIME_OF_DAY}(?:\\.\\d+)?`,replacement: `${letter}<KLOGTIME>`,})),+ // Date formats that spell the month or the weekday as a name. `\b\d+` masks the digits around+ // the name but cannot touch the name itself, so the name survives into the pattern as a literal:+ // one line splits into 12 patterns over a year, and into 7 over a week once a weekday is in it.+ // Each rule consumes the whole date, so the name leaves with it.+ //+ // The name also guards the match: nothing here claims a bare number followed by a time of day.+ //+ // Order matters between these rules and is asserted by the sequential-chain corpus. A ctime line+ // matches `ctime` and `syslogtime` at the same offset, and only `ctime` reaches the year. Listing+ // it first is what makes a single pass and a rule-at-a-time chain agree: the single pass prefers+ // the earlier alternative on a tie, and the chain runs `ctime` first.+ {+ name: 'clftime',+ pattern: `\\b\\d{2}/${MONTH}/${YEAR}:${TIME_OF_DAY}(?: [+-]\\d{4})?`,+ replacement: '<TIMESTAMP>',+ },+ {+ name: 'ctime',+ pattern: `\\b${WEEKDAY} ${MONTH} {1,2}${DAY_OF_MONTH} ${TIME_OF_DAY}(?: ${ZONE})? ${YEAR}`,+ replacement: '<TIMESTAMP>',+ },+ {+ name: 'httpdate',+ pattern: `\\b${WEEKDAY}, ${DAY_OF_MONTH} ${MONTH} ${YEAR} ${TIME_OF_DAY}(?: GMT| UTC| [+-]\\d{4})?`,+ replacement: '<TIMESTAMP>',+ },+ {+ // The weekday is optional here as well as in `ctime`, because a line can carry one without+ // carrying a year. Without it such a line falls to the month rule, which leaves the weekday+ // behind as a literal and splits the line seven ways over a week.+ name: 'syslogtime',+ pattern: `\\b(?:${WEEKDAY} )?${MONTH} {1,2}${DAY_OF_MONTH} ${TIME_OF_DAY}`,+ replacement: '<TIMESTAMP>',+ },{name: 'uuid',pattern: '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}',replacement: '<UUID>',},{ name: 'email', pattern: '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}', replacement: '<EMAIL>' },+ // The suffix list carries no `so` or `sh`. Both are real TLDs, but the rule cannot tell a host+ // from a filename, and shared object and shell script names reach it far more often than a+ // Somali or Saint Helenian domain does. With them in the list, `libssl.so` and `deploy.sh` both+ // mask to `<HOST>`, which merges lines that name different files.{name: 'host',pattern:- '\\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.){1,8}(?:ai|app|aws|bot|cloud|co|com|de|dev|eu|fr|gg|internal|io|jp|local|me|net|nl|org|sh|so|tv|uk|us|xyz)\\b',+ '\\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.){1,8}(?:ai|app|aws|bot|cloud|co|com|de|dev|eu|fr|gg|internal|io|jp|local|me|net|nl|org|tv|uk|us|xyz)\\b',replacement: '<HOST>',},{ name: 'hex0x', pattern: '\\b0x[0-9a-fA-F]+\\b', replacement: '<HEX>' },- { name: 'hex', pattern: '\\b[0-9a-fA-F]{16,}\\b', replacement: '<HEX>' },+ // The order of the rules below is what keeps a plain digit run on `num`. A whole word of digits+ // reaches `num` before `hex` can see it, so an epoch, an id, or a byte count of 8 or more digits+ // stays `<N>`, and `hex` takes only the runs that hold a letter. Splitting `num` in two is how+ // "hex run containing a letter" reads without a lookahead, which RE2 does not have. `ipv4` leads+ // so a dotted quad stays one match instead of four numbers.{ name: 'ipv4', pattern: '\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b', replacement: '<IP>' },+ { name: 'num', pattern: '\\b\\d+\\b', replacement: '<N>' },+ // Shortest hex run read as an identifier. Git short shas and container ids sit at 8 to 12 chars.+ { name: 'hex', pattern: '\\b[0-9a-fA-F]{8,}\\b', replacement: '<HEX>' },{ name: 'num', pattern: '\\b\\d+', replacement: '<N>' },]@@ -101,9 +174,18 @@ export type MaskResult = {ruleFires: number[]}-export function maskString(input: string): MaskResult {- const ruleFires: number[] = new Array(MASK_RULES.length).fill(0)- const masked = input.replace(MASK_COMBINED_RE, (...args: unknown[]): string => {+/**+ * One zeroed counter per rule in `MASK_RULES`, which `klogtime` spreads over four of.+ *+ * Every result carries a full-width vector, including the bodies that fire no rule at all. A shorter+ * array would read as `undefined` to a caller that indexes by rule position, and reach a counter as+ * `NaN`.+ */+export const zeroRuleFires = (): number[] => new Array(MASK_RULES.length).fill(0)++/** Masks `input` and adds its rule hits into `ruleFires`, so several strings can share one array. */+function maskInto(input: string, ruleFires: number[]): string {+ return input.replace(MASK_COMBINED_RE, (...args: unknown[]): string => {for (let i = 0; i < MASK_RULES.length; i++) {if (args[i + 1] !== undefined) {ruleFires[i]++@@ -112,7 +194,11 @@ export function maskString(input: string): MaskResult {}return args[0] as string})- return { masked, ruleFires }+}++export function maskString(input: string): MaskResult {+ const ruleFires = zeroRuleFires()+ return { masked: maskInto(input, ruleFires), ruleFires }}export type PatternBodyKind = 'empty' | 'plaintext' | 'json_object_or_array' | 'json_string' | 'primitive'@@ -144,17 +230,39 @@ function extractJsonMessage(value: object, messageKeys: readonly string[]): striconst capOutput = (pattern: string): string =>pattern.length > PATTERN_CAPS.maxOutputChars ? pattern.slice(0, PATTERN_CAPS.maxOutputChars) : pattern-function jsonKeySetPattern(value: object): string {- const keys = Object.keys(value).sort()+/**+ * Keys go through the same mask rules as a message, because a key set is just as often built from+ * data: an object keyed by user id, host, or trace id otherwise emits one pattern per record, which+ * is the shape the key set exists to collapse.+ *+ * Deduplicating after the mask is what bounds such an object to a single key, and doing it before+ * the cap keeps the dropped-key count off the raw key count, because `+41` and `+42` are two+ * patterns for one shape.+ */+function jsonKeySetPattern(rawKeys: readonly string[]): { pattern: string; ruleFires: number[] } {+ const ruleFires = zeroRuleFires()+ const masked = new Set<string>()+ for (const key of rawKeys) {+ masked.add(maskInto(key, ruleFires))+ }++ const keys = [...masked].sort()const kept = keys.slice(0, KEY_SET_MAX_KEYS)const overflow = keys.length - kept.length- return `<JSON:${kept.join(',')}${overflow > 0 ? `,+${overflow}` : ''}>`+ return { pattern: `<JSON:${kept.join(',')}${overflow > 0 ? `,+${overflow}` : ''}>`, ruleFires }}export type PatternInputSelection =| { kind: 'empty'; bodyKind: PatternBodyKind; inputCapped: boolean }| { kind: 'mask'; input: string; bodyKind: PatternBodyKind; inputCapped: boolean }- | { kind: 'pattern'; pattern: string; bodyKind: PatternBodyKind; inputCapped: boolean; jsonKeyCount?: number }+ | {+ kind: 'pattern'+ pattern: string+ bodyKind: PatternBodyKind+ inputCapped: boolean+ ruleFires: number[]+ jsonKeyCount?: number+ }export function selectPatternInput(body: string | null | undefined,@@ -176,13 +284,18 @@ export function selectPatternInput(case 'json_object_or_array': {const message = extractJsonMessage(parsed.value, messageKeys)if (message === null) {- const isArray = Array.isArray(parsed.value)+ if (Array.isArray(parsed.value)) {+ return { kind: 'pattern', pattern: JSON_ARRAY, bodyKind, inputCapped, ruleFires: zeroRuleFires() }+ }+ const rawKeys = Object.keys(parsed.value)+ const keySet = jsonKeySetPattern(rawKeys)return {kind: 'pattern',- pattern: isArray ? JSON_ARRAY : jsonKeySetPattern(parsed.value),+ pattern: keySet.pattern,bodyKind,inputCapped,- ...(isArray ? {} : { jsonKeyCount: Object.keys(parsed.value).length }),+ ruleFires: keySet.ruleFires,+ jsonKeyCount: rawKeys.length,}}return { kind: 'mask', input: message, bodyKind, inputCapped }@@ -212,7 +325,7 @@ export function buildLogPattern(body: string | null | undefined, messageKeys: reconst { bodyKind, inputCapped } = selectionif (selection.kind === 'empty') {- return { pattern: '', bodyKind, inputCapped, maskedLength: 0, ruleFires: [] }+ return { pattern: '', bodyKind, inputCapped, maskedLength: 0, ruleFires: zeroRuleFires() }}if (selection.kind === 'pattern') {@@ -222,7 +335,7 @@ export function buildLogPattern(body: string | null | undefined, messageKeys: reinputCapped,maskedLength: selection.pattern.length,...(selection.jsonKeyCount === undefined ? {} : { jsonKeyCount: selection.jsonKeyCount }),- ruleFires: [],+ ruleFires: selection.ruleFires,}}diff --git a/nodejs/src/logs/log-pattern-stage.ts b/nodejs/src/logs/log-pattern-stage.tsindex cc07894b0356..3e032c937587 100644--- a/nodejs/src/logs/log-pattern-stage.ts+++ b/nodejs/src/logs/log-pattern-stage.ts@@ -1,7 +1,7 @@import { performance } from 'node:perf_hooks'import { Counter, Histogram } from 'prom-client'-import { MASK_RULES, MESSAGE_KEYS, PATTERN_VERSION, buildLogPattern } from './log-pattern-mask'+import { MASK_RULES, MESSAGE_KEYS, PATTERN_VERSION, buildLogPattern, zeroRuleFires } from './log-pattern-mask'import type { LogRecord } from './log-record-avro'import type { PipelineStage } from './pipeline/log-processing-pipeline'@@ -67,7 +67,7 @@ export function makePatternMaskingStage(): PipelineStage {function stampBatch(records: LogRecord[]): void {const kindCounts = new Map<string, number>()- const ruleFires: number[] = new Array(MASK_RULES.length).fill(0)+ const ruleFires: number[] = zeroRuleFires()let inputCapped = 0for (const record of records) {diff --git a/nodejs/src/logs/log-pii-scrub.test.ts b/nodejs/src/logs/log-pii-scrub.test.tsindex e799522e858f..111446a79812 100644--- a/nodejs/src/logs/log-pii-scrub.test.ts+++ b/nodejs/src/logs/log-pii-scrub.test.ts@@ -1,7 +1,10 @@+import RE2 from 're2'+import { parseJSON } from '~/common/utils/json-parse'import {PII_REDACTED,+ PII_RULES,encodeAttributeCell,scrubLogRecord,scrubPlainString,@@ -18,17 +21,31 @@ describe('log-pii-scrub', () => {})describe('scrubPlainString', () => {- it('redacts email addresses', () => {- expect(scrubPlainString('contact [email protected] please')).toBe(`contact ${PII_REDACTED} please`)- })-+ // Bearer keeps its prefix, so it is the one shape the table below cannot assert.it('redacts Bearer tokens', () => {expect(scrubPlainString('Authorization: Bearer abc.def.ghi')).toBe(`Authorization: Bearer ${PII_REDACTED}`)})- it('redacts Stripe-style secret keys', () => {- const syntheticStripeTestKey = 'sk_' + 'test_' + '123456789012345678901234'- expect(scrubPlainString(`key ${syntheticStripeTestKey}`)).toBe(`key ${PII_REDACTED}`)+ // Secrets are built by concatenation, so no line of this file reads as a live credential to+ // a secret scanner.+ it.each([+ ['email addresses', '[email protected]'],+ ['Stripe-style secret keys', 'sk_' + 'test_' + '123456789012345678901234'],+ ['GitHub personal access tokens', 'gh' + 'p_' + 'A1b2C3d4E5f6G7h8I9j0KlMnOpQrStUvWxYz'],+ ['GitHub server tokens', 'gh' + 's_' + 'A1b2C3d4E5f6G7h8I9j0KlMnOpQrStUvWxYz'],+ ['Slack tokens', 'xox' + 'b-' + '123456789012-abcdefghijkl'],+ ['AWS access key ids', 'AKIA' + 'IOSFODNN7EXAMPLE'],+ ['JWTs', 'ey' + 'JhbGciOiJIUzI1NiJ9' + '.' + 'eyJzdWIiOiIxMjMifQ' + '.' + 'S1gnAtUr3-_x'],+ ])('redacts %s', (_label, secret) => {+ expect(scrubPlainString(`credential ${secret} rejected`)).toBe(`credential ${PII_REDACTED} rejected`)+ })++ it.each([+ ['a word that opens like a GitHub prefix', 'ghost_writer opened a file'],+ ['a truncated AWS key id', 'AKIAIOSFODNN7 is too short'],+ ['a base64 word that is not a JWT', 'eyJhbGciOiJIUzI1NiJ9 alone'],+ ])('leaves %s alone', (_label, input) => {+ expect(scrubPlainString(input)).toBe(input)})it('does not redact PAN-like digit runs (lite scrub)', () => {@@ -235,4 +252,20 @@ describe('log-pii-scrub', () => {expect(r.body).toBe(PII_REDACTED)})})++ // The redaction loop reads the fired rule off the capture-group index, so a rule that adds a+ // group of its own shifts every rule after it and applies the wrong replacement. That failure is+ // silent: an email would redact as `Bearer {{REDACTED}}`, or a real credential would not redact+ // at all. `MASK_RULES` carries the same ratchet.+ describe('RE2 ratchet', () => {+ it.each(PII_RULES.map((rule) => [rule.name, rule.pattern] as const))(+ 'rule %s compiles under RE2 and uses no lookaround, backreference, or capture group',+ (_name, pattern) => {+ expect(() => new RE2(pattern, 'g')).not.toThrow()+ expect(pattern).not.toMatch(/\(\?=|\(\?!|\(\?</)+ expect(pattern).not.toMatch(/\\[1-9]/)+ expect(pattern.replace(/\\\(/g, '')).not.toMatch(/\((?!\?)/)+ }+ )+ })})diff --git a/nodejs/src/logs/log-pii-scrub.ts b/nodejs/src/logs/log-pii-scrub.tsindex 1b8cc2896032..5bf44d504ed3 100644--- a/nodejs/src/logs/log-pii-scrub.ts+++ b/nodejs/src/logs/log-pii-scrub.ts@@ -1,8 +1,12 @@/*** Lossy ingestion scrub: replace matches with PII_REDACTED ({{REDACTED}}). Scrubs `record.body` and each value in- * `record.attributes` (no JSON parse). Rules: Bearer-shaped tokens, Stripe `sk_*` keys, email addresses.+ * `record.attributes` (no JSON parse). Rules: Bearer-shaped tokens, credential shapes that carry their own issuer+ * prefix (Stripe, GitHub, Slack, AWS access key ids, JWTs), and email addresses.* `resource_attributes` and other string fields (e.g. `service_name`, `severity_text`) are not modified here.*+ * Every rule matches on the shape of the secret itself. That is what lets the scrub run on any string without a+ * parse, and it is why the rule set grows by issuer prefix rather than by secret-holding key name.+ ** **Not guaranteed:** secrets only discoverable by JSON object keys inside `body` (no tree walk), values only in* JSON number/boolean leaves. PAN-like digit runs are not redacted.*@@ -33,11 +37,43 @@ export function encodeAttributeCell(semantic: string): string {return JSON.stringify(semantic)}-/** Bearer (group 1), Stripe sk_* (group 2), email (group 3). Order matches legacy three-pass behavior. */+export type PiiRuleName = 'bearer' | 'stripe' | 'github' | 'slack' | 'aws_access_key_id' | 'jwt' | 'email'++export type PiiRule = {+ name: PiiRuleName+ pattern: string+ replacement: string+}++/**+ * One capture group per rule, in this order, because the redaction loop reads the fired rule off the+ * group index. A rule may not add a group of its own, and `bearer` and `email` keep their original+ * positions so the legacy three-pass order still decides every tie they were deciding before.+ *+ * Rules are ordered issuer-prefix first, `email` last. Only ties matter: RE2 takes the leftmost match+ * and prefers the earlier alternative when two start at the same offset, so `Bearer eyJ...` redacts as+ * a bearer token rather than splitting into a prefix and a JWT.+ */+export const PII_RULES: readonly PiiRule[] = [+ { name: 'bearer', pattern: '(?i:Bearer\\s+[-A-Za-z0-9._~+/]+=*)', replacement: `Bearer ${PII_REDACTED}` },+ { name: 'stripe', pattern: '\\bsk_(?:live|test)_[a-zA-Z0-9]{20,}\\b', replacement: PII_REDACTED },+ // ghp_ personal, gho_ oauth, ghu_ user-to-server, ghs_ server, ghr_ refresh. GitHub issues all of+ // them as 36 base62 chars. The floor of 20 accepts a shorter reissue without a code change.+ { name: 'github', pattern: '\\bgh[pousr]_[A-Za-z0-9]{20,}\\b', replacement: PII_REDACTED },+ { name: 'slack', pattern: '\\bxox[abeprs]-[A-Za-z0-9-]{10,}\\b', replacement: PII_REDACTED },+ { name: 'aws_access_key_id', pattern: '\\b(?:AKIA|ASIA)[0-9A-Z]{16}\\b', replacement: PII_REDACTED },+ // `eyJ` is base64url for `{"`, so this reaches any JWT whose header is a JSON object, whatever+ // signed it. The signature part is unbounded rather than required: `alg: none` leaves it empty.+ {+ name: 'jwt',+ pattern: '\\beyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{4,}\\.[A-Za-z0-9_-]*',+ replacement: PII_REDACTED,+ },+ { name: 'email', pattern: '\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b', replacement: PII_REDACTED },+]+const PII_COMBINED_RE = createTrackedRE2(- '((?i:Bearer\\s+[-A-Za-z0-9._~+/]+=*))' +- '|(\\bsk_(?:live|test)_[a-zA-Z0-9]{20,}\\b)' +- '|(\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b)',+ PII_RULES.map((rule) => `(${rule.pattern})`).join('|'),'g','log-pii-scrub:combined')@@ -51,20 +87,22 @@ export function scrubPlainStringWithStats(input: string): { output: string; piiRPII_COMBINED_RE.lastIndex = 0let match: RegExpExecArray | nullwhile ((match = PII_COMBINED_RE.exec(input)) !== null) {- const [matched, bearer, stripe, email] = match+ const matched = match[0]if (matched.length === 0) {PII_COMBINED_RE.lastIndex += 1continue}- let replacement: string- if (bearer !== undefined) {- replacement = `Bearer ${PII_REDACTED}`- } else if (stripe !== undefined) {- replacement = PII_REDACTED- } else if (email !== undefined) {- replacement = PII_REDACTED- } else {+ // Indexed loop, not `findIndex`: a callback here allocates a closure per match, which is+ // the cost this loop exists to avoid.+ let replacement: string | null = null+ for (let i = 0; i < PII_RULES.length; i++) {+ if (match[i + 1] !== undefined) {+ replacement = PII_RULES[i].replacement+ break+ }+ }+ if (replacement === null) {continue}piiReplacements += 1