Skip to content

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

validate a couple of open text fields

Thiago Araujo da Silva47f47d742f85
diff --git a/backend/AGENTS.md b/backend/AGENTS.md
index a78579136c..bbc2c65983 100644
--- a/backend/AGENTS.md
+++ b/backend/AGENTS.md
@@ -1234,6 +1234,40 @@ timezone, so pin day grouping and bound parameters to `'UTC'` or they follow the
the table is a `ReplacingMergeTree`: a retried batch inserts the same `id` twice and the copy goes away
only at some later merge, so read with `FINAL` when an exact count matters.
+### Free Text in Audit Events
+
+A name, reason, comment or justification can carry ANSI escapes, bidi overrides or zero-width
+characters. They are valid JSON but rewrite a terminal line, reorder text in a SIEM, or make two values
+look identical. Two layers handle them, both built on `src/lib/validator/log-safe-text.ts`:
+
+- **The route rejects them.** Wrap any free-text field that reaches an audit event in `auditSafeText`
+ (`src/server/lib/schemas.ts`), so the caller gets a 422 naming the problem and can fix the input:
+
+ ```ts
+ name: auditSafeText(z.string().trim().min(1).max(255)),
+ reason: auditSafeText(z.string().trim().max(500), { allowMultiline: true }).optional(),
+ ```
+
+- **The sink strips them.** `audit-log-queue.ts` runs actor and event metadata through
+ `sanitizeLogPayload` and `ipAddress`, `userAgent` and `projectName` through `sanitizeLogText`. They
+ strip control, ANSI, bidi and zero-width characters, turn CR and U+2028/U+2029 into LF, drop lone
+ surrogates (Postgres jsonb rejects them, failing the whole batch), and suffix metadata keys that
+ collide after cleaning (`email~2`) instead of dropping one. This covers what the API cannot reject
+ (IdP claims, user agents, legacy rows), so do not strip values yourself before logging.
+
+Rules for the route check:
+
+- **`allowMultiline: true` for textarea fields** (reasons, comments, justifications). It keeps tab, LF
+ and CR; single-line fields reject them.
+- **Keep the bound inside the wrapper.** `auditSafeText` takes a `ZodString`, so `.max()`, `.trim()` and
+ `.min()` go on the inner schema and `.optional()`, `.nullable()` and `.describe()` go outside.
+- **Only validate a value the caller is setting.** A schema check on an editable field blocks every edit
+ of a row that already holds a legacy value, because clients resend the whole body. For updates, check
+ in the service with `containsLogUnsafeCharacters` and `LOG_UNSAFE_TEXT_MESSAGE`, and only when the
+ value differs from the stored one, as `identity-service.ts` and `project-template-service.ts` do.
+ Write-once fields (approval comments, justifications, break-glass reasons) can use the schema directly.
+- **Never put it on a response schema.** Stored rows predate the check and would fail serialization.
+
### Audit Log Event Classes and Settings
Every `EventType` belongs to exactly one class in
diff --git a/backend/src/ee/routes/v1/secret-approval-request-router.ts b/backend/src/ee/routes/v1/secret-approval-request-router.ts
index 97b4cbbfb0..39919a820d 100644
--- a/backend/src/ee/routes/v1/secret-approval-request-router.ts
+++ b/backend/src/ee/routes/v1/secret-approval-request-router.ts
@@ -9,6 +9,7 @@ import {
} from "@app/ee/services/secret-approval-request/secret-approval-request-types";
import { OrderByDirection } from "@app/lib/types";
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 { SanitizedTagSchema, SanitizedUserSchema, secretRawSchema } from "@app/server/routes/sanitizedSchemas";
@@ -236,7 +237,7 @@ export const registerSecretApprovalRequestRouter = async (server: FastifyZodProv
}),
body: z.object({
status: z.enum([ApprovalStatus.APPROVED, ApprovalStatus.REJECTED]),
- comment: z.string().optional()
+ comment: auditSafeText(z.string(), { allowMultiline: true }).optional()
}),
response: {
200: z.object({
diff --git a/backend/src/ee/services/project-template/project-template-service.test.ts b/backend/src/ee/services/project-template/project-template-service.test.ts
new file mode 100644
index 0000000000..5a447a111d
--- /dev/null
+++ b/backend/src/ee/services/project-template/project-template-service.test.ts
@@ -0,0 +1,91 @@
+import { createMongoAbility } from "@casl/ability";
+import { describe, expect, test, vi } from "vitest";
+
+import { ProjectType } from "@app/db/schemas";
+import { ActorType } from "@app/services/auth/auth-type";
+
+import { projectTemplateServiceFactory } from "./project-template-service";
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({})
+}));
+
+const ORG_ID = "org-1";
+const TEMPLATE_ID = "template-1";
+const LEGACY_NAME = "legacy​bot";
+
+// Every allowed request ends at the transaction, so reaching it proves validation passed.
+const REACHED_TRANSACTION = new Error("reached transaction");
+
+const actor = {
+ type: ActorType.USER,
+ id: "actor-1",
+ orgId: ORG_ID,
+ authMethod: null
+} as unknown as Parameters<ReturnType<typeof projectTemplateServiceFactory>["createProjectTemplate"]>[1];
+
+const createService = () =>
+ projectTemplateServiceFactory({
+ licenseService: {
+ getPlan: vi.fn().mockResolvedValue({ projectTemplates: true, environmentLimit: null })
+ },
+ permissionService: {
+ getOrgPermission: vi.fn().mockResolvedValue({
+ permission: createMongoAbility([{ action: ["create", "edit"], subject: "project-templates" }])
+ })
+ },
+ projectTemplateDAL: {
+ findOne: vi.fn().mockResolvedValue(undefined),
+ findById: vi.fn().mockResolvedValue({
+ id: TEMPLATE_ID,
+ orgId: ORG_ID,
+ name: "template",
+ type: ProjectType.SecretManager,
+ roles: [],
+ environments: [],
+ projectManagedIdentities: [{ name: LEGACY_NAME, roles: [] }]
+ }),
+ transaction: vi.fn().mockRejectedValue(REACHED_TRANSACTION)
+ }
+ } as unknown as Parameters<typeof projectTemplateServiceFactory>[0]);
+
+const create = (name: string) =>
+ createService().createProjectTemplate(
+ {
+ name: "template",
+ type: ProjectType.SecretManager,
+ roles: [],
+ environments: [],
+ projectManagedIdentities: [{ name, roles: [] }]
+ } as unknown as Parameters<ReturnType<typeof projectTemplateServiceFactory>["createProjectTemplate"]>[0],
+ actor
+ );
+
+const update = (names: string[]) =>
+ createService().updateProjectTemplateById(
+ TEMPLATE_ID,
+ { projectManagedIdentities: names.map((name) => ({ name, roles: [] })) },
+ actor
+ );
+
+describe("project-managed identity names", () => {
+ test("create rejects a name with an invisible character", async () => {
+ await expect(create("bad​bot")).rejects.toThrow(/zero-width/);
+ });
+
+ test("create rejects a name longer than the identity column", async () => {
+ await expect(create("a".repeat(256))).rejects.toThrow(/too long/);
+ });
+
+ test("create accepts a normal name", async () => {
+ await expect(create("deploy-bot")).rejects.toBe(REACHED_TRANSACTION);
+ });
+
+ test("update keeps a legacy name already on the template", async () => {
+ await expect(update([LEGACY_NAME, "deploy-bot"])).rejects.toBe(REACHED_TRANSACTION);
+ });
+
+ test("update rejects a new name with an invisible character", async () => {
+ await expect(update([LEGACY_NAME, "new‮bot"])).rejects.toThrow(/bidirectional/);
+ });
+});
diff --git a/backend/src/ee/services/project-template/project-template-service.ts b/backend/src/ee/services/project-template/project-template-service.ts
index 51cedf691d..c54ced85d1 100644
--- a/backend/src/ee/services/project-template/project-template-service.ts
+++ b/backend/src/ee/services/project-template/project-template-service.ts
@@ -19,6 +19,7 @@ import {
} from "@app/ee/services/project-template/project-template-types";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { validateHandlebarTemplate } from "@app/lib/template/validate-handlebars";
+import { containsLogUnsafeCharacters, LOG_UNSAFE_TEXT_MESSAGE } from "@app/lib/validator/log-safe-text";
import { unpackPermissions } from "@app/server/routes/sanitizedSchema/permission";
import { TIdentityDALFactory } from "@app/services/identity/identity-dal";
import { TOrgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";
@@ -42,6 +43,22 @@ type TProjectTemplatesServiceFactoryDep = {
identityDAL: Pick<TIdentityDALFactory, "find">;
};
+const $validateProjectManagedIdentityNames = (
+ projectManagedIdentities: TProjectTemplateProjectManagedIdentity[],
+ existingNames: string[] = []
+) => {
+ const existing = new Set(existingNames);
+ projectManagedIdentities.forEach(({ name }) => {
+ if (existing.has(name)) return;
+ if (name.length > 255) {
+ throw new BadRequestError({ message: `Project-managed identity name "${name.slice(0, 32)}..." is too long` });
+ }
+ if (containsLogUnsafeCharacters(name)) {
+ throw new BadRequestError({ message: `Project-managed identity name: ${LOG_UNSAFE_TEXT_MESSAGE}` });
+ }
+ });
+};
+
const $unpackProjectTemplate = (
{ roles, environments, projectManagedIdentities, ...rest }: TProjectTemplates,
users: TProjectTemplateUser[],
@@ -416,6 +433,7 @@ export const projectTemplateServiceFactory = ({
message: "Project-managed identity names must be unique within the template"
});
}
+ $validateProjectManagedIdentityNames(projectManagedIdentities);
}
const projectTemplateEnvironments =
@@ -716,6 +734,12 @@ export const projectTemplateServiceFactory = ({
message: "Project-managed identity names must be unique within the template"
});
}
+ $validateProjectManagedIdentityNames(
+ projectManagedIdentities,
+ ((projectTemplate.projectManagedIdentities as TProjectTemplateProjectManagedIdentity[]) || []).map(
+ (i) => i.name
+ )
+ );
}
if (params.name && projectTemplate.name !== params.name) {
diff --git a/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts b/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts
index 27d9988d0e..c526c861de 100644
--- a/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts
+++ b/backend/src/server/routes/v1/approval-policy-routers/approval-policy-endpoints.ts
@@ -5,6 +5,7 @@ import { APPROVAL_POLICY_AUTO_APPROVAL } from "@app/lib/api-docs";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
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";
@@ -629,7 +630,7 @@ export const registerApprovalPolicyEndpoints = ({
requestId: z.string().uuid()
}),
body: z.object({
- comment: z.string().optional()
+ comment: auditSafeText(z.string(), { allowMultiline: true }).optional()
}),
response: {
200: z.object({
@@ -693,7 +694,7 @@ export const registerApprovalPolicyEndpoints = ({
requestId: z.string().uuid()
}),
body: z.object({
- bypassReason: z.string().min(10).max(500)
+ bypassReason: auditSafeText(z.string().min(10).max(500), { allowMultiline: true })
}),
response: {
200: z.object({
@@ -758,7 +759,7 @@ export const registerApprovalPolicyEndpoints = ({
requestId: z.string().uuid()
}),
body: z.object({
- comment: z.string().optional()
+ comment: auditSafeText(z.string(), { allowMultiline: true }).optional()
}),
response: {
200: z.object({
diff --git a/backend/src/server/routes/v1/signer-routers/requests-router.ts b/backend/src/server/routes/v1/signer-routers/requests-router.ts
index baeee56acf..345a531bf7 100644
--- a/backend/src/server/routes/v1/signer-routers/requests-router.ts
+++ b/backend/src/server/routes/v1/signer-routers/requests-router.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags } from "@app/lib/api-docs";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { auditSafeText } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import {
CODE_SIGNING_SCOPE_API_DESCRIPTION,
@@ -69,7 +70,7 @@ export const registerSignerRequestsRouter = async (server: FastifyZodProvider) =
description: "Open a request to sign with this signer (operator self-serve)",
params: SignerIdParamsSchema,
body: z.object({
- justification: z.string().trim().min(1).max(2048),
+ justification: auditSafeText(z.string().trim().min(1).max(2048), { allowMultiline: true }),
requestedSignings: z.number().int().min(1).optional(),
requestedWindowDuration: SigningWindowDurationSchema.optional().describe(
"How long the approval stays usable once it is granted, for example '4h'. The window starts when the request is approved."
@@ -117,7 +118,7 @@ export const registerSignerRequestsRouter = async (server: FastifyZodProvider) =
body: z.object({
granteeUserId: z.string().uuid().optional(),
granteeIdentityId: z.string().uuid().optional(),
- justification: z.string().trim().min(1).max(2048),
+ justification: auditSafeText(z.string().trim().min(1).max(2048), { allowMultiline: true }),
requestedSignings: z.number().int().min(1).optional(),
requestedWindowDuration: SigningWindowDurationSchema.optional().describe(
"How long the approval stays usable once it is granted, for example '4h'. The window starts when the request is approved."
diff --git a/backend/src/services/approval-policy/approval-policy-schemas.ts b/backend/src/services/approval-policy/approval-policy-schemas.ts
index d6d025e791..0a068dac3f 100644
--- a/backend/src/services/approval-policy/approval-policy-schemas.ts
+++ b/backend/src/services/approval-policy/approval-policy-schemas.ts
@@ -8,6 +8,7 @@ import {
ApprovalRequestStepsSchema
} from "@app/db/schemas";
import { ms } from "@app/lib/ms";
+import { auditSafeText } from "@app/server/lib/schemas";
import { ApprovalPolicyScope, ApproverType, EnforcementLevel } from "./approval-policy-enums";
import {
@@ -104,7 +105,7 @@ export const BaseApprovalRequestSchema = ApprovalRequestsSchema.omit({ autoAppro
export const BaseCreateApprovalRequestSchema = z.object({
scope: z.nativeEnum(ApprovalPolicyScope),
scopeId: z.string().uuid(),
- justification: z.string().max(256).nullable().optional(),
+ justification: auditSafeText(z.string().max(256), { allowMultiline: true }).nullable().optional(),
requestDuration: z
.string()
.refine(