Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(audit-log): normalize free text in audit events

Vlad Ligai0b160097136b
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts
index 36a122b531..7bb7c9ef79 100644
--- a/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts
+++ b/backend/src/ee/routes/v1/pam-routers/pam-access-request-router.ts
@@ -4,6 +4,7 @@ import { ApprovalRequestsSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { PamAccessType } from "@app/ee/services/pam/pam-enums";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { auditSafeText } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import {
@@ -35,7 +36,7 @@ export const registerPamAccessRequestRouter = async (server: FastifyZodProvider)
.object({
accountId: z.string().uuid().optional(),
path: z.string().min(3).optional().describe("Account path in the format 'folderName/accountName'"),
- reason: z.string().max(500).optional(),
+ reason: auditSafeText(z.string().max(500), { allowMultiline: true }).optional(),
duration: z.string().min(1),
accessType: z
.nativeEnum(PamAccessType)
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts
index 7d0a8995c5..9cbf8a3b9a 100644
--- a/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts
+++ b/backend/src/ee/routes/v1/pam-routers/pam-account-router.ts
@@ -20,7 +20,7 @@ import { PasswordRequirementsSchema } from "@app/ee/services/secret-rotation-v2/
import { ApiDocsTags } from "@app/lib/api-docs/constants";
import { BadRequestError } from "@app/lib/errors";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
-import { slugSchema } from "@app/server/lib/schemas";
+import { auditSafeText, slugSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { withRoutePrefix } from "@app/server/lib/with-route-prefix";
import { isUserSessionAuth } from "@app/server/plugins/auth/inject-identity";
@@ -884,10 +884,7 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
tags: [ApiDocsTags.PamAccounts],
params: z.object({ accountId: z.string().uuid().describe("The ID of the account") }),
body: z.object({
- reason: z
- .string()
- .trim()
- .max(500)
+ reason: auditSafeText(z.string().trim().max(500), { allowMultiline: true })
.optional()
.describe("Why the credentials are being viewed. Required when the template requires a reason."),
mfaSessionId: z
diff --git a/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts
index 757d3aa44d..b3bee7d469 100644
--- a/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts
+++ b/backend/src/ee/routes/v1/pam-routers/pam-session-router.ts
@@ -10,6 +10,7 @@ import { PamRecordingStorageBackend } from "@app/ee/services/pam-session-recordi
import { ApiDocsTags } from "@app/lib/api-docs/constants";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { auditSafeText } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { isUserSessionAuth } from "@app/server/plugins/auth/inject-identity";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
@@ -305,7 +306,9 @@ export const registerPamWebAccessRouter = async (server: FastifyZodProvider) =>
tags: [ApiDocsTags.PamSessions],
body: z.object({
path: z.string().trim().min(3).describe("Account path in the format 'folderName/accountName'"),
- reason: z.string().trim().max(1000).optional().describe("Optional reason for the session"),
+ reason: auditSafeText(z.string().trim().max(1000), { allowMultiline: true })
+ .optional()
+ .describe("Optional reason for the session"),
duration: z
.string()
.trim()
@@ -438,7 +441,9 @@ export const registerPamWebAccessRouter = async (server: FastifyZodProvider) =>
accountId: z.string().uuid().describe("The ID of the account")
}),
body: z.object({
- reason: z.string().trim().max(1000).optional().describe("Optional reason for the session"),
+ reason: auditSafeText(z.string().trim().max(1000), { allowMultiline: true })
+ .optional()
+ .describe("Optional reason for the session"),
mfaSessionId: z.string().max(64).optional().describe("MFA session ID from a completed MFA verification"),
selectedHost: z
.string()
diff --git a/backend/src/ee/services/audit-log/audit-log-queue.ts b/backend/src/ee/services/audit-log/audit-log-queue.ts
index bff2c60d18..a6b30892a3 100644
--- a/backend/src/ee/services/audit-log/audit-log-queue.ts
+++ b/backend/src/ee/services/audit-log/audit-log-queue.ts
@@ -14,6 +14,7 @@ import {
auditLogEnqueuedCounter,
auditLogPersistDurationHistogram
} from "@app/lib/telemetry/metrics";
+import { sanitizeLogPayload, sanitizeLogText } from "@app/lib/validator/log-safe-text";
import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -220,14 +221,16 @@ export const auditLogQueueServiceFactory = async ({
}
const createdAt = new Date(entry.createdAt);
+ // `enriched` feeds both the insert and the stream outbox below, so normalizing free text
+ // here covers persistence and forwarding in one place.
return {
id: entry.id,
actor: entry.actor.type,
- actorMetadata: normalizeJsonPayload(entry.actor.metadata),
- ipAddress: normalizeEmptyValue(entry.ipAddress, isClickHouseBatchEnabled),
+ actorMetadata: sanitizeLogPayload(normalizeJsonPayload(entry.actor.metadata)),
+ ipAddress: normalizeEmptyValue(sanitizeLogText(entry.ipAddress), isClickHouseBatchEnabled),
eventType: entry.event.type,
- eventMetadata: normalizeJsonPayload(entry.event.metadata),
- userAgent: normalizeEmptyValue(entry.userAgent, isClickHouseBatchEnabled),
+ eventMetadata: sanitizeLogPayload(normalizeJsonPayload(entry.event.metadata)),
+ userAgent: normalizeEmptyValue(sanitizeLogText(entry.userAgent), isClickHouseBatchEnabled),
userAgentType: normalizeEmptyValue(entry.userAgentType, isClickHouseBatchEnabled),
projectId: normalizeEmptyValue(entry.projectId, isClickHouseBatchEnabled),
orgId: entry.orgId,
@@ -235,7 +238,7 @@ export const auditLogQueueServiceFactory = async ({
createdAt,
updatedAt: createdAt,
// project name is only stored for non-ClickHouse insertion
- ...(!isClickHouseBatchEnabled ? { projectName: entry.projectName } : {})
+ ...(!isClickHouseBatchEnabled ? { projectName: sanitizeLogText(entry.projectName) } : {})
};
};
diff --git a/backend/src/lib/validator/log-safe-text.test.ts b/backend/src/lib/validator/log-safe-text.test.ts
new file mode 100644
index 0000000000..da17742d82
--- /dev/null
+++ b/backend/src/lib/validator/log-safe-text.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, test } from "vitest";
+
+import { containsLogUnsafeCharacters, DEPTH_LIMIT_MARKER, sanitizeLogPayload, sanitizeLogText } from "./log-safe-text";
+
+const NUL = String.fromCharCode(0);
+const ESC = String.fromCharCode(27);
+const RLO = String.fromCharCode(0x202e);
+const ZWSP = String.fromCharCode(0x200b);
+
+describe("sanitizeLogText", () => {
+ test.each([
+ ["line feed", `deploy${String.fromCharCode(10)}worker`, "deploy worker"],
+ ["carriage return", `a${String.fromCharCode(13)}b`, "a b"],
+ ["null byte", `svc${NUL}account`, "svcaccount"],
+ ["ansi colour", `${ESC}[31mroot${ESC}[0m`, "root"],
+ ["ansi osc", `${ESC}]0;title${String.fromCharCode(7)}x`, "x"],
+ ["bidi override", `report${RLO}txt.exe`, "reporttxt.exe"],
+ ["zero width", `ad${ZWSP}min`, "admin"],
+ ["c1 control", `a${String.fromCharCode(155)}b`, "ab"]
+ ])("strips %s", (_label, input, expected) => {
+ expect(sanitizeLogText(input)).toBe(expected);
+ });
+
+ test("leaves ordinary text untouched", () => {
+ const value = "build-agent v1.2 (linux), ok";
+ expect(sanitizeLogText(value)).toBe(value);
+ });
+
+ test("passes through null and undefined", () => {
+ expect(sanitizeLogText(null)).toBeNull();
+ expect(sanitizeLogText(undefined)).toBeUndefined();
+ });
+});
+
+describe("containsLogUnsafeCharacters", () => {
+ test.each([`a${NUL}b`, `${ESC}[31m`, `x${RLO}y`, `x${ZWSP}y`, `a${String.fromCharCode(10)}b`])(
+ "flags %j",
+ (value) => {
+ expect(containsLogUnsafeCharacters(value)).toBe(true);
+ }
+ );
+
+ test("does not flag ordinary text", () => {
+ expect(containsLogUnsafeCharacters("prod-db read, ticket INF-42")).toBe(false);
+ });
+
+ test("allows newline, tab and CR only when the caller opts in", () => {
+ const multiline = `line one${String.fromCharCode(10)}line two${String.fromCharCode(9)}tabbed`;
+ const crlf = `one${String.fromCharCode(13)}${String.fromCharCode(10)}two`;
+
+ expect(containsLogUnsafeCharacters(multiline)).toBe(true);
+ expect(containsLogUnsafeCharacters(multiline, { allowMultiline: true })).toBe(false);
+ expect(containsLogUnsafeCharacters(crlf, { allowMultiline: true })).toBe(false);
+ });
+
+ test("still flags the rest of the set when multiline is allowed", () => {
+ expect(containsLogUnsafeCharacters(`a${NUL}b`, { allowMultiline: true })).toBe(true);
+ expect(containsLogUnsafeCharacters(`${ESC}[31m`, { allowMultiline: true })).toBe(true);
+ expect(containsLogUnsafeCharacters(`x${RLO}y`, { allowMultiline: true })).toBe(true);
+ expect(containsLogUnsafeCharacters(`x${ZWSP}y`, { allowMultiline: true })).toBe(true);
+ });
+
+ // A stale lastIndex on the global pattern would make repeat calls alternate.
+ test("is stable across repeated calls", () => {
+ const value = `a${NUL}b`;
+ expect(containsLogUnsafeCharacters(value)).toBe(true);
+ expect(containsLogUnsafeCharacters(value)).toBe(true);
+ });
+});
+
+describe("sanitizeLogPayload", () => {
+ test("sanitizes nested values, keys and arrays", () => {
+ expect(
+ sanitizeLogPayload({
+ [`na${ZWSP}me`]: `svc${NUL}acct`,
+ nested: { reason: `${ESC}[31mapproved`, count: 3, flag: true, missing: null },
+ tags: [`a${RLO}b`, "clean"]
+ })
+ ).toEqual({
+ name: "svcacct",
+ nested: { reason: "approved", count: 3, flag: true, missing: null },
+ tags: ["ab", "clean"]
+ });
+ });
+
+ test("returns non-object payloads unchanged", () => {
+ expect(sanitizeLogPayload(42)).toBe(42);
+ 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` };
+ 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);
+ });
+
+ test("keeps both fields when two keys normalize to the same string", () => {
+ const sanitized = sanitizeLogPayload({ [`a${ZWSP}b`]: 1, ab: 2 }) as Record<string, unknown>;
+
+ expect(Object.keys(sanitized)).toHaveLength(2);
+ expect(Object.values(sanitized).sort()).toEqual([1, 2]);
+ });
+
+ test("whitespace controls collapse to a single space, preserving word boundaries", () => {
+ expect(sanitizeLogText(`approved by${String.fromCharCode(10)}ops`)).toBe("approved by ops");
+ expect(sanitizeLogText(`one${String.fromCharCode(13)}${String.fromCharCode(10)}two`)).toBe("one two");
+ expect(sanitizeLogText(`a${String.fromCharCode(9)}b`)).toBe("a b");
+ });
+
+ test("an unterminated OSC introducer does not swallow the rest of the value", () => {
+ expect(sanitizeLogText(`ok ${ESC}] ticket INF-42 rest`)).toBe("ok ticket INF-42 rest");
+ // A properly terminated sequence still goes entirely.
+ expect(sanitizeLogText(`${ESC}]0;title${String.fromCharCode(7)}kept`)).toBe("kept");
+ });
+
+ test("leaves ZWNJ and ZWJ alone, so emoji and Indic/Arabic script survive", () => {
+ const rainbowFlag = "\u{1F3F3}\uFE0F\u200D\u{1F308}";
+ const persian = "\u0645\u06CC\u200C\u0634\u0648\u062F";
+
+ expect(sanitizeLogText(rainbowFlag)).toBe(rainbowFlag);
+ expect(sanitizeLogText(persian)).toBe(persian);
+ expect(containsLogUnsafeCharacters(rainbowFlag)).toBe(false);
+ expect(containsLogUnsafeCharacters(persian)).toBe(false);
+ });
+
+ 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.ts
new file mode 100644
index 0000000000..6fddbc5972
--- /dev/null
+++ b/backend/src/lib/validator/log-safe-text.ts
@@ -0,0 +1,111 @@
+/**
+ * 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.
+ *
+ * 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.
+ *
+ * Code points are named rather than escaped: a literal control character in the source is invisible
+ * to a reader and trips no-irregular-whitespace.
+ */
+
+const ESC = String.fromCharCode(0x1b);
+const BEL = String.fromCharCode(0x07);
+
+// ESC-introduced sequences. The OSC terminator is required: with it optional, an unterminated
+// `ESC ]` matches to end of string and silently deletes the rest of the value. An unterminated
+// 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(
+ `${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 TAB = 0x09;
+const LINE_FEED = 0x0a;
+const CARRIAGE_RETURN = 0x0d;
+
+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;
+
+const isUnsafeCharacter = (character: string) => {
+ const code = character.charCodeAt(0);
+ return isControlCharacter(code) || isInvisibleCharacter(code);
+};
+
+// `allowMultiline` is for fields a user types into a textarea, where a line break or tab is ordinary
+// input. CR is included so CRLF-separated content is not rejected. The sink-side strip still
+// collapses them, so the stored record stays single-line.
+export const containsLogUnsafeCharacters = (value: string, { allowMultiline = false } = {}): boolean => {
+ ANSI_ESCAPE_PATTERN.lastIndex = 0;
+ if (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;
+ return isUnsafeCharacter(character);
+ });
+};
+
+export const sanitizeLogText = <T extends string | null | undefined>(value: T): T => {
+ if (typeof value !== "string") return value;
+
+ // Sequences first, so a body leaves with its introducer rather than surviving as visible text.
+ const collapsed = value.replace(ANSI_ESCAPE_PATTERN, "").replace(WHITESPACE_CONTROL_RUN, " ");
+
+ return Array.from(collapsed)
+ .filter((character) => !isUnsafeCharacter(character))
+ .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>) => {
+ if (!taken.has(key)) return key;
+
+ let suffix = 2;
+ while (taken.has(`${key}~${suffix}`)) suffix += 1;
+ return `${key}~${suffix}`;
+};
+
+// Keys are sanitized alongside values: a flattening exporter renders both.
+export const sanitizeLogPayload = <T>(payload: T, depth = 0): 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 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;
+};
diff --git a/backend/src/server/lib/schemas.ts b/backend/src/server/lib/schemas.ts
index cbe7c7207e..e8c20ff9be 100644
--- a/backend/src/server/lib/schemas.ts
+++ b/backend/src/server/lib/schemas.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
import { TemporaryPermissionMode } from "@app/db/schemas";
import { ms } from "@app/lib/ms";
+import { containsLogUnsafeCharacters } from "@app/lib/validator/log-safe-text";
import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";
interface SlugSchemaInputs {
@@ -42,6 +43,14 @@ export const GenericResourceNameSchema = z
"Name can only contain alphanumeric characters, dashes, underscores, and spaces"
);
+// For free-text fields copied into audit events (display names, access reasons). A charset
+// allowlist would reject existing values, so this bounds only the non-printing set; the audit
+// ingest path normalizes the same characters.
+export const auditSafeText = (schema: z.ZodString, { allowMultiline = false } = {}) =>
+ schema.refine((val) => !containsLogUnsafeCharacters(val, { allowMultiline }), {
+ message: "Value cannot contain control, escape, bidirectional or zero-width characters"
+ });
+
export const BaseSecretNameSchema = z.string().trim().min(1);
export const SecretNameSchema = BaseSecretNameSchema.refine(
diff --git a/backend/src/server/routes/v1/identity-router.ts b/backend/src/server/routes/v1/identity-router.ts
index f846a4d249..6796e69204 100644
--- a/backend/src/server/routes/v1/identity-router.ts
+++ b/backend/src/server/routes/v1/identity-router.ts
@@ -8,6 +8,7 @@ import { buildSearchZodSchema, SearchResourceOperators } from "@app/lib/search-r
import { OrderByDirection } from "@app/lib/types";
import { CharacterType, zodValidateCharacters } from "@app/lib/validator/validate-string";
import { identityCreationLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { auditSafeText } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
@@ -46,7 +47,7 @@ export const registerIdentityRouter = async (server: FastifyZodProvider) => {
}
],
body: z.object({
- name: z.string().trim().describe(IDENTITIES.CREATE.name),
+ name: auditSafeText(z.string().trim()).describe(IDENTITIES.CREATE.name),
organizationId: z.string().trim().describe(IDENTITIES.CREATE.organizationId),
role: z.string().trim().min(1).default(OrgMembershipRole.NoAccess).describe(IDENTITIES.CREATE.role),
hasDeleteProtection: z.boolean().default(false).describe(IDENTITIES.CREATE.hasDeleteProtection),
@@ -125,7 +126,7 @@ export const registerIdentityRouter = async (server: FastifyZodProvider) => {
identityId: z.string().describe(IDENTITIES.UPDATE.identityId)
}),
body: z.object({
- name: z.string().trim().optional().describe(IDENTITIES.UPDATE.name),
+ name: auditSafeText(z.string().trim()).optional().describe(IDENTITIES.UPDATE.name),
role: z.string().trim().min(1).optional().describe(IDENTITIES.UPDATE.role),
hasDeleteProtection: z.boolean().optional().describe(IDENTITIES.UPDATE.hasDeleteProtection),
metadata: z