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
feat(validation): enhance secret validation during folder moves and add error handling for duplicates
Dimitris Staratzisce77d1f62887
diff --git a/backend/src/services/secret-folder/secret-folder-service.ts b/backend/src/services/secret-folder/secret-folder-service.tsindex c346a6cf1f..36f5f6ef0f 100644--- a/backend/src/services/secret-folder/secret-folder-service.ts+++ b/backend/src/services/secret-folder/secret-folder-service.ts@@ -115,7 +115,7 @@ type TSecretFolderServiceFactoryDep = {secretRotationV2DAL: Pick<TSecretRotationV2DALFactory, "existsByFolderIds">;honeyTokenDAL: Pick<THoneyTokenDALFactory, "find">;secretImportDAL: Pick<TSecretImportDALFactory, "findImportByFolderIds">;- secretV2BridgeService: Pick<TSecretV2BridgeServiceFactory, "dispatchSecretMoveSideEffects">;+ secretV2BridgeService: Pick<TSecretV2BridgeServiceFactory, "dispatchSecretMoveSideEffects" | "$validateSecrets">;reminderDAL: Pick<TReminderDALFactory, "findSecretReminders" | "delete">;reminderService: Pick<TReminderServiceFactory, "batchCreateReminders">;keyStore: Pick<TKeyStoreFactory, "acquireLock">;@@ -2003,7 +2003,8 @@ export const secretFolderServiceFactory = ({secretApprovalRequestSecretDAL,secretQueueService,reminderDAL,- reminderService+ reminderService,+ validateSecrets: secretV2BridgeService.$validateSecrets}));}diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.tsindex 8083c54ba7..a78874f798 100644--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts@@ -1629,7 +1629,8 @@ export const fnSecretMove = async (dto: TFnSecretMove): Promise<TFnSecretMoveRessecretApprovalRequestSecretDAL,secretQueueService,reminderDAL,- reminderService+ reminderService,+ validateSecrets} = dto;const sourceFolder = await folderDAL.findBySecretPath(projectId, sourceEnvironment, sourceSecretPath, tx);@@ -1812,6 +1813,27 @@ export const fnSecretMove = async (dto: TFnSecretMove): Promise<TFnSecretMoveRes}}+ // a move writes these secrets at the destination, directly or through a change request, so they are held to+ // the destination's validation rules. the source copies still exist in this transaction, so they are left out+ // of the duplicate lookup rather than reported as duplicates of the secrets being moved.+ await validateSecrets(+ {+ projectId,+ environment: destinationEnvironment,+ envId: destinationFolder.envId,+ secretPath: destinationFolder.path,+ secrets: secretsToApplyAtDestination.map((secret) => ({+ key: secret.key,+ // an empty value is stored without ciphertext, but the moved secret is still held to the rules as empty+ value: secret.value ?? "",+ secretId: destinationSecretsGroupedByKey[secret.key]?.[0]?.id+ })),+ excludedSecretIds: secretsToApplyAtDestination.map((secret) => secret.id)+ },+ permission,+ tx+ );+const destinationFolderPolicy = await secretApprovalPolicyService.getSecretApprovalPolicy(projectId,destinationFolder.environment.slug,diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.tsindex 4c7436ced9..a8da0abda9 100644--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts@@ -3271,7 +3271,8 @@ export const secretV2BridgeServiceFactory = ({secretApprovalRequestSecretDAL,secretQueueService,reminderDAL,- reminderService+ reminderService,+ validateSecrets: $validateSecrets}));@@ -4047,6 +4048,7 @@ export const secretV2BridgeServiceFactory = ({getSecretVersionsByIds,findSecretIdsByFolderIdAndKeys,$validateSecretReferences,+ $validateSecrets,redactSecretVersionValue};};diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.tsindex 237817ea44..d8daccc921 100644--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts@@ -26,6 +26,7 @@ import { TReminderDALFactory } from "../reminder/reminder-dal";import { TReminderServiceFactory } from "../reminder/reminder-types";import { TResourceMetadataDALFactory } from "../resource-metadata/resource-metadata-dal";import { ResourceMetadataWithEncryptionDTO } from "../resource-metadata/resource-metadata-schema";+import { TValidateSecretsDTO } from "../secret-validation-rule/secret-validation-rule-types";import { TSecretValueBlindIndexes } from "./secret-blind-index-fns";import { TSecretV2BridgeDALFactory } from "./secret-v2-bridge-dal";import { TSecretVersionV2DALFactory } from "./secret-version-dal";@@ -315,6 +316,12 @@ export type TFnSecretMove = {secretQueueService: Pick<TSecretQueueFactory, "syncSecrets">;reminderDAL: Pick<TReminderDALFactory, "findSecretReminders" | "delete">;reminderService: Pick<TReminderServiceFactory, "batchCreateReminders">;+ // the secret service's rule check, which also words the failure for what the actor may read+ validateSecrets: (+ dto: TValidateSecretsDTO,+ permission: MongoAbility<ProjectPermissionSet>,+ tx?: Knex+ ) => Promise<void>;};export type TFnSecretMoveResult = {diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-constants.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-constants.tsindex 60a1587cad..5341ff823a 100644--- a/backend/src/services/secret-validation-rule/secret-validation-rule-constants.ts+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-constants.ts@@ -6,3 +6,6 @@ export const MAX_GENERATED_CONSTRAINT_LENGTH = 2048;export const MAX_CONSTRAINT_PATTERN_LENGTH = 4096;export const MAX_CONSTRAINT_AFFIX_LENGTH = 1024;++// a bulk write or a folder move can fail on every secret it carries, so the error describes only the first few+export const MAX_DESCRIBED_FAILING_SECRETS = 5;diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-errors.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-errors.tsindex 007c3c76e8..d24d20c78f 100644--- a/backend/src/services/secret-validation-rule/secret-validation-rule-errors.ts+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-errors.ts@@ -1,5 +1,6 @@import { BadRequestError } from "@app/lib/errors";+import { MAX_DESCRIBED_FAILING_SECRETS } from "./secret-validation-rule-constants";import { TConstraintViolation } from "./secret-validation-rule-constraint-fns";export type TCanDescribeLocation = (environment: string, secretPath: string) => boolean;@@ -27,7 +28,18 @@ export const describeSecretValidationFailures = (failures: TSecretValidationFailure[],canDescribeLocation?: TCanDescribeLocation) => {- const described = failures.map((failure) => describeFailure(failure, canDescribeLocation));+ // capped by secret rather than by failure, so every failure of a secret that is listed stays visible+ const failingKeys = [...new Set(failures.map((failure) => failure.secretKey))];+ const describedKeys = new Set(failingKeys.slice(0, MAX_DESCRIBED_FAILING_SECRETS));+ const described = failures+ .filter((failure) => describedKeys.has(failure.secretKey))+ .map((failure) => describeFailure(failure, canDescribeLocation));++ const remaining = failingKeys.length - describedKeys.size;+ if (remaining > 0) {+ described.push(`...and ${remaining} more ${remaining === 1 ? "secret" : "secrets"} failed validation`);+ }+return `Secret validation failed:\n${described.join("\n\n")}`;};diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-service.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-service.tsindex be9d65b88c..6f56afcfcf 100644--- a/backend/src/services/secret-validation-rule/secret-validation-rule-service.ts+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-service.ts@@ -401,7 +401,8 @@ export const secretValidationRuleServiceFactory = ({* every secret in the project back out.** The index is built over the value as stored, so a value carrying a `${...}` reference is skipped:- * its stored form would never line up with the resolved one anyway.+ * its stored form would never line up with the resolved one anyway. An empty value is skipped too:+ * it is stored without an index, so empty secrets never count as duplicates of one another.*/const $findDuplicatesInScope = async ({@@ -409,9 +410,10 @@ export const secretValidationRuleServiceFactory = ({environment,secretPath,secrets,+ excludedSecretIds: otherExcludedSecretIds = [],scope,generateSecretBlindIndex- }: Pick<TValidateSecretsDTO, "projectId" | "environment" | "secretPath" | "secrets"> & {+ }: Pick<TValidateSecretsDTO, "projectId" | "environment" | "secretPath" | "secrets" | "excludedSecretIds"> & {scope: { envId?: string | null; secretPath: string };generateSecretBlindIndex: (value: Buffer) => Promise<string>;},@@ -419,7 +421,7 @@ export const secretValidationRuleServiceFactory = ({): Promise<Record<string, TDuplicateSecret>> => {const candidates = secrets.filter((secret): secret is typeof secret & { value: string } =>- secret.value !== undefined && !containsSecretReference(secret.value)+ Boolean(secret.value && !containsSecretReference(secret.value)));if (!candidates.length) return {};@@ -437,7 +439,10 @@ export const secretValidationRuleServiceFactory = ({else seenInBatch.set(blindIndexes[idx], { key: secret.key, environment, secretPath });});- const excludedSecretIds = candidates.map((secret) => secret.secretId).filter(Boolean) as string[];+ const excludedSecretIds = [+ ...(candidates.map((secret) => secret.secretId).filter(Boolean) as string[]),+ ...otherExcludedSecretIds+ ];const existing = await secretDAL.findExistingSecretsWithMatchingValues(projectId,[...new Set(blindIndexes)],@@ -477,7 +482,7 @@ export const secretValidationRuleServiceFactory = ({};const validateSecrets = async (- { projectId, environment, envId, secretPath, secrets }: TValidateSecretsDTO,+ { projectId, environment, envId, secretPath, secrets, excludedSecretIds }: TValidateSecretsDTO,tx?: Knex) => {if (!secrets.length) return;@@ -536,6 +541,7 @@ export const secretValidationRuleServiceFactory = ({environment,secretPath,secrets,+ excludedSecretIds,scope: reuseAcrossSecretsRule.scope,generateSecretBlindIndex},diff --git a/backend/src/services/secret-validation-rule/secret-validation-rule-types.ts b/backend/src/services/secret-validation-rule/secret-validation-rule-types.tsindex 542584f604..1001e5d59c 100644--- a/backend/src/services/secret-validation-rule/secret-validation-rule-types.ts+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-types.ts@@ -129,6 +129,11 @@ export type TValidateSecretsDTO = {envId: string;secretPath: string;secrets: TSecretToValidate[];+ /**+ * Secrets left out of the duplicate lookup without being the ones written, such as the source copies+ * a move is about to remove. Unlike `secretId`, they bring no version history into the check.+ */+ excludedSecretIds?: string[];};export type TFindConstraintsForGeneratedSecretDTO = {