Skip to content

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

feat: rename secret references

Daniel Hougaarda4d1edbfed9c
diff --git a/backend/src/lib/knex/index.ts b/backend/src/lib/knex/index.ts
index 499e7cb26d..230d5cb392 100644
--- a/backend/src/lib/knex/index.ts
+++ b/backend/src/lib/knex/index.ts
@@ -23,6 +23,7 @@ export const withTransaction = <K extends object>(db: Knex, dal: K) => ({
export type TFindFilter<R extends object = object> = Partial<R> & {
$in?: Partial<{ [k in keyof R]: R[k][] }>;
+ $notEqual?: Partial<{ [k in keyof R]: R[k] }>;
$notNull?: Array<keyof R>;
$search?: Partial<{ [k in keyof R]: R[k] }>;
$complex?: TKnexDynamicOperator<R>;
@@ -30,7 +31,7 @@ export type TFindFilter<R extends object = object> = Partial<R> & {
export const buildFindFilter =
<R extends object = object>(
- { $in, $notNull, $search, $complex, ...filter }: TFindFilter<R>,
+ { $in, $notNull, $search, $complex, $notEqual, ...filter }: TFindFilter<R>,
tableName?: TableName,
excludeKeys?: string[]
) =>
@@ -52,6 +53,14 @@ export const buildFindFilter =
});
}
+ if ($notEqual) {
+ Object.entries($notEqual).forEach(([key, val]) => {
+ if (val) {
+ void bd.whereNot(`${tableName ? `${tableName}.` : ""}${key}`, val as never);
+ }
+ });
+ }
+
if ($notNull?.length) {
$notNull.forEach((key) => {
void bd.whereNotNull(`${tableName ? `${tableName}.` : ""}${key as string}`);
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
index bfddd7e9e1..e08aa9a969 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
@@ -138,7 +138,7 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
}
};
- const find = async (filter: TFindFilter<TSecretsV2>, opts: TFindOpt<TSecretsV2> = {}) => {
+ const find = async (filter: TFindFilter<TSecretsV2 & { projectId?: string }>, opts: TFindOpt<TSecretsV2> = {}) => {
const { offset, limit, sort, tx } = opts;
try {
const query = (tx || db.replicaNode())(TableName.SecretV2)
@@ -160,6 +160,8 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
`${TableName.SecretV2}.id`,
`${TableName.SecretRotationV2SecretMapping}.secretId`
)
+ .leftJoin(TableName.SecretFolder, `${TableName.SecretV2}.folderId`, `${TableName.SecretFolder}.id`)
+ .leftJoin(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
.select(
db.ref("id").withSchema(TableName.ResourceMetadata).as("metadataId"),
db.ref("key").withSchema(TableName.ResourceMetadata).as("metadataKey"),
@@ -167,10 +169,16 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
db.ref("value").withSchema(TableName.ResourceMetadata).as("metadataValue")
)
.select(selectAllTableCols(TableName.SecretV2))
+ .select(db.ref("projectId").withSchema(TableName.Environment).as("environmentProjectId"))
.select(db.ref("id").withSchema(TableName.SecretTag).as("tagId"))
.select(db.ref("color").withSchema(TableName.SecretTag).as("tagColor"))
.select(db.ref("slug").withSchema(TableName.SecretTag).as("tagSlug"))
.select(db.ref("rotationId").withSchema(TableName.SecretRotationV2SecretMapping));
+
+ if (filter?.projectId) {
+ void query.where(`${TableName.Environment}.projectId`, filter.projectId);
+ }
+
if (limit) void query.limit(limit);
if (offset) void query.offset(offset);
if (sort) {
@@ -185,7 +193,8 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
_id: el.id,
...SecretsV2Schema.parse(el),
rotationId: el.rotationId,
- isRotatedSecret: Boolean(el.rotationId)
+ isRotatedSecret: Boolean(el.rotationId),
+ projectId: el.environmentProjectId
}),
childrenMapper: [
{
@@ -771,6 +780,39 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
}
};
+ const updateSecretReferenceSecretKey = async (
+ projectId: string,
+ envSlug: string,
+ secretPath: string,
+ oldSecretKey: string,
+ newSecretKey: string,
+ tx?: Knex
+ ) => {
+ try {
+ // Update all SecretReferenceV2 records that reference the old key
+ // We need to join to ensure we're only updating references within this project
+ const updatedCount = await (tx || db)(TableName.SecretReferenceV2)
+ .whereIn("secretId", (qb) => {
+ void qb
+ .select(`${TableName.SecretV2}.id`)
+ .from(TableName.SecretV2)
+ .join(TableName.SecretFolder, `${TableName.SecretV2}.folderId`, `${TableName.SecretFolder}.id`)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .where(`${TableName.Environment}.projectId`, projectId);
+ })
+ .where({
+ environment: envSlug,
+ secretPath,
+ secretKey: oldSecretKey
+ })
+ .update({ secretKey: newSecretKey });
+
+ return updatedCount;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "UpdateSecretReferenceSecretKey" });
+ }
+ };
+
const upsertSecretReferences = async (
data: {
secretId: string;
@@ -825,6 +867,33 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
}
};
+ const findReferencedSecretReferencesBySecretKey = async (
+ projectId: string,
+ envSlug: string,
+ secretPath: string,
+ secretKey: string,
+ tx?: Knex
+ ) => {
+ try {
+ const docs = await (tx || db.replicaNode())(TableName.SecretReferenceV2)
+ .where({
+ secretPath,
+ environment: envSlug,
+ secretKey
+ })
+ .join(TableName.SecretV2, `${TableName.SecretV2}.id`, `${TableName.SecretReferenceV2}.secretId`)
+ .join(TableName.SecretFolder, `${TableName.SecretV2}.folderId`, `${TableName.SecretFolder}.id`)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .where("projectId", projectId)
+ .select(selectAllTableCols(TableName.SecretReferenceV2))
+ .select("folderId");
+
+ return docs;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindReferencedSecretReferencesBySecretKey" });
+ }
+ };
+
// special query to backfill secret value
const findAllProjectSecretValues = async (projectId: string, tx?: Knex) => {
try {
@@ -1003,6 +1072,8 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
find,
invalidateSecretCacheByProjectId,
findSecretsWithReminderRecipients,
- findSecretsWithReminderRecipientsOld
+ findSecretsWithReminderRecipientsOld,
+ findReferencedSecretReferencesBySecretKey,
+ updateSecretReferenceSecretKey
};
};
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.ts
index 7e4c1799e2..a9cc9cf2b2 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
@@ -1,5 +1,6 @@
import { ForbiddenError, MongoAbility, subject } from "@casl/ability";
import { Knex } from "knex";
+import RE2 from "re2";
import { z } from "zod";
import {
@@ -85,12 +86,17 @@ import {
TGetSecretVersionsDTO,
TMoveSecretsDTO,
TSecretReference,
+ TUpdateLinkedSecretReferencesDTO,
TUpdateManySecretDTO,
TUpdateSecretDTO
} from "./secret-v2-bridge-types";
import { TSecretVersionV2DALFactory } from "./secret-version-dal";
import { TSecretVersionV2TagDALFactory } from "./secret-version-tag-dal";
+function escapeRegex(str: string): string {
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
type TSecretV2BridgeServiceFactoryDep = {
secretDAL: TSecretV2BridgeDALFactory;
projectDAL: Pick<TProjectDALFactory, "findById">;
@@ -151,6 +157,105 @@ export const secretV2BridgeServiceFactory = ({
keyStore,
reminderService
}: TSecretV2BridgeServiceFactoryDep) => {
+ const $updateLinkedSecretReferences = async (
+ {
+ projectId,
+ environment,
+ secretPath,
+ folderId,
+ oldSecretKey,
+ newSecretKey,
+ secretId
+ }: TUpdateLinkedSecretReferencesDTO,
+ tx?: Knex
+ ) => {
+ const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ // 1. Handle NESTED references (from SecretReferenceV2 table - cross-env/path)
+ const nestedSecretReferences = await secretDAL.findReferencedSecretReferencesBySecretKey(
+ projectId,
+ environment,
+ secretPath,
+ oldSecretKey,
+ tx
+ );
+
+ // 2. Handle LOCAL references (same folder only)
+ // Get all other secrets in the same folder that might have local refs
+ const secretsInSameFolder = await secretDAL.find(
+ {
+ folderId,
+ $notEqual: { [`${TableName.SecretV2}.id` as "id"]: secretId }
+ },
+ { tx }
+ );
+
+ // Combine: nested refs point to secrets by ID, local refs need folder scan
+ const secretIdsToUpdateFromNested = nestedSecretReferences.map((el) => el.secretId);
+
+ // For local refs, we need to check each secret in the folder
+ const secretsToCheck = secretsInSameFolder.filter(
+ (s) => !secretIdsToUpdateFromNested.includes(s.id) // Don't double-process
+ );
+
+ // Process nested reference secrets
+ const nestedSecretsToUpdate = await secretDAL.find(
+ { $in: { [`${TableName.SecretV2}.id` as "id"]: secretIdsToUpdateFromNested } },
+ { tx }
+ );
+
+ const allSecretsToUpdate: Array<TSecretsV2> = [...nestedSecretsToUpdate, ...secretsToCheck];
+
+ for await (const secretToUpdate of allSecretsToUpdate) {
+ // eslint-disable-next-line no-continue
+ if (!secretToUpdate.encryptedValue) continue;
+
+ const originalValue = decryptor({ cipherTextBlob: secretToUpdate.encryptedValue }).toString();
+ let newValue = originalValue;
+
+ const { localReferences, nestedReferences } = getAllSecretReferences(originalValue);
+
+ // Check if this secret references the renamed secret at all (either locally or nested)
+ const hasLocalRef = localReferences.includes(oldSecretKey);
+ const hasNestedRef = nestedReferences.some(
+ (ref) => ref.environment === environment && ref.secretPath === secretPath && ref.secretKey === oldSecretKey
+ );
+
+ // eslint-disable-next-line no-continue
+ if (!hasLocalRef && !hasNestedRef) continue; // No reference to renamed secret, skip
+
+ // Replace LOCAL references: ${OLD_KEY} -> ${NEW_KEY}
+ if (hasLocalRef) {
+ newValue = newValue.replace(new RE2(`\\$\\{${escapeRegex(oldSecretKey)}\\}`, "g"), `\${${newSecretKey}}`);
+ }
+
+ // Replace NESTED references: ${env.path.OLD_KEY} -> ${env.path.NEW_KEY}
+ if (hasNestedRef) {
+ const pathPart = secretPath === "/" ? "" : `.${secretPath.slice(1).replace(/\//g, ".")}`;
+
+ const oldRef = `\${${environment}${pathPart}.${oldSecretKey}}`;
+ const newRef = `\${${environment}${pathPart}.${newSecretKey}}`;
+
+ // Using split/join handles multiple occurrences
+ newValue = newValue.split(oldRef).join(newRef);
+ }
+
+ if (newValue !== originalValue) {
+ await secretDAL.updateById(
+ secretToUpdate.id,
+ { encryptedValue: encryptor({ plainText: Buffer.from(newValue) }).cipherTextBlob },
+ tx
+ );
+ }
+ }
+
+ // Update the SecretReferenceV2 records for nested refs
+ await secretDAL.updateSecretReferenceSecretKey(projectId, environment, secretPath, oldSecretKey, newSecretKey, tx);
+ };
+
const $validateSecretReferences = async (
projectId: string,
permission: MongoAbility<ProjectPermissionSet>,
@@ -652,6 +757,21 @@ export const secretV2BridgeServiceFactory = ({
tx
});
+ if (inputSecret.newSecretName && inputSecret.type === SecretType.Shared) {
+ await $updateLinkedSecretReferences(
+ {
+ projectId,
+ environment,
+ secretPath,
+ folderId,
+ oldSecretKey: secretName,
+ newSecretKey: inputSecret.newSecretName,
+ secretId
+ },
+ tx
+ );
+ }
+
await secretDAL.invalidateSecretCacheByProjectId(projectId, tx);
return modifiedSecretsInDB;
});
@@ -2151,6 +2271,12 @@ export const secretV2BridgeServiceFactory = ({
project.secretDetectionIgnoreValues || []
);
+ const secretKeyUpdates: {
+ secretId: string;
+ oldSecretKey: string;
+ newSecretKey: string;
+ }[] = [];
+
const bulkUpdatedSecrets = await fnSecretBulkUpdate({
folderId,
orgId: actorOrgId,
@@ -2162,6 +2288,14 @@ export const secretV2BridgeServiceFactory = ({
const shouldUpdateValue = !originalSecret.isRotatedSecret && typeof el.secretValue !== "undefined";
const shouldUpdateName = !originalSecret.isRotatedSecret && el.newSecretName;
+ if (shouldUpdateName && el.newSecretName && originalSecret.type === SecretType.Shared) {
+ secretKeyUpdates.push({
+ secretId: originalSecret.id,
+ oldSecretKey: originalSecret.key,
+ newSecretKey: el.newSecretName
+ });
+ }
+
const encryptedValue =
shouldUpdateValue && el.secretValue !== undefined
? {
@@ -2201,6 +2335,23 @@ export const secretV2BridgeServiceFactory = ({
resourceMetadataDAL
});
+ if (secretKeyUpdates.length) {
+ for await (const secretKeyUpdate of secretKeyUpdates) {
+ await $updateLinkedSecretReferences(
+ {
+ projectId,
+ environment,
+ secretPath,
+ folderId,
+ secretId: secretKeyUpdate.secretId,
+ oldSecretKey: secretKeyUpdate.oldSecretKey,
+ newSecretKey: secretKeyUpdate.newSecretKey
+ },
+ tx
+ );
+ }
+ }
+
updatedSecrets.push(
...bulkUpdatedSecrets.map((el, i) => ({
...el,
@@ -2208,6 +2359,7 @@ export const secretV2BridgeServiceFactory = ({
secretMetadata: secretsToUpdate?.[i].secretMetadata
}))
);
+
if (updateMode === SecretUpdateMode.Upsert) {
const bulkInsertedSecrets = await fnSecretBulkInsert({
inputSecrets: secretsToCreate.map((el) => {
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.ts
index 6a12b3d2b3..21b1b0a1ae 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
@@ -384,3 +384,13 @@ export type TGetAccessibleSecretsDTO = {
recursive?: boolean;
filterByAction: ProjectPermissionSecretActions.DescribeSecret | ProjectPermissionSecretActions.ReadValue;
} & TProjectPermission;
+
+export type TUpdateLinkedSecretReferencesDTO = {
+ projectId: string;
+ environment: string;
+ secretPath: string;
+ folderId: string;
+ secretId: string;
+ oldSecretKey: string;
+ newSecretKey: string;
+};