Skip to content

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

Improvement on the recursive secrets fetch to reduce the DB usage

Carlos Monastyrski82d1e4632156
diff --git a/backend/src/services/secret-folder/secret-folder-dal.ts b/backend/src/services/secret-folder/secret-folder-dal.ts
index f2befbe1ad..3eb8b22856 100644
--- a/backend/src/services/secret-folder/secret-folder-dal.ts
+++ b/backend/src/services/secret-folder/secret-folder-dal.ts
@@ -3,13 +3,20 @@ import { Knex } from "knex";
import { TDbClient } from "@app/db";
import { TableName, TSecretFolders, TSecretFoldersUpdate } from "@app/db/schemas";
import { BadRequestError, DatabaseError } from "@app/lib/errors";
-import { groupBy, removeTrailingSlash } from "@app/lib/fn";
+import { groupBy, removeTrailingSlash, unique } from "@app/lib/fn";
import { ormify, selectAllTableCols } from "@app/lib/knex";
import { OrderByDirection } from "@app/lib/types";
import { isValidSecretPath } from "@app/lib/validator";
import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";
import { SecretsOrderBy } from "@app/services/secret/secret-types";
+import {
+ buildChildrenMap,
+ buildFolderIdMap,
+ buildFolderPath,
+ resolveClosestFolder,
+ resolvePathToFolder
+} from "./secret-folder-fns";
import { TFindFoldersDeepByParentIdsDTO } from "./secret-folder-types";
export const validateFolderName = characterValidator([
@@ -18,193 +25,6 @@ export const validateFolderName = characterValidator([
CharacterType.Underscore
]);
-const sqlFindMultipleFolderByEnvPathQuery = (db: Knex, query: Array<{ envId: string; secretPath: string }>) => {
- // this is removing an trailing slash like /folder1/folder2/ -> /folder1/folder2
- const formatedQuery = query.map(({ envId, secretPath }) => {
- const formatedPath = secretPath.at(-1) === "/" && secretPath.length > 1 ? secretPath.slice(0, -1) : secretPath;
- const segments = formatedPath.split("/").filter(Boolean);
- if (segments.some((segment) => !validateFolderName(segment))) {
- throw new BadRequestError({ message: "Invalid folder name" });
- }
- return {
- envId,
- secretPath: segments
- };
- });
- // next goal to sanitize saw the raw sql query is safe
- // for this we ensure folder name contains only string and - nothing else
-
- return db
- .withRecursive("parent", (baseQb) => {
- // first remember our folders are connected as a link list or known as adjacency list
- // Thus each node has connection to parent node
- // for a given path from root we recursively reach to the leaf path or till we get null
- // the below query is the base case where we select root folder which has parent folder id as null
- void baseQb
- .select({
- depth: 1,
- path: db.raw("'/'")
- })
- .from(TableName.SecretFolder)
- .where({
- parentId: null,
- name: "root"
- })
- .whereIn(
- "envId",
- formatedQuery.map(({ envId }) => envId)
- )
- .select(selectAllTableCols(TableName.SecretFolder))
- .union(
- (qb) =>
- // for here on we keep going to next child node.
- // we also keep a measure of depth then we check the depth matches the array path segment and folder name
- // that is at depth 1 for a path /folder1/folder2 -> the name should be folder1
- void qb
- .select({
- depth: db.raw("parent.depth + 1"),
- path: db.raw(
- "CONCAT((CASE WHEN parent.path = '/' THEN '' ELSE parent.path END),'/', secret_folders.name)"
- )
- })
- .select(selectAllTableCols(TableName.SecretFolder))
- .where((wb) =>
- formatedQuery.map(({ secretPath }) =>
- wb.orWhereRaw(
- `secret_folders.name = (ARRAY[${secretPath.map(() => "?").join(",")}]::varchar[])[depth]`,
- [...secretPath]
- )
- )
- )
- .from(TableName.SecretFolder)
- .join("parent", (bd) =>
- bd
- .on("parent.id", `${TableName.SecretFolder}.parentId`)
- .andOn("parent.envId", `${TableName.SecretFolder}.envId`)
- )
- );
- })
- .select("*")
- .from<TSecretFolders & { depth: number; path: string }>("parent");
-};
-
-const sqlFindFolderByPathQuery = (db: Knex, projectId: string, environments: string[], secretPath: string) => {
- // this is removing an trailing slash like /folder1/folder2/ -> /folder1/folder2
- const formatedPath = secretPath.at(-1) === "/" && secretPath.length > 1 ? secretPath.slice(0, -1) : secretPath;
- // next goal to sanitize saw the raw sql query is safe
- // for this we ensure folder name contains only string and - nothing else
- const pathSegments = formatedPath.split("/").filter(Boolean);
- if (pathSegments.some((segment) => !validateFolderName(segment))) {
- throw new BadRequestError({ message: "Invalid folder name" });
- }
-
- return db
- .withRecursive("parent", (baseQb) => {
- // first remember our folders are connected as a link list or known as adjacency list
- // Thus each node has connection to parent node
- // for a given path from root we recursively reach to the leaf path or till we get null
- // the below query is the base case where we select root folder which has parent folder id as null
- void baseQb
- .select({
- depth: 1,
- path: db.raw("'/'")
- })
- .from(TableName.SecretFolder)
- .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
- .where({
- projectId,
- parentId: null
- })
- .whereIn(`${TableName.Environment}.slug`, environments)
- .select(
- db.ref("slug").withSchema(TableName.Environment).as("envSlug"),
- db.ref("name").withSchema(TableName.Environment).as("envName"),
- db.ref("projectId").withSchema(TableName.Environment)
- )
- .select(selectAllTableCols(TableName.SecretFolder))
- .union(
- (qb) =>
- // for here on we keep going to next child node.
- // we also keep a measure of depth then we check the depth matches the array path segment and folder name
- // that is at depth 1 for a path /folder1/folder2 -> the name should be folder1
- void qb
- .select({
- depth: db.raw("parent.depth + 1"),
- path: db.raw(
- "CONCAT((CASE WHEN parent.path = '/' THEN '' ELSE parent.path END),'/', secret_folders.name)"
- ),
- envSlug: db.ref("envSlug").withSchema("parent"),
- envName: db.ref("envName").withSchema("parent"),
- projectId: db.ref("projectId").withSchema("parent")
- })
- .select(selectAllTableCols(TableName.SecretFolder))
- .whereRaw(`secret_folders.name = (ARRAY[${pathSegments.map(() => "?").join(",")}]::varchar[])[depth]`, [
- ...pathSegments
- ])
- .from(TableName.SecretFolder)
- .join("parent", "parent.id", `${TableName.SecretFolder}.parentId`)
- );
- })
- .from<TSecretFolders & { depth: number; path: string }>("parent")
- .select<
- (TSecretFolders & {
- depth: number;
- path: string;
- envId: string;
- envSlug: string;
- envName: string;
- projectId: string;
- })[]
- >(selectAllTableCols("parent" as TableName.SecretFolder));
-};
-
-const sqlFindSecretPathByFolderId = (db: Knex, projectId: string, folderIds: string[]) =>
- db
- .withRecursive("parent", (baseQb) => {
- // first remember our folders are connected as a link list or known as adjacency list
- // Thus each node has connection to parent node
- // we first find the folder given in folder id
- void baseQb
- .from(TableName.SecretFolder)
- .select(selectAllTableCols(TableName.SecretFolder))
- .select({
- // this is for root condition
- // if the given folder id is root folder id then intial path is set as / instead of /root
- // if not root folder the path here will be /<folder name>
- depth: 1,
- path: db.raw(`CONCAT('/', (CASE WHEN "parentId" is NULL THEN '' ELSE ${TableName.SecretFolder}.name END))`),
- child: db.raw("NULL::uuid"),
- environmentSlug: `${TableName.Environment}.slug`
- })
- .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
- .where({ projectId })
- .whereIn(`${TableName.SecretFolder}.id`, folderIds)
- .union(
- (qb) =>
- // then we keep going up
- // until parent id is null
- void qb
- .select(selectAllTableCols(TableName.SecretFolder))
- .select({
- // then we join join this folder name behind previous as we are going from child to parent
- // the root folder check is used to avoid last / and also root name in folders
- depth: db.raw("parent.depth + 1"),
- path: db.raw(
- `CONCAT( CASE
- WHEN ${TableName.SecretFolder}."parentId" is NULL THEN ''
- ELSE CONCAT('/', secret_folders.name)
- END, parent.path )`
- ),
- child: db.raw("COALESCE(parent.child, parent.id)"),
- environmentSlug: "parent.environmentSlug"
- })
- .from(TableName.SecretFolder)
- .join("parent", "parent.parentId", `${TableName.SecretFolder}.id`)
- );
- })
- .select("*")
- .from<TSecretFolders & { child: string | null; path: string; environmentSlug: string; depth: number }>("parent");
-
export type TSecretFolderDALFactory = ReturnType<typeof secretFolderDALFactory>;
// never change this. If u do write a migration for it
export const ROOT_FOLDER_NAME = "root";
@@ -218,14 +38,30 @@ export const secretFolderDALFactory = (db: TDbClient) => {
message: "Invalid secret path. Only alphanumeric characters, dashes, and underscores are allowed."
});
const formatedPath = removeTrailingSlash(path);
+ const pathSegments = formatedPath.split("/").filter(Boolean);
+ if (pathSegments.some((segment) => !validateFolderName(segment))) {
+ throw new BadRequestError({ message: "Invalid folder name" });
+ }
+
try {
- const query = sqlFindFolderByPathQuery(tx || db.replicaNode(), projectId, [environment], formatedPath)
- .where("path", formatedPath)
- .first();
- const folder = await query;
+ const folders = await (tx || db.replicaNode())(TableName.SecretFolder)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .where(`${TableName.Environment}.projectId`, projectId)
+ .where(`${TableName.Environment}.slug`, environment)
+ .select(
+ selectAllTableCols(TableName.SecretFolder),
+ db.ref("id").withSchema(TableName.Environment).as("envId"),
+ db.ref("slug").withSchema(TableName.Environment).as("envSlug"),
+ db.ref("name").withSchema(TableName.Environment).as("envName")
+ );
+
+ const childrenMap = buildChildrenMap(folders);
+ const folder = resolvePathToFolder(childrenMap, pathSegments);
if (!folder) return;
- const { envId: id, envName: name, envSlug: slug, ...el } = folder;
- return { ...el, envId: id, environment: { id, name, slug } };
+
+ const envInfo = folders[0] as (typeof folders)[0] & { envSlug: string; envName: string };
+ const { envId: id, envName: name, envSlug: slug } = envInfo;
+ return { ...folder, envId: id, path: formatedPath, projectId, environment: { id, name, slug } };
} catch (error) {
throw new DatabaseError({ error, name: "Find by secret path" });
}
@@ -239,19 +75,50 @@ export const secretFolderDALFactory = (db: TDbClient) => {
message: "Invalid secret path. Only alphanumeric characters, dashes, and underscores are allowed."
});
+ const formatedPath = removeTrailingSlash(path);
+ const pathSegments = formatedPath.split("/").filter(Boolean);
+ if (pathSegments.some((segment) => !validateFolderName(segment))) {
+ throw new BadRequestError({ message: "Invalid folder name" });
+ }
+
try {
- const formatedPath = removeTrailingSlash(path);
- const folders = await sqlFindFolderByPathQuery(
- tx || db.replicaNode(),
- projectId,
- environments,
- formatedPath
- ).where("path", removeTrailingSlash(path));
+ const allFolders = await (tx || db.replicaNode())(TableName.SecretFolder)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .where(`${TableName.Environment}.projectId`, projectId)
+ .whereIn(`${TableName.Environment}.slug`, environments)
+ .select(
+ selectAllTableCols(TableName.SecretFolder),
+ db.ref("id").withSchema(TableName.Environment).as("envId"),
+ db.ref("slug").withSchema(TableName.Environment).as("envSlug"),
+ db.ref("name").withSchema(TableName.Environment).as("envName")
+ );
- return folders.map((folder) => {
- const { envId: id, envName: name, envSlug: slug, ...el } = folder;
- return { ...el, envId: id, environment: { id, name, slug } };
- });
+ const foldersByEnv = groupBy(allFolders, (f) => f.envId);
+
+ const results: (TSecretFolders & {
+ envId: string;
+ path: string;
+ projectId: string;
+ environment: { id: string; name: string; slug: string };
+ })[] = [];
+
+ for (const envId of Object.keys(foldersByEnv)) {
+ const envFolders = foldersByEnv[envId];
+ const childrenMap = buildChildrenMap(envFolders);
+ const folder = resolvePathToFolder(childrenMap, pathSegments);
+ if (folder) {
+ const envInfo = envFolders[0] as (typeof envFolders)[0] & { envSlug: string; envName: string };
+ results.push({
+ ...folder,
+ envId: envInfo.envId,
+ path: formatedPath,
+ projectId,
+ environment: { id: envInfo.envId, name: envInfo.envName, slug: envInfo.envSlug }
+ });
+ }
+ }
+
+ return results;
} catch (error) {
throw new DatabaseError({ error, name: "Find folders by secret path multi env" });
}
@@ -267,18 +134,40 @@ export const secretFolderDALFactory = (db: TDbClient) => {
message: "Invalid secret path. Only alphanumeric characters, dashes, and underscores are allowed."
});
+ const formatedPath = removeTrailingSlash(path);
+ const pathSegments = formatedPath.split("/").filter(Boolean);
+ if (pathSegments.some((segment) => !validateFolderName(segment))) {
+ throw new BadRequestError({ message: "Invalid folder name" });
+ }
+
try {
- const folder = await sqlFindFolderByPathQuery(
- tx || db.replicaNode(),
- projectId,
- [environment],
- removeTrailingSlash(path)
- )
- .orderBy("depth", "desc")
- .first();
+ const folders = await (tx || db.replicaNode())(TableName.SecretFolder)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .where(`${TableName.Environment}.projectId`, projectId)
+ .where(`${TableName.Environment}.slug`, environment)
+ .select(
+ selectAllTableCols(TableName.SecretFolder),
+ db.ref("id").withSchema(TableName.Environment).as("envId"),
+ db.ref("slug").withSchema(TableName.Environment).as("envSlug"),
+ db.ref("name").withSchema(TableName.Environment).as("envName")
+ );
+
+ const childrenMap = buildChildrenMap(folders);
+ const folder = resolveClosestFolder(childrenMap, pathSegments);
if (!folder) return;
- const { envId: id, envName: name, envSlug: slug, ...el } = folder;
- return { ...el, envId: id, environment: { id, name, slug } };
+
+ // Compute the actual path of the resolved folder
+ const idMap = buildFolderIdMap(folders);
+ const resolvedPath = buildFolderPath(folder, idMap);
+
+ const envInfo = folders[0] as (typeof folders)[0] & { envSlug: string; envName: string };
+ return {
+ ...folder,
+ envId: envInfo.envId,
+ path: resolvedPath,
+ projectId,
+ environment: { id: envInfo.envId, name: envInfo.envName, slug: envInfo.envSlug }
+ };
} catch (error) {
throw new DatabaseError({ error, name: "Find by secret path" });
}
@@ -290,10 +179,30 @@ export const secretFolderDALFactory = (db: TDbClient) => {
envId,
secretPath: removeTrailingSlash(secretPath)
}));
- const folders = await sqlFindMultipleFolderByEnvPathQuery(tx || db.replicaNode(), formatedQuery);
- return formatedQuery.map(({ envId, secretPath }) =>
- folders.find(({ path: targetPath, envId: targetEnvId }) => targetPath === secretPath && targetEnvId === envId)
- );
+
+ const uniqueEnvIds = unique(formatedQuery, (q) => q.envId).map((q) => q.envId);
+
+ // Fetch all folders for these envs in one query
+ const allEnvFolders = await (tx || db.replicaNode())(TableName.SecretFolder).whereIn("envId", uniqueEnvIds);
+
+ const foldersByEnv = groupBy(allEnvFolders, (f) => f.envId);
+
+ // Build children maps per env
+ const childrenMapByEnv: Record<string, Record<string, TSecretFolders[]>> = {};
+ for (const envId of uniqueEnvIds) {
+ childrenMapByEnv[envId] = buildChildrenMap(foldersByEnv[envId] || []);
+ }
+
+ return formatedQuery.map(({ envId, secretPath }) => {
+ const pathSegments = secretPath.split("/").filter(Boolean);
+ const childrenMap = childrenMapByEnv[envId];
+ if (!childrenMap) return undefined;
+
+ const folder = resolvePathToFolder(childrenMap, pathSegments);
+ if (!folder) return undefined;
+
+ return { ...folder, depth: pathSegments.length + 1, path: secretPath };
+ });
} catch (error) {
throw new DatabaseError({ error, name: "FindByManySecretPath" });
}
@@ -303,23 +212,38 @@ export const secretFolderDALFactory = (db: TDbClient) => {
// that is instances in which for a given folderid find the secret path
const findSecretPathByFolderIds = async (projectId: string, folderIds: string[], tx?: Knex) => {
try {
- const folders = await sqlFindSecretPathByFolderId(tx || db.replicaNode(), projectId, folderIds);
- // travelling all the way from leaf node to root contains real path
- const rootFolders = groupBy(
- folders.filter(({ parentId }) => parentId === null),
- (i) => i.child || i.id // root condition then child and parent will null
- );
- const actualFolders = groupBy(
- folders.filter(({ depth }) => depth === 1),
- (i) => i.id // root condition then child and parent will null
- );
+ const targetFolders = await (tx || db.replicaNode())(TableName.SecretFolder)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .whereIn(`${TableName.SecretFolder}.id`, folderIds)
+ .where(`${TableName.Environment}.projectId`, projectId)
+ .select(
+ selectAllTableCols(TableName.SecretFolder),
+ db.ref("slug").withSchema(TableName.Environment).as("environmentSlug")
+ );
+
+ if (!targetFolders.length) {
+ return folderIds.map(() => undefined);
+ }
+
+ const targetEnvIds = unique(targetFolders, (f) => f.envId).map((f) => f.envId);
+
+ // Fetch all folders in those environments for path building
+ const allEnvFolders = await (tx || db.replicaNode())(TableName.SecretFolder).whereIn("envId", targetEnvIds);
+
+ const idMap = buildFolderIdMap(allEnvFolders);
+
+ // Map environmentSlug by envId from target folders
+ const envSlugMap: Record<string, string> = {};
+ for (const f of targetFolders) {
+ envSlugMap[f.envId] = (f as typeof f & { environmentSlug: string }).environmentSlug;
+ }
return folderIds.map((folderId) => {
- if (!rootFolders[folderId]?.[0]) return;
+ const folder = idMap[folderId];
+ if (!folder) return undefined;
- const actualId = rootFolders[folderId][0].child || rootFolders[folderId][0].id;
- const folder = actualFolders[actualId][0];
- return { ...folder, path: rootFolders[folderId]?.[0].path };
+ const path = buildFolderPath(folder, idMap);
+ return { ...folder, path, environmentSlug: envSlugMap[folder.envId] };
});
} catch (error) {
throw new DatabaseError({ error, name: "Find by secret path" });
@@ -454,44 +378,61 @@ export const secretFolderDALFactory = (db: TDbClient) => {
tx?: Knex
) => {
try {
- const folders = await (tx || db.replicaNode())
- .withRecursive("parents", (qb) =>
- qb
- .select(
- selectAllTableCols(TableName.SecretFolder),
- db.raw("0 as depth"),
- db.raw(`'/' as path`),
- db.ref(`${TableName.Environment}.slug`).as("environment")
- )
- .from(TableName.SecretFolder)
- .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
- .whereIn(`${TableName.SecretFolder}.id`, parentIds)
- .union((un) => {
- void un
- .select(
- selectAllTableCols(TableName.SecretFolder),
- db.raw("parents.depth + 1 as depth"),
- db.raw(
- `CONCAT(
- CASE WHEN parents.path = '/' THEN '' ELSE parents.path END,
- CASE WHEN ${TableName.SecretFolder}."parentId" is NULL THEN '' ELSE CONCAT('/', secret_folders.name) END
- )`
- ),
- db.ref("parents.environment")
- )
- .from(TableName.SecretFolder)
- .where(`${TableName.SecretFolder}.isReserved`, false)
- .join("parents", `${TableName.SecretFolder}.parentId`, "parents.id");
- })
- )
- .select<(TSecretFolders & { path: string; depth: number; environment: string })[]>("*")
- .from("parents")
- .orderBy("depth")
- .orderByRaw(`"parents".?? COLLATE "en-x-icu" ${orderDirection === OrderByDirection.ASC ? "ASC" : "DESC"}`, [
- orderBy
- ]);
+ const parentFolders = await (tx || db.replicaNode())(TableName.SecretFolder)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .whereIn(`${TableName.SecretFolder}.id`, parentIds)
+ .select(
+ selectAllTableCols(TableName.SecretFolder),
+ db.ref("slug").withSchema(TableName.Environment).as("environment")
+ );
- return folders;
+ if (!parentFolders.length) return [];
+
+ const envIds = unique(parentFolders, (f) => f.envId).map((f) => f.envId);
+
+ const allFolders = await (tx || db.replicaNode())(TableName.SecretFolder)
+ .whereIn("envId", envIds)
+ .where("isReserved", false);
+
+ const envSlugMap: Record<string, string> = {};
+ for (const pf of parentFolders) {
+ envSlugMap[pf.envId] = (pf as typeof pf & { environment: string }).environment;
+ }
+
+ // Include parent folders themselves
+ const allFoldersIncludingParents = [
+ ...allFolders,
+ ...parentFolders.filter((pf) => !allFolders.some((f) => f.id === pf.id))
+ ];
+
+ const childrenMap = buildChildrenMap(allFoldersIncludingParents);
+
+ const results: (TSecretFolders & { path: string; depth: number; environment: string })[] = [];
+ const parentIdSet = new Set(parentIds);
+
+ const traverse = (folder: TSecretFolders, currentPath: string, depth: number, environment: string) => {
+ results.push({ ...folder, path: currentPath, depth, environment });
+ const children = childrenMap[folder.id] || [];
+ for (const child of children) {
+ if (child.isReserved) continue;
+ const childPath = currentPath === "/" ? `/${child.name}` : `${currentPath}/${child.name}`;
+ traverse(child, childPath, depth + 1, environment);
+ }
+ };
+
+ for (const parent of parentFolders) {
+ traverse(parent, "/", 0, envSlugMap[parent.envId]);
+ }
+
+ results.sort((a, b) => {
+ if (a.depth !== b.depth) return a.depth - b.depth;
+ const nameA = a[orderBy as keyof TSecretFolders] as string;
+ const nameB = b[orderBy as keyof TSecretFolders] as string;
+ const cmp = nameA.localeCompare(nameB, "en");
+ return orderDirection === OrderByDirection.ASC ? cmp : -cmp;
+ });
+
+ return results;
} catch (error) {
throw new DatabaseError({ error, name: "FindByEnvsDeep" });
}
@@ -499,44 +440,45 @@ export const secretFolderDALFactory = (db: TDbClient) => {
const findFoldersByRootAndIds = async ({ rootId, folderIds }: { rootId: string; folderIds: string[] }, tx?: Knex) => {
try {
- // First, get all descendant folders of rootId
- const descendants = await (tx || db.replicaNode())
- .withRecursive("descendants", (qb) =>
- qb
- .select(
- selectAllTableCols(TableName.SecretFolder),
- db.raw("0 as depth"),
- db.raw(`'/' as path`),
- db.ref(`${TableName.Environment}.slug`).as("environment")
- )
- .from(TableName.SecretFolder)
- .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
- .where(`${TableName.SecretFolder}.id`, rootId)
- .union((un) => {
- void un
- .select(
- selectAllTableCols(TableName.SecretFolder),
- db.raw("descendants.depth + 1 as depth"),
- db.raw(
- `CONCAT(
- CASE WHEN descendants.path = '/' THEN '' ELSE descendants.path END,
- CASE WHEN ${TableName.SecretFolder}."parentId" is NULL THEN '' ELSE CONCAT('/', secret_folders.name) END
- )`
- ),
- db.ref("descendants.environment")
- )
- .from(TableName.SecretFolder)
- .where(`${TableName.SecretFolder}.isReserved`, false)
- .join("descendants", `${TableName.SecretFolder}.parentId`, "descendants.id");
- })
+ const rootFolder = await (tx || db.replicaNode())(TableName.SecretFolder)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .where(`${TableName.SecretFolder}.id`, rootId)
+ .select(
+ selectAllTableCols(TableName.SecretFolder),
+ db.ref("slug").withSchema(TableName.Environment).as("environment")
)
- .select<(TSecretFolders & { path: string; depth: number; environment: string })[]>("*")
- .from("descendants")
- .whereIn(`id`, folderIds)
- .orderBy("depth")
- .orderBy(`name`);
+ .first();
+
+ if (!rootFolder) return [];
+
+ const allFolders = await (tx || db.replicaNode())(TableName.SecretFolder).where("envId", rootFolder.envId);
+
+ const childrenMap = buildChildrenMap(allFolders);
+ const folderIdSet = new Set(folderIds);
+ const { environment } = rootFolder as typeof rootFolder & { environment: string };
+
+ const results: (TSecretFolders & { path: string; depth: number; environment: string })[] = [];
+
+ const traverse = (folder: TSecretFolders, currentPath: string, depth: number) => {
+ if (folderIdSet.has(folder.id)) {
+ results.push({ ...folder, path: currentPath, depth, environment });
+ }
+ const children = childrenMap[folder.id] || [];
+ for (const child of children) {
+ if (child.isReserved) continue;
+ const childPath = currentPath === "/" ? `/${child.name}` : `${currentPath}/${child.name}`;
+ traverse(child, childPath, depth + 1);
+ }
+ };
+
+ traverse(rootFolder, "/", 0);
+
+ results.sort((a, b) => {
+ if (a.depth !== b.depth) return a.depth - b.depth;
+ return a.name.localeCompare(b.name, "en");
+ });
- return descendants;
+ return results;
} catch (error) {
throw new DatabaseError({ error, name: "FindFoldersByRootAndIds" });
}
diff --git a/backend/src/services/secret-folder/secret-folder-fns.test.ts b/backend/src/services/secret-folder/secret-folder-fns.test.ts
new file mode 100644
index 0000000000..daacd89c4d
--- /dev/null
+++ b/backend/src/services/secret-folder/secret-folder-fns.test.ts
@@ -0,0 +1,332 @@
+import { TSecretFolders } from "@app/db/schemas";
+
+import {
+ buildChildrenMap,
+ buildFolderIdMap,
+ buildFolderPath,
+ resolveClosestFolder,
+ resolvePathToFolder
+} from "./secret-folder-fns";
+
+const makeFolder = (id: string, name: string, parentId: string | null, envId: string = "env-1"): TSecretFolders => ({
+ id,
+ name,
+ parentId,
+ envId,
+ version: 1,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ isReserved: false,
+ description: null,
+ lastSecretModified: null
+});
+
+// Reusable folder tree fixture:
+//
+// root (parentId=null)
+// ├── folder-a
+// │ ├── folder-b
+// │ │ └── folder-c
+// │ └── folder-d
+// └── folder-e
+//
+const root = makeFolder("root-id", "root", null);
+const folderA = makeFolder("a-id", "folder-a", "root-id");
+const folderB = makeFolder("b-id", "folder-b", "a-id");
+const folderC = makeFolder("c-id", "folder-c", "b-id");
+const folderD = makeFolder("d-id", "folder-d", "a-id");
+const folderE = makeFolder("e-id", "folder-e", "root-id");
+
+const allFolders = [root, folderA, folderB, folderC, folderD, folderE];
+
+describe("buildFolderIdMap", () => {
+ test("builds a map keyed by folder id", () => {
+ const map = buildFolderIdMap(allFolders);
+ expect(Object.keys(map)).toHaveLength(6);
+ expect(map["root-id"]).toBe(root);
+ expect(map["a-id"]).toBe(folderA);
+ expect(map["c-id"]).toBe(folderC);
+ });
+
+ test("returns empty map for empty input", () => {
+ const map = buildFolderIdMap([]);
+ expect(Object.keys(map)).toHaveLength(0);
+ });
+});
+
+describe("buildChildrenMap", () => {
+ test("groups folders by parentId", () => {
+ const map = buildChildrenMap(allFolders);
+ // root has parentId=null -> key "null"
+ expect(map.null).toHaveLength(1);
+ expect(map.null[0]).toBe(root);
+
+ // root's children
+ expect(map["root-id"]).toHaveLength(2);
+ expect(map["root-id"].map((f) => f.name).sort()).toEqual(["folder-a", "folder-e"]);
+
+ // folder-a's children
+ expect(map["a-id"]).toHaveLength(2);
+ expect(map["a-id"].map((f) => f.name).sort()).toEqual(["folder-b", "folder-d"]);
+
+ // folder-b has one child
+ expect(map["b-id"]).toHaveLength(1);
+ expect(map["b-id"][0].name).toBe("folder-c");
+
+ // leaf folders have no children entries
+ expect(map["c-id"]).toBeUndefined();
+ expect(map["d-id"]).toBeUndefined();
+ expect(map["e-id"]).toBeUndefined();
+ });
+
+ test("returns map with no entries for empty input", () => {
+ const map = buildChildrenMap([]);
+ expect(Object.keys(map)).toHaveLength(0);
+ });
+});
+
+describe("buildFolderPath", () => {
+ const idMap = buildFolderIdMap(allFolders);
+
+ test("returns '/' for root folder", () => {
+ expect(buildFolderPath(root, idMap)).toBe("/");
+ });
+
+ test("returns correct path for first-level folder", () => {
+ expect(buildFolderPath(folderA, idMap)).toBe("/folder-a");
+ expect(buildFolderPath(folderE, idMap)).toBe("/folder-e");
+ });
+
+ test("returns correct path for deeply nested folder", () => {
+ expect(buildFolderPath(folderC, idMap)).toBe("/folder-a/folder-b/folder-c");
+ });
+
+ test("returns correct path for second-level folder", () => {
+ expect(buildFolderPath(folderB, idMap)).toBe("/folder-a/folder-b");
+ });
+
+ test("returns correct path for sibling folder", () => {
+ expect(buildFolderPath(folderD, idMap)).toBe("/folder-a/folder-d");
+ });
+
+ test("throws when depth exceeds 20", () => {
+ // Create a chain of 22 folders (root + 21 children)
+ const deepFolders: TSecretFolders[] = [makeFolder("deep-0", "root", null)];
+ // eslint-disable-next-line no-plusplus
+ for (let i = 1; i <= 22; i++) {
+ deepFolders.push(makeFolder(`deep-${i}`, `level${i}`, `deep-${i - 1}`));
+ }
+ const deepMap = buildFolderIdMap(deepFolders);
+ const leaf = deepFolders[deepFolders.length - 1];
+
+ expect(() => buildFolderPath(leaf, deepMap)).toThrow("Maximum folder depth of 20 exceeded");
+ });
+});
+
+describe("resolvePathToFolder", () => {
+ const childrenMap = buildChildrenMap(allFolders);
+
+ test("returns root for empty path segments (path '/')", () => {
+ const result = resolvePathToFolder(childrenMap, []);
+ expect(result).toBe(root);
+ });
+
+ test("resolves first-level path", () => {
+ const result = resolvePathToFolder(childrenMap, ["folder-a"]);
+ expect(result).toBe(folderA);
+ });
+
+ test("resolves deeply nested path", () => {
+ const result = resolvePathToFolder(childrenMap, ["folder-a", "folder-b", "folder-c"]);
+ expect(result).toBe(folderC);
+ });
+
+ test("resolves sibling path", () => {
+ const result = resolvePathToFolder(childrenMap, ["folder-a", "folder-d"]);
+ expect(result).toBe(folderD);
+ });
+
+ test("resolves second top-level folder", () => {
+ const result = resolvePathToFolder(childrenMap, ["folder-e"]);
+ expect(result).toBe(folderE);
+ });
+
+ test("returns undefined for nonexistent first segment", () => {
+ const result = resolvePathToFolder(childrenMap, ["nonexistent"]);
+ expect(result).toBeUndefined();
+ });
+
+ test("returns undefined for nonexistent deep segment", () => {
+ const result = resolvePathToFolder(childrenMap, ["folder-a", "nonexistent"]);
+ expect(result).toBeUndefined();
+ });
+
+ test("returns undefined for partially valid path with extra segment", () => {
+ const result = resolvePathToFolder(childrenMap, ["folder-a", "folder-b", "folder-c", "extra"]);
+ expect(result).toBeUndefined();
+ });
+
+ test("returns undefined when no root folder exists", () => {
+ const noRootMap = buildChildrenMap([folderA, folderB]);
+ const result = resolvePathToFolder(noRootMap, []);
+ expect(result).toBeUndefined();
+ });
+
+ test("returns undefined for empty children map", () => {
+ const result = resolvePathToFolder({}, ["folder-a"]);
+ expect(result).toBeUndefined();
+ });
+});
+
+describe("resolveClosestFolder", () => {
+ const childrenMap = buildChildrenMap(allFolders);
+
+ test("returns root for empty path segments (path '/')", () => {
+ const result = resolveClosestFolder(childrenMap, []);
+ expect(result).toBe(root);
+ });
+
+ test("resolves exact match at first level", () => {
+ const result = resolveClosestFolder(childrenMap, ["folder-a"]);
+ expect(result).toBe(folderA);
+ });
+
+ test("resolves exact match at deep level", () => {
+ const result = resolveClosestFolder(childrenMap, ["folder-a", "folder-b", "folder-c"]);
+ expect(result).toBe(folderC);
+ });
+
+ test("returns root when first segment doesn't match", () => {
+ const result = resolveClosestFolder(childrenMap, ["nonexistent"]);
+ expect(result).toBe(root);
+ });
+
+ test("returns deepest matching folder when path partially exists", () => {
+ const result = resolveClosestFolder(childrenMap, ["folder-a", "nonexistent"]);
+ expect(result).toBe(folderA);
+ });
+
+ test("returns deepest matching folder for longer nonexistent path", () => {
+ const result = resolveClosestFolder(childrenMap, ["folder-a", "folder-b", "nonexistent", "deep"]);
+ expect(result).toBe(folderB);
+ });
+
+ test("returns leaf folder even with extra trailing segments", () => {
+ const result = resolveClosestFolder(childrenMap, ["folder-a", "folder-b", "folder-c", "extra"]);
+ expect(result).toBe(folderC);
+ });
+
+ test("returns undefined when no root folder exists", () => {
+ const noRootMap = buildChildrenMap([folderA, folderB]);
+ const result = resolveClosestFolder(noRootMap, ["folder-a"]);
+ expect(result).toBeUndefined();
+ });
+});
+
+describe("multi-environment folder resolution", () => {
+ // Simulate two environments sharing the same folder names but different IDs
+ const env1Root = makeFolder("env1-root", "root", null, "env-1");
+ const env1FolderA = makeFolder("env1-a", "shared-name", "env1-root", "env-1");
+
+ const env2Root = makeFolder("env2-root", "root", null, "env-2");
+ const env2FolderA = makeFolder("env2-a", "shared-name", "env2-root", "env-2");
+
+ test("resolves paths independently per environment", () => {
+ const env1Map = buildChildrenMap([env1Root, env1FolderA]);
+ const env2Map = buildChildrenMap([env2Root, env2FolderA]);
+
+ const result1 = resolvePathToFolder(env1Map, ["shared-name"]);
+ const result2 = resolvePathToFolder(env2Map, ["shared-name"]);
+
+ expect(result1?.id).toBe("env1-a");
+ expect(result2?.id).toBe("env2-a");
+ expect(result1?.id).not.toBe(result2?.id);
+ });
+
+ test("buildFolderPath works per environment", () => {
+ const env1IdMap = buildFolderIdMap([env1Root, env1FolderA]);
+ const env2IdMap = buildFolderIdMap([env2Root, env2FolderA]);
+
+ expect(buildFolderPath(env1FolderA, env1IdMap)).toBe("/shared-name");
+ expect(buildFolderPath(env2FolderA, env2IdMap)).toBe("/shared-name");
+ });
+});
+
+describe("edge cases", () => {
+ test("single root folder with no children", () => {
+ const onlyRoot = makeFolder("only-root", "root", null);
+ const childrenMap = buildChildrenMap([onlyRoot]);
+
+ expect(resolvePathToFolder(childrenMap, [])).toBe(onlyRoot);
+ expect(resolvePathToFolder(childrenMap, ["anything"])).toBeUndefined();
+ expect(resolveClosestFolder(childrenMap, [])).toBe(onlyRoot);
+ expect(resolveClosestFolder(childrenMap, ["anything"])).toBe(onlyRoot);
+ });
+
+ test("deeply nested chain (10 levels)", () => {
+ const folders: TSecretFolders[] = [makeFolder("chain-0", "root", null)];
+ const segments: string[] = [];
+ // eslint-disable-next-line no-plusplus
+ for (let i = 1; i <= 10; i++) {
+ const name = `depth-${i}`;
+ folders.push(makeFolder(`chain-${i}`, name, `chain-${i - 1}`));
+ segments.push(name);
+ }
+
+ const childrenMap = buildChildrenMap(folders);
+ const idMap = buildFolderIdMap(folders);
+
+ // resolvePathToFolder should reach the deepest folder
+ const deepest = resolvePathToFolder(childrenMap, segments);
+ expect(deepest?.id).toBe("chain-10");
+ expect(deepest?.name).toBe("depth-10");
+
+ // buildFolderPath should produce the full path
+ const path = buildFolderPath(folders[10], idMap);
+ expect(path).toBe("/depth-1/depth-2/depth-3/depth-4/depth-5/depth-6/depth-7/depth-8/depth-9/depth-10");
+
+ // Partial path should resolve correctly
+ const partial = resolvePathToFolder(childrenMap, segments.slice(0, 5));
+ expect(partial?.id).toBe("chain-5");
+ });
+
+ test("folders with similar name prefixes", () => {
+ const similarRoot = makeFolder("sim-root", "root", null);
+ const folderProd = makeFolder("sim-prod", "prod", "sim-root");
+ const folderProdDb = makeFolder("sim-prod-db", "prod-db", "sim-root");
+ const folderProduction = makeFolder("sim-production", "production", "sim-root");
+
+ const childrenMap = buildChildrenMap([similarRoot, folderProd, folderProdDb, folderProduction]);
+
+ expect(resolvePathToFolder(childrenMap, ["prod"])?.id).toBe("sim-prod");
+ expect(resolvePathToFolder(childrenMap, ["prod-db"])?.id).toBe("sim-prod-db");
+ expect(resolvePathToFolder(childrenMap, ["production"])?.id).toBe("sim-production");
+ // Exact match required — no prefix matching
+ expect(resolvePathToFolder(childrenMap, ["pro"])).toBeUndefined();
+ });
+
+ test("multiple root folders — picks the first one with parentId=null", () => {
+ const firstRoot = makeFolder("first-root", "root", null);
+ const secondRoot = makeFolder("second-root", "also-root", null);
+ const child = makeFolder("child-of-first", "child", "first-root");
+
+ const childrenMap = buildChildrenMap([firstRoot, secondRoot, child]);
+
+ // First entry in the null key wins — doesn't depend on name
+ expect(resolvePathToFolder(childrenMap, [])?.id).toBe("first-root");
+ expect(resolvePathToFolder(childrenMap, ["child"])?.id).toBe("child-of-first");
+ });
+
+ test("root folder does not need to be named 'root'", () => {
+ const customRoot = makeFolder("custom-root", "my-custom-root-name", null);
+ const child = makeFolder("child-1", "folder-a", "custom-root");
+
+ const childrenMap = buildChildrenMap([customRoot, child]);
+
+ expect(resolvePathToFolder(childrenMap, [])?.id).toBe("custom-root");
+ expect(resolvePathToFolder(childrenMap, ["folder-a"])?.id).toBe("child-1");
+ expect(resolveClosestFolder(childrenMap, [])?.id).toBe("custom-root");
+ expect(resolveClosestFolder(childrenMap, ["folder-a"])?.id).toBe("child-1");
+ expect(resolveClosestFolder(childrenMap, ["nonexistent"])?.id).toBe("custom-root");
+ });
+});
diff --git a/backend/src/services/secret-folder/secret-folder-fns.ts b/backend/src/services/secret-folder/secret-folder-fns.ts
index a3783a1b9d..a92510c301 100644
--- a/backend/src/services/secret-folder/secret-folder-fns.ts
+++ b/backend/src/services/secret-folder/secret-folder-fns.ts
@@ -15,3 +15,63 @@ export const buildFolderPath = (
return `${buildFolderPath(foldersMap[folder.parentId], foldersMap, depth + 1)}/${folder.name}`;
};
+
+export const buildFolderIdMap = (folders: TSecretFolders[]): Record<string, TSecretFolders> => {
+ const map: Record<string, TSecretFolders> = {};
+ for (const folder of folders) {
+ map[folder.id] = folder;
+ }
+ return map;
+};
+
+export const buildChildrenMap = (folders: TSecretFolders[]): Record<string, TSecretFolders[]> => {
+ const map: Record<string, TSecretFolders[]> = {};
+ for (const folder of folders) {
+ const key = folder.parentId || "null";
+ if (!map[key]) {
+ map[key] = [];
+ }
+ map[key].push(folder);
+ }
+ return map;
+};
+
+export const resolvePathToFolder = (
+ childrenMap: Record<string, TSecretFolders[]>,
+ pathSegments: string[]
+): TSecretFolders | undefined => {
+ const roots = childrenMap.null || [];
+ const root = roots[0];
+ if (!root) return undefined;
+
+ if (pathSegments.length === 0) return root;
+
+ let current = root;
+ for (const segment of pathSegments) {
+ const children = childrenMap[current.id] || [];
+ const next = children.find((f) => f.name === segment);
+ if (!next) return undefined;
+ current = next;
+ }
+ return current;
+};
+
+export const resolveClosestFolder = (
+ childrenMap: Record<string, TSecretFolders[]>,
+ pathSegments: string[]
+): TSecretFolders | undefined => {
+ const roots = childrenMap.null || [];
+ const root = roots[0];
+ if (!root) return undefined;
+
+ if (pathSegments.length === 0) return root;
+
+ let current = root;
+ for (const segment of pathSegments) {
+ const children = childrenMap[current.id] || [];
+ const next = children.find((f) => f.name === segment);
+ if (!next) return current;
+ current = next;
+ }
+ return current;
+};