Skip to content

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

summarize comments

Thiago Araujo da Silvaeb56b0953efb
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.ts
index 276a932759..b001c8dbef 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
@@ -548,7 +548,7 @@ describe("audit-log-queue unified consumer", () => {
}
});
- // projectName is only carried on the postgres path, so the clickhouse case opts out of it.
+ // projectName only exists on the postgres path.
const expectClean = (row: Record<string, unknown>, { withProjectName = true } = {}) => {
if (withProjectName) expect(row.projectName).toBe("projx");
expect(row.ipAddress).toBe("1.1.1.1[31m");
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 65446f9eef..93b62f0ad6 100644
--- a/backend/src/ee/services/audit-log/audit-log-queue.ts
+++ b/backend/src/ee/services/audit-log/audit-log-queue.ts
@@ -227,8 +227,7 @@ 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.
+ // `enriched` feeds both the insert and the stream outbox, so cleaning here covers both.
return {
id: entry.id,
actor: entry.actor.type,
diff --git a/backend/src/lib/validator/log-safe-text.test.ts b/backend/src/lib/validator/log-safe-text.test.ts
index 8fa353e74a..304c1dd983 100644
--- a/backend/src/lib/validator/log-safe-text.test.ts
+++ b/backend/src/lib/validator/log-safe-text.test.ts
@@ -87,8 +87,6 @@ describe("sanitizeLogPayload", () => {
});
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 };
@@ -147,7 +145,6 @@ describe("sanitizeLogPayload", () => {
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");
});
diff --git a/backend/src/lib/validator/log-safe-text.ts b/backend/src/lib/validator/log-safe-text.ts
index b31fddb460..08fb16ede0 100644
--- a/backend/src/lib/validator/log-safe-text.ts
+++ b/backend/src/lib/validator/log-safe-text.ts
@@ -1,74 +1,56 @@
import RE2 from "re2";
/**
- * Normalizes free text bound for an audit record: C0/C1 controls, ANSI escapes, bidirectional
- * 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.
+ * Cleans free text headed for audit logs: control chars, ANSI escapes, bidi overrides and invisible
+ * formatting chars. They're all valid JSON but can still mess up terminals, CSV exports and SIEMs.
*
- * Line breaks and tabs are kept. Every audit consumer JSON-encodes the value, which escapes them, and
- * some fields are multiline by design (PAM reasons); the credential-view reason is recorded nowhere
- * but the audit log, so collapsing it would lose what the user typed.
+ * Line breaks and tabs stay. Consumers JSON-encode them anyway, and some fields (PAM reasons) are
+ * multiline on purpose.
*
- * 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.
+ * We reject at the API, where the caller can fix the input, and strip on the way into the log,
+ * where dropping the event would lose the record.
*/
+// Built with fromCharCode because a literal control char is invisible 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.
+// The OSC terminator is required. If it were optional, an unterminated `ESC ]` would match to the end
+// and wipe the rest of the value. The single-char branch matches `]` but not `[`, so CSI goes first.
const ANSI_ESCAPE_PATTERN = new RE2(
`${ESC}(?:\\[[0-?]*[ -/]*[@-~]|\\][^${BEL}${ESC}]*(?:${BEL}|${ESC}\\\\)|[@-Z\\\\-_])`,
"g"
);
-// CRLF and a lone CR become LF: a bare CR returns a terminal's cursor to the start of the line, so the
-// rest of the value overprints what was already shown. U+2028/U+2029 become LF too, because
-// JSON.stringify leaves them unescaped.
+// CRLF, lone CR and U+2028/U+2029 all become LF. A bare CR lets text overwrite the line in a terminal,
+// and JSON.stringify doesn't escape U+2028/U+2029.
const LINE_BREAK_VARIANTS = new RE2("\\r\\n?|[\\u2028\\u2029]", "g");
-// VT and FF still mark a word boundary, so they become a space rather than running words together.
+// VT and FF become a space so words don't run together.
const VERTICAL_WHITESPACE = new RE2("[\\v\\f]", "g");
const KEPT_WHITESPACE = new Set([0x09, 0x0a]);
-// 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.
+// What a multiline field may contain. U+2028/U+2029 split lines too, so single-line fields reject them.
const LINE_BREAKS = new Set([0x09, 0x0a, 0x0d, 0x2028, 0x2029]);
const isControlCharacter = (code: number) => code <= 0x1f || (code >= 0x7f && code <= 0x9f);
-// The whole Unicode format category, rather than a list of its members: an enumeration of invisible
-// code points is a category Unicode keeps extending, and it has already been extended past two
-// rounds of this one.
+// The whole Cf category instead of a hand-picked list, since Unicode keeps adding to it.
const FORMAT_CATEGORY = new RE2("\\p{Cf}", "u");
-// U+200C/U+200D (ZWNJ/ZWJ) are in that category but are ordinary text, joining emoji sequences and
-// Persian, Arabic and Indic script. Variation selectors are marks rather than format characters, so
-// they survive without an exclusion.
+// ZWNJ/ZWJ are Cf but they're real text: emoji sequences and Persian, Arabic and Indic scripts need them.
const TEXT_JOINERS = new Set([0x200c, 0x200d]);
-// What the category misses: U+2028/U+2029 are line and paragraph separators, and the unassigned
-// half of the tags block is ignorable in rendering without being classified.
+// Invisible stuff Cf misses: the line/paragraph separators and the tags block.
const isUncategorizedFormat = (code: number) =>
code === 0x2028 || code === 0x2029 || (code >= 0xe0000 && code <= 0xe007f);
-// A whole-string screen, run before the per-character walk below. The walk crosses into RE2 once per
-// character, which measures ~30x the cost of the walk itself, and audit text is almost always clean,
-// so one call per string answers the common case. The screen over-matches on ZWNJ, ZWJ, LF and tab,
-// which only costs those strings a walk that then keeps them.
+// Cheap whole-string check before the per-char walk, which costs one RE2 call per char (~30x slower).
+// Audit text is almost always clean. It over-matches ZWNJ, ZWJ, LF and tab, so those just get walked.
const UNSAFE_SCREEN = new RE2("[\\x00-\\x1f\\x7f-\\x9f\\x{2028}\\x{2029}]|[\\x{E0000}-\\x{E007F}]|\\p{Cf}", "u");
-// codePointAt, not charCodeAt: the astral ranges sit beyond U+FFFF, where charCodeAt would return a
-// surrogate half and never match.
+// codePointAt, not charCodeAt: past U+FFFF charCodeAt only sees a surrogate half and never matches.
const isUnsafeCharacter = (character: string) => {
const code = character.codePointAt(0) ?? 0;
if (TEXT_JOINERS.has(code)) return false;
@@ -78,8 +60,7 @@ const isUnsafeCharacter = (character: string) => {
export const LOG_UNSAFE_TEXT_MESSAGE = "Value cannot contain control, escape, bidirectional or zero-width characters";
-// `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 normalizes it to LF.
+// `allowMultiline` is for textarea fields. CR is allowed so CRLF input passes, the sink turns it into LF.
export const containsLogUnsafeCharacters = (value: string, { allowMultiline = false } = {}): boolean => {
if (!UNSAFE_SCREEN.test(value)) return false;
@@ -97,7 +78,7 @@ export const sanitizeLogText = <T extends string | null | undefined>(value: T):
if (typeof value !== "string") return value;
if (!UNSAFE_SCREEN.test(value)) return value;
- // Sequences first, so a body leaves with its introducer rather than surviving as visible text.
+ // Whole sequences first, otherwise dropping ESC alone leaves the rest as visible text.
const normalized = value
.replace(ANSI_ESCAPE_PATTERN, "")
.replace(LINE_BREAK_VARIANTS, "\n")
@@ -108,8 +89,7 @@ export const sanitizeLogText = <T extends string | null | undefined>(value: T):
.join("") as T;
};
-// Two keys can normalize to the same string, so a collision is suffixed rather than left to
-// overwrite and silently drop a field.
+// Two keys can clean up to the same string, so suffix the second one instead of losing a field.
const disambiguate = (key: string, taken: Set<string>) => {
if (!taken.has(key)) return key;
@@ -121,13 +101,11 @@ const disambiguate = (key: string, taken: Set<string>) => {
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.
+ * Cleans every string in a metadata payload, keys too, since flattening exporters show 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.
+ * No depth limit on purpose: nesting is legit (`oidcClaimsReceived` holds whatever the IdP sent) and
+ * truncating would change the shape consumers parse. Input always comes from JSON.parse, so it's
+ * finite and acyclic.
*/
export const sanitizeLogPayload = <T>(payload: T): T => {
if (typeof payload === "string") return sanitizeLogText(payload) as T;
@@ -139,8 +117,7 @@ export const sanitizeLogPayload = <T>(payload: T): T => {
while (pending.length) {
const [source, target] = pending.pop()!;
- // defineProperty, not assignment: a `__proto__` key hits the inherited setter and sets the
- // prototype instead of writing a field. Metadata keys come from the IdP on OIDC login.
+ // defineProperty, not assignment: a `__proto__` key (IdP claims can have one) would set the prototype.
const put = (key: string | number, value: unknown) => {
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
};
diff --git a/backend/src/server/lib/audit-safe-text-schema.test.ts b/backend/src/server/lib/audit-safe-text-schema.test.ts
index 138a9b1b7b..c0b3fb7590 100644
--- a/backend/src/server/lib/audit-safe-text-schema.test.ts
+++ b/backend/src/server/lib/audit-safe-text-schema.test.ts
@@ -6,9 +6,8 @@ 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.
+// Tests the wiring, not the sanitizer. Drop the wrapper or flip the multiline flag and the sanitizer
+// suite would still pass.
const NUL = String.fromCharCode(0);
const ESC = String.fromCharCode(0x1b);
@@ -56,14 +55,12 @@ describe("auditSafeText composition", () => {
});
});
-// 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.
+// Route schemas live inside server.route() calls, so there's nothing to import. Reading the source is
+// how we catch a dropped wrapper.
describe("routes that feed audit metadata keep the wrapper", () => {
const read = (relative: string) => readFileSync(path.join(__dirname, "../..", relative), "utf8");
- // Every route that creates an identity: the org and project routers take the same name the legacy
- // router does, and the web app creates project identities through the project router. Renames are
- // checked in the identity services instead, and only when the name changes.
+ // Create routes only. Renames are checked in the identity services, and only when the name changes.
test.each([
"server/routes/v1/identity-router.ts",
"server/routes/v1/org-identity-router.ts",
diff --git a/backend/src/server/lib/schemas.ts b/backend/src/server/lib/schemas.ts
index d95aeb2291..b383cf78cc 100644
--- a/backend/src/server/lib/schemas.ts
+++ b/backend/src/server/lib/schemas.ts
@@ -43,9 +43,8 @@ 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.
+// For free text that lands in audit events (names, reasons). An allowlist would break existing values,
+// so this only blocks non-printing chars. The audit sink strips the same set.
export const auditSafeText = (schema: z.ZodString, { allowMultiline = false } = {}) =>
schema.refine((val) => !containsLogUnsafeCharacters(val, { allowMultiline }), {
message: LOG_UNSAFE_TEXT_MESSAGE