Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(audit-log): address review on free-text normalization
Vlad Ligai5d1ef3892afc
diff --git a/backend/src/ee/services/audit-log/audit-log-queue.test.ts b/backend/src/ee/services/audit-log/audit-log-queue.test.tsindex baadb43cab..b7b12647d4 100644--- a/backend/src/ee/services/audit-log/audit-log-queue.test.ts+++ b/backend/src/ee/services/audit-log/audit-log-queue.test.ts@@ -404,4 +404,80 @@ describe("audit-log-queue unified consumer", () => {expect(release).toHaveBeenCalledTimes(1);});++ describe("free-text normalization reaches both sinks", () => {+ const NUL = String.fromCharCode(0);+ const ESC = String.fromCharCode(0x1b);+ const RLO = String.fromCodePoint(0x202e);++ const hostileEntry = () =>+ streamEntry({+ projectId: "p1",+ projectName: `proj${RLO}x`,+ ipAddress: `1.1.1.1${String.fromCharCode(0x9b)}[31m`,+ userAgent: `Agent/1.0${ESC}[31m`,+ actor: { type: "user", metadata: { name: `svc${NUL}acct` } },+ event: {+ type: "test-event",+ metadata: { reason: `approved by${String.fromCharCode(10)}ops`, nested: { note: `a${RLO}b` } }+ }+ });++ // projectName is only carried on the postgres path, so the clickhouse case opts out of it.+ const expectClean = (row: Record<string, unknown>, { withProjectName = true } = {}) => {+ if (withProjectName) expect(row.projectName).toBe("projx");+ expect(row.ipAddress).toBe("1.1.1.1[31m");+ expect(row.userAgent).toBe("Agent/1.0");+ expect((row.actorMetadata as Record<string, unknown>).name).toBe("svcacct");++ const eventMetadata = row.eventMetadata as Record<string, unknown>;+ expect(eventMetadata.reason).toBe("approved by ops");+ expect((eventMetadata.nested as Record<string, unknown>).note).toBe("ab");+ };++ test("the postgres insert receives normalized values", async () => {+ const { consumer, auditLogDAL, keyStore } = await createHarness();+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([hostileEntry()]));++ await consumer();++ expectClean(auditLogDAL.batchCreate.mock.calls[0][0][0]);+ });++ test("the stream outbox receives the same normalized rows", async () => {+ const { consumer, auditLogStreamOutboxService, keyStore } = await createHarness({ streamsEnabled: true });+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([hostileEntry()]));++ await consumer();++ expect(auditLogStreamOutboxService.enqueueForLogs).toHaveBeenCalledTimes(1);+ expectClean(auditLogStreamOutboxService.enqueueForLogs.mock.calls[0][0][0] as Record<string, unknown>);+ });++ test("the clickhouse insert receives normalized values", async () => {+ const { consumer, clickhouseClient, keyStore } = await createHarness({ clickhouse: true });+ keyStore.streamCollect.mockResolvedValueOnce(collectResult([hostileEntry()]));++ await consumer();++ expectClean(clickhouseClient!.insert.mock.calls[0][0].values[0], { withProjectName: false });+ });++ test("legitimate nesting survives the walk intact", async () => {+ const { consumer, auditLogDAL, keyStore } = await createHarness();+ let claims: Record<string, unknown> = { sub: `id${NUL}1`, keep: 7 };+ for (let i = 0; i < 20; i += 1) claims = { nested: claims };+ keyStore.streamCollect.mockResolvedValueOnce(+ collectResult([streamEntry({ event: { type: "test-event", metadata: { oidcClaimsReceived: claims } } })])+ );++ await consumer();++ const row = auditLogDAL.batchCreate.mock.calls[0][0][0];+ let cursor = (row.eventMetadata as Record<string, unknown>).oidcClaimsReceived as Record<string, unknown>;+ for (let i = 0; i < 20; i += 1) cursor = cursor.nested as Record<string, unknown>;+ expect(cursor.sub).toBe("id1");+ expect(cursor.keep).toBe(7);+ });+ });});diff --git a/backend/src/lib/validator/log-safe-text.test.ts b/backend/src/lib/validator/log-safe-text.test.tsindex da17742d82..dc41cb92a4 100644--- a/backend/src/lib/validator/log-safe-text.test.ts+++ b/backend/src/lib/validator/log-safe-text.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from "vitest";-import { containsLogUnsafeCharacters, DEPTH_LIMIT_MARKER, sanitizeLogPayload, sanitizeLogText } from "./log-safe-text";+import { containsLogUnsafeCharacters, sanitizeLogPayload, sanitizeLogText } from "./log-safe-text";const NUL = String.fromCharCode(0);const ESC = String.fromCharCode(27);@@ -88,15 +88,19 @@ describe("sanitizeLogPayload", () => {expect(sanitizeLogPayload(null)).toBeNull();});- test("marks the subtree at the depth cap rather than dropping it silently", () => {- let deep: Record<string, unknown> = { value: `a${NUL}b` };+ test("preserves deep structure instead of truncating it", () => {+ // oidcClaimsReceived carries whatever the IdP returned, so nesting is legitimate and the shape+ // is part of what downstream consumers parse.+ let deep: Record<string, unknown> = { value: `a${NUL}b`, keep: 7 };for (let i = 0; i < 40; i += 1) deep = { nested: deep };const sanitized = sanitizeLogPayload(deep);- let cursor: unknown = sanitized;- for (let i = 0; i < 12; i += 1) cursor = (cursor as Record<string, unknown>).nested;- expect(cursor).toBe(DEPTH_LIMIT_MARKER);+ let cursor: Record<string, unknown> = sanitized;+ for (let i = 0; i < 40; i += 1) cursor = cursor.nested as Record<string, unknown>;++ expect(cursor.value).toBe("ab");+ expect(cursor.keep).toBe(7);});test("keeps both fields when two keys normalize to the same string", () => {@@ -128,6 +132,39 @@ describe("sanitizeLogPayload", () => {expect(containsLogUnsafeCharacters(persian)).toBe(false);});+ test.each([+ ["arabic letter mark", 0x061c],+ ["mongolian vowel separator", 0x180e],+ ["word joiner", 0x2060],+ ["interlinear annotation anchor", 0xfff9],+ ["musical format control", 0x1d173],+ ["tag character", 0xe0020]+ ])("catches the %s", (_label, code) => {+ const value = `a${String.fromCodePoint(code)}b`;++ expect(containsLogUnsafeCharacters(value)).toBe(true);+ expect(sanitizeLogText(value)).toBe("ab");+ });++ test("line and paragraph separators collapse like other line breaks", () => {+ expect(sanitizeLogText(`one${String.fromCodePoint(0x2028)}two`)).toBe("one two");+ expect(sanitizeLogText(`one${String.fromCodePoint(0x2029)}two`)).toBe("one two");+ });++ test.each([0x2028, 0x2029])("a single-line field rejects U+%s", (code) => {+ const value = `one${String.fromCodePoint(code)}two`;++ expect(containsLogUnsafeCharacters(value)).toBe(true);+ expect(containsLogUnsafeCharacters(value, { allowMultiline: true })).toBe(false);+ });++ test("keeps variation selectors, which choose emoji presentation", () => {+ const flag = String.fromCodePoint(0x1f3f3, 0xfe0f);++ expect(containsLogUnsafeCharacters(flag)).toBe(false);+ expect(sanitizeLogText(flag)).toBe(flag);+ });+test("still strips the zero-width space itself", () => {expect(sanitizeLogText(`ad${ZWSP}min`)).toBe("admin");expect(containsLogUnsafeCharacters(`ad${ZWSP}min`)).toBe(true);diff --git a/backend/src/lib/validator/log-safe-text.ts b/backend/src/lib/validator/log-safe-text.tsindex 6fddbc5972..79954b5ca5 100644--- a/backend/src/lib/validator/log-safe-text.ts+++ b/backend/src/lib/validator/log-safe-text.ts@@ -1,7 +1,9 @@+import RE2 from "re2";+/*** Normalizes free text bound for an audit record: C0/C1 controls, ANSI escapes, bidirectional- * overrides and zero-width characters. All are legal in JSON, so well-formed output says nothing- * about how a value renders in a terminal, a CSV export or a line-based SIEM.+ * overrides and invisible formatting characters. All are legal in JSON, so well-formed output says+ * nothing about how a value renders in a terminal, a CSV export or a line-based SIEM.** Reject at the API boundary, where the caller can correct its input; strip on the way into the* log, where dropping the event would lose the record.@@ -18,35 +20,46 @@ const BEL = String.fromCharCode(0x07);// introducer falls through to the single-character branch instead, which removes `ESC ]` alone.// That branch's `[@-Z\-_]` class covers 0x40-0x5A and 0x5C-0x5F, so it matches `]` but not `[`;// CSI is listed first to catch `ESC [` before it.-const ANSI_ESCAPE_PATTERN = new RegExp(+const ANSI_ESCAPE_PATTERN = new RE2(`${ESC}(?:\\[[0-?]*[ -/]*[@-~]|\\][^${BEL}${ESC}]*(?:${BEL}|${ESC}\\\\)|[@-Z\\\\-_])`,"g");// Whitespace controls carry word boundaries, so a run collapses to a single space rather than being// deleted, which would run the surrounding words together.-const WHITESPACE_CONTROL_RUN = /[\t\n\v\f\r]+/g;+const WHITESPACE_CONTROL_RUN = new RE2("[\\t\\n\\v\\f\\r\\u2028\\u2029]+", "g");-const TAB = 0x09;-const LINE_FEED = 0x0a;-const CARRIAGE_RETURN = 0x0d;+// The line-break set a multiline field is allowed to contain. U+2028/U+2029 are line and paragraph+// separators: not C0 controls, but line breaks to anything that splits on them, so a single-line+// field has to reject them too.+const LINE_BREAKS = new Set([0x09, 0x0a, 0x0d, 0x2028, 0x2029]);const isControlCharacter = (code: number) => code <= 0x1f || (code >= 0x7f && code <= 0x9f);-// Bidi overrides, embeddings and isolates, LRM/RLM, ZWSP and the BOM. U+200C/U+200D (ZWNJ/ZWJ) are-// deliberately excluded: they are ordinary text, joining emoji sequences and Persian, Arabic and-// Indic script, so removing them corrupts the value rather than neutralizing it.-const isInvisibleCharacter = (code: number) =>- code === 0x200b ||- code === 0x200e ||- code === 0x200f ||- (code >= 0x202a && code <= 0x202e) ||- (code >= 0x2066 && code <= 0x2069) ||- code === 0xfeff;-+// Invisible and bidirectional formatting characters. Two deliberate exclusions: U+200C/U+200D+// (ZWNJ/ZWJ) join emoji sequences and Persian, Arabic and Indic script, and U+FE00-U+FE0F+// (variation selectors) select emoji presentation. Removing either corrupts ordinary text.+const isFormatCharacter = (code: number) =>+ code === 0x061c || // Arabic letter mark+ code === 0x180e || // Mongolian vowel separator+ code === 0x200b || // zero-width space+ code === 0x200e || // left-to-right mark+ code === 0x200f || // right-to-left mark+ (code >= 0x202a && code <= 0x202e) || // bidi embeddings and overrides+ (code >= 0x2060 && code <= 0x2064) || // word joiner and invisible operators+ (code >= 0x2066 && code <= 0x2069) || // bidi isolates+ code === 0x2028 || // line separator+ code === 0x2029 || // paragraph separator+ code === 0xfeff || // byte order mark+ (code >= 0xfff9 && code <= 0xfffb) || // interlinear annotation+ (code >= 0x1d173 && code <= 0x1d17a) || // musical format controls+ (code >= 0xe0000 && code <= 0xe007f); // tags block++// codePointAt, not charCodeAt: the astral ranges above sit beyond U+FFFF, where charCodeAt would+// return a surrogate half and never match.const isUnsafeCharacter = (character: string) => {- const code = character.charCodeAt(0);- return isControlCharacter(code) || isInvisibleCharacter(code);+ const code = character.codePointAt(0) ?? 0;+ return isControlCharacter(code) || isFormatCharacter(code);};// `allowMultiline` is for fields a user types into a textarea, where a line break or tab is ordinary@@ -57,8 +70,8 @@ export const containsLogUnsafeCharacters = (value: string, { allowMultiline = faif (ANSI_ESCAPE_PATTERN.test(value)) return true;return Array.from(value).some((character) => {- const code = character.charCodeAt(0);- if (allowMultiline && (code === LINE_FEED || code === TAB || code === CARRIAGE_RETURN)) return false;+ const code = character.codePointAt(0) ?? 0;+ if (allowMultiline && LINE_BREAKS.has(code)) return false;return isUnsafeCharacter(character);});};@@ -74,12 +87,6 @@ export const sanitizeLogText = <T extends string | null | undefined>(value: T):.join("") as T;};-// Audit metadata is shallow; the cap bounds recursion on arbitrary input. Past it the subtree is-// replaced by a marker rather than dropped, so the truncation is visible in the record itself and an-// array element cannot become a hole that serializes to null.-const MAX_SANITIZE_DEPTH = 12;-export const DEPTH_LIMIT_MARKER = "[truncated: nesting depth limit]";-// Two keys can normalize to the same string, so a collision is suffixed rather than left to// overwrite and silently drop a field.const disambiguate = (key: string, taken: Set<string>) => {@@ -90,22 +97,52 @@ const disambiguate = (key: string, taken: Set<string>) => {return `${key}~${suffix}`;};-// Keys are sanitized alongside values: a flattening exporter renders both.-export const sanitizeLogPayload = <T>(payload: T, depth = 0): T => {+const emptyLike = (node: object) => (Array.isArray(node) ? [] : {}) as Record<string, unknown> | unknown[];++/**+ * Sanitizes every string in a metadata payload, keys included: a flattening exporter renders both.+ *+ * The walk is iterative and has no depth limit, because the structure is part of the record. An+ * event can legitimately nest (`oidcClaimsReceived` on LOGIN_IDENTITY_OIDC_AUTH carries whatever the+ * IdP returned), and truncating it would retype fields that downstream consumers already parse.+ * Input always arrives from JSON.parse in the audit queue, so it is finite, acyclic and holds no+ * shared references.+ */+export const sanitizeLogPayload = <T>(payload: T): T => {if (typeof payload === "string") return sanitizeLogText(payload) as T;if (payload === null || typeof payload !== "object") return payload;- if (depth >= MAX_SANITIZE_DEPTH) return DEPTH_LIMIT_MARKER as T;- if (Array.isArray(payload)) {- return (payload as unknown[]).map((item) => sanitizeLogPayload(item, depth + 1)) as T;+ const root = emptyLike(payload);+ const pending: [source: object, target: Record<string, unknown> | unknown[]][] = [[payload, root]];++ while (pending.length) {+ const [source, target] = pending.pop()!;++ const assign = (key: string | number, value: unknown) => {+ if (typeof value === "string") {+ (target as Record<string | number, unknown>)[key] = sanitizeLogText(value);+ return;+ }+ if (value !== null && typeof value === "object") {+ const child = emptyLike(value);+ (target as Record<string | number, unknown>)[key] = child;+ pending.push([value, child]);+ return;+ }+ (target as Record<string | number, unknown>)[key] = value;+ };++ if (Array.isArray(source)) {+ source.forEach((item, index) => assign(index, item));+ } else {+ const taken = new Set<string>();+ Object.entries(source as Record<string, unknown>).forEach(([key, value]) => {+ const sanitizedKey = disambiguate(sanitizeLogText(key), taken);+ taken.add(sanitizedKey);+ assign(sanitizedKey, value);+ });+ }}- const taken = new Set<string>();- return Object.fromEntries(- Object.entries(payload as Record<string, unknown>).map(([key, value]) => {- const sanitizedKey = disambiguate(sanitizeLogText(key), taken);- taken.add(sanitizedKey);- return [sanitizedKey, sanitizeLogPayload(value, depth + 1)];- })- ) as T;+ return root as T;};diff --git a/backend/src/server/lib/audit-safe-text-schema.test.ts b/backend/src/server/lib/audit-safe-text-schema.test.tsnew file mode 100644index 0000000000..37516ed1e4--- /dev/null+++ b/backend/src/server/lib/audit-safe-text-schema.test.ts@@ -0,0 +1,85 @@+import { readFileSync } from "node:fs";+import path from "node:path";++import { describe, expect, test } from "vitest";+import { z } from "zod";++import { auditSafeText } from "./schemas";++// Guards the composition rather than the sanitizer. The route schemas are the only reason the+// boundary check runs at all, so a refactor that drops the wrapper or flips the multiline flag+// would leave the sanitizer's own suite green.++const NUL = String.fromCharCode(0);+const ESC = String.fromCharCode(0x1b);+const LF = String.fromCharCode(10);+const CR = String.fromCharCode(13);+const TAB = String.fromCharCode(9);++const nameSchema = auditSafeText(z.string().trim());+const reasonSchema = auditSafeText(z.string().trim().max(500), { allowMultiline: true });++describe("auditSafeText composition", () => {+ test("a single-line field rejects line breaks", () => {+ expect(nameSchema.safeParse(`probe${LF}name`).success).toBe(false);+ expect(nameSchema.safeParse(`probe${CR}name`).success).toBe(false);+ expect(nameSchema.safeParse(`probe${TAB}name`).success).toBe(false);+ });++ test("a multiline field accepts LF, CR and tab", () => {+ expect(reasonSchema.safeParse(`line one${LF}line two`).success).toBe(true);+ expect(reasonSchema.safeParse(`line one${CR}${LF}line two`).success).toBe(true);+ expect(reasonSchema.safeParse(`a${TAB}b`).success).toBe(true);+ });++ test("both reject the rest of the unsafe set", () => {+ [nameSchema, reasonSchema].forEach((schema) => {+ expect(schema.safeParse(`a${NUL}b`).success).toBe(false);+ expect(schema.safeParse(`${ESC}[31mred`).success).toBe(false);+ expect(schema.safeParse(`x${String.fromCodePoint(0x202e)}y`).success).toBe(false);+ expect(schema.safeParse(`x${String.fromCodePoint(0x200b)}y`).success).toBe(false);+ expect(schema.safeParse(`x${String.fromCodePoint(0x2060)}y`).success).toBe(false);+ });+ });++ test("both accept ordinary text, including emoji and Arabic script", () => {+ [nameSchema, reasonSchema].forEach((schema) => {+ expect(schema.safeParse("deploy bot 7").success).toBe(true);+ expect(schema.safeParse("deploy \u{1F3F3}️\u{1F308} bot").success).toBe(true);+ expect(schema.safeParse("میشود").success).toBe(true);+ });+ });++ test("the wrapper keeps the constraints of the schema it wraps", () => {+ expect(reasonSchema.safeParse("x".repeat(501)).success).toBe(false);+ expect(reasonSchema.parse(" padded ")).toBe("padded");+ });+});++// The route bodies are registered inside server.route() calls, so there is no exported schema to+// import. Reading the source is what catches the wrapper being dropped from a field.+describe("routes that feed audit metadata keep the wrapper", () => {+ const read = (relative: string) => readFileSync(path.join(__dirname, "../..", relative), "utf8");++ test("identity names are wrapped and stay single-line", () => {+ const source = read("server/routes/v1/identity-router.ts");+ const wrapped = source.match(/name: auditSafeText\(/g) ?? [];++ expect(wrapped).toHaveLength(2); // create and update+ expect(source).not.toMatch(/name: auditSafeText\([^)]*\), \{ allowMultiline: true \}/);+ });++ test.each([+ ["ee/routes/v1/pam-routers/pam-account-router.ts", 1],+ ["ee/routes/v1/pam-routers/pam-session-router.ts", 2],+ ["ee/routes/v1/pam-routers/pam-access-request-router.ts", 1]+ ])("%s wraps its reason fields as multiline", (file, expected) => {+ const source = read(file);+ const reasonFields = source.match(/reason: /g) ?? [];+ const wrapped = source.match(/reason: auditSafeText\(.*allowMultiline: true/g) ?? [];++ expect(wrapped).toHaveLength(expected);+ // Every request-body `reason:` on these routers goes through the wrapper.+ expect(reasonFields.length).toBeGreaterThanOrEqual(wrapped.length);+ });+});