Skip to content

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

fix: fix sorting logic to handle replicated imports

Scott Wilsonfa33d9843676
diff --git a/backend/src/services/secret-import/secret-import-dal.ts b/backend/src/services/secret-import/secret-import-dal.ts
index cf464c8283..c59c1656bf 100644
--- a/backend/src/services/secret-import/secret-import-dal.ts
+++ b/backend/src/services/secret-import/secret-import-dal.ts
@@ -22,29 +22,45 @@ export const secretImportDALFactory = (db: TDbClient) => {
return lastPos?.position || 0;
};
- const updateAllPosition = async (folderId: string, pos: number, targetPos: number, positionInc = 1, tx?: Knex) => {
+ const updateAllPosition = async (
+ folderId: string,
+ pos: number,
+ targetPos: number,
+ positionInc = 1,
+ tx?: Knex,
+ excludeIds?: string[]
+ ) => {
try {
if (targetPos === -1) {
// this means delete
- await (tx || db)(TableName.SecretImport)
+ const query = (tx || db)(TableName.SecretImport)
.where({ folderId })
- .andWhere("position", ">", pos)
- .decrement("position", positionInc);
+ .andWhere("position", ">", pos);
+ if (excludeIds?.length) {
+ void query.whereNotIn("id", excludeIds);
+ }
+ await query.decrement("position", positionInc);
return;
}
if (targetPos > pos) {
- await (tx || db)(TableName.SecretImport)
+ const query = (tx || db)(TableName.SecretImport)
.where({ folderId })
.where("position", "<=", targetPos)
- .andWhere("position", ">", pos)
- .decrement("position", positionInc);
+ .andWhere("position", ">", pos);
+ if (excludeIds?.length) {
+ void query.whereNotIn("id", excludeIds);
+ }
+ await query.decrement("position", positionInc);
} else {
- await (tx || db)(TableName.SecretImport)
+ const query = (tx || db)(TableName.SecretImport)
.where({ folderId })
.where("position", ">=", targetPos)
- .andWhere("position", "<", pos)
- .increment("position", positionInc);
+ .andWhere("position", "<", pos);
+ if (excludeIds?.length) {
+ void query.whereNotIn("id", excludeIds);
+ }
+ await query.increment("position", positionInc);
}
} catch (error) {
throw new DatabaseError({ error, name: "Update position" });
@@ -362,6 +378,25 @@ export const secretImportDALFactory = (db: TDbClient) => {
}
};
+ const bulkUpdatePosition = async (updates: { id: string; position: number }[], tx?: Knex) => {
+ if (!updates.length) return;
+ try {
+ const ids = updates.map(({ id }) => id);
+ const bindings: (string | number)[] = [];
+ const cases = updates
+ .map(({ id, position }) => {
+ bindings.push(id, position);
+ return `WHEN id = ? THEN ?::integer`;
+ })
+ .join(" ");
+ await (tx || db)(TableName.SecretImport)
+ .whereIn("id", ids)
+ .update({ position: db.raw(`CASE ${cases} END`, bindings) });
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Bulk update position" });
+ }
+ };
+
return {
...secretImportOrm,
find,
@@ -370,6 +405,7 @@ export const secretImportDALFactory = (db: TDbClient) => {
findByFolderIds,
findLastImportPosition,
updateAllPosition,
+ bulkUpdatePosition,
getProjectImportCount,
getUniqueImportCountByFolderIds,
getFolderIsImportedBy,
diff --git a/backend/src/services/secret-import/secret-import-service.ts b/backend/src/services/secret-import/secret-import-service.ts
index 132268bf08..9dbef01738 100644
--- a/backend/src/services/secret-import/secret-import-service.ts
+++ b/backend/src/services/secret-import/secret-import-service.ts
@@ -263,14 +263,63 @@ export const secretImportServiceFactory = ({
const updatedSecImport = await secretImportDAL.transaction(async (tx) => {
const secImp = await secretImportDAL.findOne({ folderId: folder.id, id });
if (!secImp) throw ERR_SEC_IMP_NOT_FOUND;
+
+ let finalPosition = data.position;
+
if (data.position) {
if (secImp.isReplication) {
- await secretImportDAL.updateAllPosition(folder.id, secImp.position, data.position, 2, tx);
+ const replicationFolderPath = path.join(secretPath, getReplicationFolderName(secImp.id));
+ const reservedImport = await secretImportDAL.findOne({
+ folderId: folder.id,
+ importEnv: folder.environment.id,
+ importPath: replicationFolderPath,
+ isReserved: true
+ });
+
+ const pairIds = new Set([secImp.id, ...(reservedImport ? [reservedImport.id] : [])]);
+
+ // Fetch all imports for this folder in position order.
+ const allImports = await secretImportDAL.find({ folderId: folder.id }, tx);
+ const otherImports = allImports
+ .filter((imp) => !pairIds.has(imp.id))
+ .sort((a, b) => Number(a.position) - Number(b.position));
+
+ // Determine where in the compacted list to insert the pair.
+ // data.position is the DB position of the displaced item in the original ordering.
+ let insertIndex = otherImports.length;
+ if (data.position > secImp.position) {
+ // Moving forward: pair goes after the displaced item
+ const idx = otherImports.findIndex((imp) => Number(imp.position) === data.position);
+ if (idx !== -1) insertIndex = idx + 1;
+ } else {
+ // Moving backward: pair goes before the displaced item
+ const idx = otherImports.findIndex((imp) => Number(imp.position) === data.position);
+ if (idx !== -1) insertIndex = idx;
+ }
+
+ // Build new positions for all imports: other imports get sequential positions
+ // with a 2-slot gap at insertIndex for the replication pair.
+ const positionUpdates: { id: string; position: number }[] = [];
+ let nextPos = 1;
+ for (let i = 0; i < otherImports.length; i += 1) {
+ if (i === insertIndex) nextPos += 2;
+ positionUpdates.push({ id: otherImports[i].id, position: nextPos });
+ nextPos += 1;
+ }
+
+ // The pair occupies the 2-slot gap at insertIndex + 1.
+ finalPosition = insertIndex + 1;
+ positionUpdates.push({ id: secImp.id, position: finalPosition });
+ if (reservedImport) {
+ positionUpdates.push({ id: reservedImport.id, position: finalPosition + 1 });
+ }
+
+ // Apply all position changes atomically to avoid unique constraint violations.
+ await secretImportDAL.bulkUpdatePosition(positionUpdates, tx);
} else {
await secretImportDAL.updateAllPosition(folder.id, secImp.position, data.position, 1, tx);
}
- }
- if (secImp.isReplication) {
+ } else if (secImp.isReplication) {
const replicationFolderPath = path.join(secretPath, getReplicationFolderName(secImp.id));
await secretImportDAL.update(
{
@@ -279,16 +328,15 @@ export const secretImportServiceFactory = ({
importPath: replicationFolderPath,
isReserved: true
},
- { position: data?.position ? data.position + 1 : undefined },
+ { position: undefined },
tx
);
}
+
const [doc] = await secretImportDAL.update(
{ id, folderId: folder.id },
{
- // when moving replicated import, the position is meant for reserved import
- // replicated one should always be behind the reserved import
- position: data.position,
+ position: finalPosition,
importEnv: data?.environment ? importedEnv.id : undefined,
importPath: data?.path
},
diff --git a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
index 0629ec37fe..05c296451d 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
@@ -524,7 +524,6 @@ export const OverviewPage = () => {
{ value: string; comments: string[] }
> | null>(null);
-
const { handlePopUpOpen, handlePopUpToggle, handlePopUpClose, popUp } = usePopUp([
"addSecretsInAllEnvs",
"addFolder",
@@ -792,6 +791,11 @@ export const OverviewPage = () => {
const newIndex = source.sortable.index;
if (oldIndex === newIndex) return;
+ // sortableImportItems excludes reserved imports, so UI indices don't map 1:1
+ // to DB positions when replications are present. Use the DB position of the
+ // item currently at the target slot.
+ const targetPosition = Number(sortableImportItems[newIndex].position);
+
const newImportOrder = arrayMove(sortableImportItems, oldIndex, newIndex);
setSortableImportItems(newImportOrder);
updateSecretImport({
@@ -800,7 +804,7 @@ export const OverviewPage = () => {
path: secretPath,
id: source.id as string,
import: {
- position: newIndex + 1
+ position: targetPosition
}
});
};
@@ -1233,6 +1237,8 @@ export const OverviewPage = () => {
const isTableFiltered = isFilteredByResources;
+ console.log("secret import", sortableImportItems);
+
if (!isProjectV3)
return (
<div className="flex h-full w-full flex-col items-center justify-center px-6 text-mineshaft-50 dark:scheme-dark">