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
Merge remote-tracking branch 'origin/main' into matheus/prevent-duplicate-secret-values
Matheus Nogueira90a1258e3aa9
diff --cc backend/src/services/secret-v2-bridge/secret-v2-bridge-service.tsindex 9364604435,2effc24060..bbcfacbaf6--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts@@@ -2152,29 -2172,51 +2188,40 @@@ export const secretV2BridgeServiceFacto});const folderId = folder.id;- const secrets = await secretDAL.find({- folderId,- type: SecretType.Shared,- $in: {- [`${TableName.SecretV2}.key` as "key"]: deduplicatedSecrets.map((el) => el.secretKey)- }- });+ const secrets = await secretDAL.find(+ {+ folderId,+ type: SecretType.Shared,+ $in: {+ [`${TableName.SecretV2}.key` as "key"]: deduplicatedSecrets.map((el) => el.secretKey)+ }+ },+ { tx: providedTx }+ );if (secrets.length)- throw new BadRequestError({ message: `Secret already exists: ${secrets.map((el) => el.key).join(",")}` });+ throw new BadRequestError({+ message: `Secret already exists: ${secrets.map((el) => `'${el.key}'`).join(", ")} in path '${secretPath}' of environment '${environment}'`+ });- const project = await requestMemoize(requestMemoKeys.projectFindById(projectId), () =>- projectDAL.findById(projectId)- );- await scanSecretPolicyViolations(- projectId,- secretPath,- deduplicatedSecrets,- project.secretDetectionIgnoreValues || []- );+ // requestMemoize can hand back a value read outside a caller-supplied transaction, so it is bypassed here+ const project = providedTx+ ? await projectDAL.findById(projectId, providedTx)+ : await requestMemoize(requestMemoKeys.projectFindById(projectId), () => projectDAL.findById(projectId));++ if (!providedTx) {+ await scanSecretPolicyViolations(+ projectId,+ secretPath,+ deduplicatedSecrets,+ project.secretDetectionIgnoreValues || []+ );+ }- await secretValidationRuleService.validateSecrets(- {- projectId,- environment,- envId: folder.envId,- secretPath,- secrets: deduplicatedSecrets.map((s) => ({ key: s.secretKey, value: s.secretValue }))- },- providedTx- );-// get all tagsconst sanitizedTagIds = [...new Set(deduplicatedSecrets.flatMap(({ tagIds = [] }) => tagIds))];- const tags = sanitizedTagIds.length ? await secretTagDAL.findManyTagsById(projectId, sanitizedTagIds) : [];+ const tags = sanitizedTagIds.length+ ? await secretTagDAL.findManyTagsById(projectId, sanitizedTagIds, providedTx)+ : [];if (tags.length !== sanitizedTagIds.length)throw new NotFoundError({ message: `Tag not found. Found ${tags.map((el) => el.slug).join(",")}` });const tagsGroupByID = groupBy(tags, (i) => i.id);@@@ -2210,21 -2252,9 +2257,21 @@@encryptor: secretManagerEncryptor,decryptor: secretManagerDecryptor,generateSecretBlindIndex- } = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });+ } = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId }, providedTx);const executeBulkInsert = async (tx: Knex) => {+ await secretValidationRuleService.validateSecrets(+ {+ projectId,+ environment,+ envId: folder.envId,+ secretPath,+ secrets: deduplicatedSecrets.map((s) => ({ key: s.secretKey, value: s.secretValue })),+ canAccessLocation: $canDescribeSecretAt(permission)+ },+ tx+ );+const inputSecretsWithBlindIndex = await Promise.all(deduplicatedSecrets.map(async (el) => {const references = secretReferencesGroupByInputSecretKey[el.secretKey]?.nestedReferences;diff --cc backend/src/services/secret-validation-rule/secret-validation-rule-service.tsindex eaad5e6505,b044351602..a3cdd57ff9--- a/backend/src/services/secret-validation-rule/secret-validation-rule-service.ts+++ b/backend/src/services/secret-validation-rule/secret-validation-rule-service.ts@@@ -108,8 -99,8 +108,9 @@@ export const secretValidationRuleServic}};-- const $getCipher = (projectId: string) =>-- kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });++ // Pass `tx` from inside a transaction: without it the key lookup checks out a second connection.++ const $getCipher = (projectId: string, tx?: Knex) =>++ kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId }, tx);// Listed rather than spread so `encryptedInputs` can never reach a response.const $toRecord = (rule: TSecretValidationRuleWithEnv, config: TSecretValidationRuleConfig) =>@@@ -396,112 -372,8 +397,108 @@@return $toRecord(rule, config);};+ /**+ * The secret already holding each incoming value, keyed by the incoming key, for the secrets that+ * collide with one. Values are matched through the project's blind index rather than by reading+ * 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.+ */+ const $findDuplicatesInScope = async (+ {+ projectId,+ environment,+ secretPath,+ secrets,+ scope,+ canAccessLocation,+ generateSecretBlindIndex+ }: Pick<TValidateSecretsDTO, "projectId" | "environment" | "secretPath" | "secrets" | "canAccessLocation"> & {+ scope: { envId?: string | null; secretPath: string };+ generateSecretBlindIndex: (value: Buffer) => Promise<string>;+ },+ tx?: Knex+ ): Promise<Record<string, TDuplicateSecret>> => {+ const candidates = secrets.filter(+ (secret): secret is typeof secret & { value: string } =>+ secret.value !== undefined && !containsSecretReference(secret.value)+ );+ if (!candidates.length) return {};++ // Two writes of the same value would each find no duplicate and both land. The lock makes this+ // check and the write that follows it atomic, so the second one sees the first.+ if (tx) await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.SecretValueUniqueCheck(projectId)]);++ const blindIndexes = await Promise.all(+ candidates.map((secret) => generateSecretBlindIndex(Buffer.from(secret.value)))+ );++ const duplicates: Record<string, TDuplicateSecret> = {};++ // Two secrets in one request can collide with each other before either exists in the database.+ const seenInBatch = new Map<string, TDuplicateSecret>();+ candidates.forEach((secret, idx) => {+ const seen = seenInBatch.get(blindIndexes[idx]);+ if (seen) duplicates[secret.key] = seen;+ else seenInBatch.set(blindIndexes[idx], { key: secret.key, environment, secretPath });+ });++ const excludedSecretIds = candidates.map((secret) => secret.secretId).filter(Boolean) as string[];+ const existing = await secretDAL.findExistingSecretsByBlindIndexes(+ projectId,+ [...new Set(blindIndexes)],+ excludedSecretIds.length ? excludedSecretIds : undefined,+ scope.envId ?? undefined,+ tx+ );+ if (!existing.length) return duplicates;++ const folderIds = [...new Set(existing.map((secret) => secret.folderId))];+ const folderPaths = await folderDAL.findSecretPathByFolderIds(projectId, folderIds, tx);+ const pathByFolderId = new Map(folderIds.map((id, idx) => [id, folderPaths[idx]?.path ?? "/"]));++ const accessByLocation = new Map<string, boolean>();+ const isHidden = (dupEnvironment: string, dupPath: string) => {+ if (!canAccessLocation) return false;++ const location = `${dupEnvironment}:${dupPath}`;+ let hidden = accessByLocation.get(location);+ if (hidden === undefined) {+ hidden = !canAccessLocation(dupEnvironment, dupPath);+ accessByLocation.set(location, hidden);+ }+ return hidden;+ };++ // The lookup spans the project, so drop the hits the rule's own path does not reach.+ const inScope = new Map<string, TDuplicateSecret>();+ existing.forEach((secret) => {+ if (!secret.secretValueBlindIndex || inScope.has(secret.secretValueBlindIndex)) return;++ const dupPath = pathByFolderId.get(secret.folderId) ?? "/";+ if (!doesRulePathCover(scope.secretPath, dupPath)) return;++ inScope.set(secret.secretValueBlindIndex, {+ key: secret.key,+ environment: secret.environment,+ secretPath: dupPath,+ hidden: isHidden(secret.environment, dupPath)+ });+ });++ candidates.forEach((secret, idx) => {+ if (duplicates[secret.key]) return;++ const duplicate = inScope.get(blindIndexes[idx]);+ if (duplicate) duplicates[secret.key] = duplicate;+ });++ return duplicates;+ };+- /**- * Pass `tx` when the caller already holds a transaction, or this checks out a second connection.- * `${env.key}` references are expanded first, so constraints see the resolved value.- */const validateSecrets = async (- { projectId, environment, envId, secretPath, secrets }: TValidateSecretsDTO,+ { projectId, environment, envId, secretPath, secrets, canAccessLocation }: TValidateSecretsDTO,tx?: Knex) => {if (!secrets.length) return;@@@ -512,7 -384,7 +509,7 @@@);if (!rules.length) return;- const { decryptor, generateSecretBlindIndex } = await $getCipher(projectId);- const { decryptor } = await $getCipher(projectId);++ const { decryptor, generateSecretBlindIndex } = await $getCipher(projectId, tx);const coveringRules = findRulesCoveringScope(rules, { envId, secretPath }).map((rule) => ({name: rule.name,