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: secret reference dependency tracking
Daniel Hougaardc96a3223a2e1
diff --git a/backend/src/server/routes/v4/secret-router.ts b/backend/src/server/routes/v4/secret-router.tsindex 33fe070001..34c4f167fa 100644--- a/backend/src/server/routes/v4/secret-router.ts+++ b/backend/src/server/routes/v4/secret-router.ts@@ -1259,7 +1259,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {server.route({method: "GET",- url: "/:secretName/secret-references",+ url: "/:secretName/reference-dependency-tree",config: {rateLimit: secretsLimit},@@ -1267,7 +1267,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {hide: false,operationId: "getSecretReferencesV4",tags: [ApiDocsTags.Secrets],- description: "Get secret references",+ description: "Get secret reference dependency tree",security: [{bearerAuth: []@@ -1288,16 +1288,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {}),response: {200: z.object({- references: z.array(- z.object({- secretKey: z.string(),- secretId: z.string(),- environment: z.string(),- secretPath: z.string(),- referenceType: z.string()- })- ),- totalCount: z.number()+ tree: SecretReferenceNodeTree})}},@@ -1305,7 +1296,8 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {handler: async (req) => {const { secretName } = req.params;const { secretPath, environment, projectId } = req.query;- const { references, totalCount } = await server.services.secret.getSecretReferences({++ const { tree } = await server.services.secret.getSecretReferenceDependencyTree({actorId: req.permission.id,actor: req.permission.type,actorAuthMethod: req.permission.authMethod,@@ -1315,7 +1307,8 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {secretPath,environment});- return { references, totalCount };++ return { tree };}});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 dc19b4378e..5365b49250 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@@ -3244,7 +3244,7 @@ export const secretV2BridgeServiceFactory = ({return { tree: stackTrace, value: expandedValue, secret };};- const getSecretReferences = async ({+ const getSecretReferenceDependencyTree = async ({projectId,secretName,environment,@@ -3293,96 +3293,142 @@ export const secretV2BridgeServiceFactory = ({projectId});- const nestedSecretReferences = await secretDAL.findReferencedSecretReferencesBySecretKey(- projectId,- environment,- secretPath,- secretName- );+ const findSecretsReferencingSecret = async (env: string, path: string, key: string) => {+ const secretFolder = await folderDAL.findBySecretPath(projectId, env, path);+ if (!secretFolder) return [];- const nestedSecretIds = nestedSecretReferences.map((ref) => ref.secretId);- const nestedSecrets =- nestedSecretIds.length > 0- ? await secretDAL.find({ $in: { [`${TableName.SecretV2}.id` as "id"]: nestedSecretIds } })- : [];+ const targetSecret = await secretDAL.findOne({+ folderId: secretFolder.id,+ key,+ type: SecretType.Shared+ });- const nestedFolderIds = [...new Set(nestedSecrets.map((s) => s.folderId))];- const folderPaths =- nestedFolderIds.length > 0 ? await folderDAL.findSecretPathByFolderIds(projectId, nestedFolderIds) : [];- const folderPathMap = new Map(folderPaths.filter(Boolean).map((fp) => [fp!.id, fp]));+ if (!targetSecret) return [];- const secretsInSameFolder = await secretDAL.find({- folderId: folder.id,- $notEqual: { [`${TableName.SecretV2}.id` as "id"]: secret.id }- });+ const nestedSecretReferences = await secretDAL.findReferencedSecretReferencesBySecretKey(+ projectId,+ env,+ path,+ key+ );- const localReferencingSecrets = secretsInSameFolder.filter((s) => {- if (!s.encryptedValue) return false;- const decryptedValue = secretManagerDecryptor({ cipherTextBlob: s.encryptedValue }).toString();- const { localReferences } = getAllSecretReferences(decryptedValue);- return localReferences.includes(secretName);- });+ const nestedSecretIds = nestedSecretReferences.map((ref) => ref.secretId);+ const nestedSecrets =+ nestedSecretIds.length > 0+ ? await secretDAL.find({ $in: { [`${TableName.SecretV2}.id` as "id"]: nestedSecretIds } })+ : [];++ const nestedFolderIds = [...new Set(nestedSecrets.map((s) => s.folderId))];+ const nestedFolderPaths =+ nestedFolderIds.length > 0 ? await folderDAL.findSecretPathByFolderIds(projectId, nestedFolderIds) : [];+ const nestedFolderPathMap = new Map(nestedFolderPaths.filter(Boolean).map((fp) => [fp!.id, fp]));++ const secretsInSameFolder = await secretDAL.find({+ folderId: secretFolder.id,+ $notEqual: { [`${TableName.SecretV2}.id` as "id"]: targetSecret.id }+ });++ const localReferencingSecrets = secretsInSameFolder.filter((s) => {+ if (!s.encryptedValue) return false;+ const decryptedValue = secretManagerDecryptor({ cipherTextBlob: s.encryptedValue }).toString();+ const { localReferences } = getAllSecretReferences(decryptedValue);+ return localReferences.includes(key);+ });++ const results: Array<{+ key: string;+ environment: string;+ secretPath: string;+ tags: Array<{ slug: string }>;+ }> = [];++ for (const nestedSecret of nestedSecrets) {+ const folderPath = nestedFolderPathMap.get(nestedSecret.folderId);+ if (folderPath) {+ results.push({+ key: nestedSecret.key,+ environment: folderPath.environmentSlug,+ secretPath: folderPath.path,+ tags: nestedSecret.tags || []+ });+ }+ }- const totalCount = nestedSecrets.length + localReferencingSecrets.length;+ for (const localSecret of localReferencingSecrets) {+ results.push({+ key: localSecret.key,+ environment: env,+ secretPath: path,+ tags: localSecret.tags || []+ });+ }- const referencingSecrets: {- secretKey: string;- secretId: string;+ return results;+ };++ const createSecretId = (env: string, path: string, key: string) => `${env}:${path}:${key}`;+ const visitedSecrets = new Set<string>();+ const MAX_DEPTH = 10;++ type DependencyNode = {+ key: string;environment: string;secretPath: string;- referenceType: "nested" | "local";- }[] = [];+ children: DependencyNode[];+ };- for (const nestedSecret of nestedSecrets) {- const folderPath = folderPathMap.get(nestedSecret.folderId);- if (folderPath) {+ const buildDependencyTree = async (+ env: string,+ path: string,+ key: string,+ depth: number+ ): Promise<DependencyNode> => {+ const node: DependencyNode = {+ key,+ environment: env,+ secretPath: path,+ children: []+ };++ const secretId = createSecretId(env, path, key);++ if (visitedSecrets.has(secretId) || depth >= MAX_DEPTH) {+ return node;+ }++ visitedSecrets.add(secretId);++ const referencingSecrets = await findSecretsReferencingSecret(env, path, key);++ for await (const refSecret of referencingSecrets) {const hasAccess = hasSecretReadValueOrDescribePermission(permission,ProjectPermissionSecretActions.DescribeSecret,{- environment: folderPath.environmentSlug,- secretPath: folderPath.path,- secretName: nestedSecret.key,- secretTags: (nestedSecret.tags || []).map((t) => t.slug)+ environment: refSecret.environment,+ secretPath: refSecret.secretPath,+ secretName: refSecret.key,+ secretTags: refSecret.tags.map((t) => t.slug)});if (hasAccess) {- referencingSecrets.push({- secretKey: nestedSecret.key,- secretId: nestedSecret.id,- environment: folderPath.environmentSlug,- secretPath: folderPath.path,- referenceType: "nested"- });+ const childNode = await buildDependencyTree(+ refSecret.environment,+ refSecret.secretPath,+ refSecret.key,+ depth + 1+ );+ node.children.push(childNode);}}- }- for (const localSecret of localReferencingSecrets) {- const hasAccess = hasSecretReadValueOrDescribePermission(- permission,- ProjectPermissionSecretActions.DescribeSecret,- {- environment,- secretPath,- secretName: localSecret.key,- secretTags: (localSecret.tags || []).map((t) => t.slug)- }- );+ return node;+ };- if (hasAccess) {- referencingSecrets.push({- secretKey: localSecret.key,- secretId: localSecret.id,- environment,- secretPath,- referenceType: "local"- });- }- }+ const tree = await buildDependencyTree(environment, secretPath, secretName, 0);- return { references: referencingSecrets, totalCount };+ return { tree };};const getAccessibleSecrets = async ({@@ -3608,7 +3654,7 @@ export const secretV2BridgeServiceFactory = ({getSecretsCountMultiEnv,getSecretsMultiEnv,getSecretReferenceTree,- getSecretReferences,+ getSecretReferenceDependencyTree,getSecretsByFolderMappings,getSecretById,getAccessibleSecrets,diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.tsindex 5d32263986..3a9a319443 100644--- a/backend/src/services/secret/secret-service.ts+++ b/backend/src/services/secret/secret-service.ts@@ -1262,7 +1262,7 @@ export const secretServiceFactory = ({return secretV2BridgeService.getSecretReferenceTree(dto);};- const getSecretReferences = async (dto: TGetSecretReferencesDTO) => {+ const getSecretReferenceDependencyTree = async (dto: TGetSecretReferencesDTO) => {const { shouldUseSecretV2Bridge } = await projectBotService.getBotKey(dto.projectId);if (!shouldUseSecretV2Bridge) {@@ -1272,7 +1272,7 @@ export const secretServiceFactory = ({});}- return secretV2BridgeService.getSecretReferences(dto);+ return secretV2BridgeService.getSecretReferenceDependencyTree(dto);};const getSecretAccessList = async (dto: TGetSecretAccessListDTO) => {@@ -3552,6 +3552,6 @@ export const secretServiceFactory = ({getAccessibleSecrets,getSecretVersionsV2ByIds,getChangeVersions,- getSecretReferences+ getSecretReferenceDependencyTree};};diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex cfc746b149..146bb491a4 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -84,6 +84,7 @@"qrcode": "^1.5.4","react": "^18.3.1","react-code-input": "^3.10.1",+ "react-complex-tree": "^2.6.1","react-day-picker": "^9.4.3","react-dom": "^18.3.1","react-helmet": "^6.1.0",@@ -13643,6 +13644,18 @@"object-assign": "^4.1.1"}},+ "node_modules/react-complex-tree": {+ "version": "2.6.1",+ "resolved": "https://registry.npmjs.org/react-complex-tree/-/react-complex-tree-2.6.1.tgz",+ "integrity": "sha512-RZubW4lh086/R38bbNKpkRpLWG+PdEMBIvYvSUelYNJfv/xaAboRKguWN8hfBvoV9O4NSi6jcMv/AcCm2PbJRg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/lukasbach"+ },+ "peerDependencies": {+ "react": ">=16.0.0"+ }+ },"node_modules/react-day-picker": {"version": "9.4.3","resolved": "https://registry.npmjs.org/react-day-picker/-/react-day-picker-9.4.3.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 02d6d26db5..55dd1e2429 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -93,6 +93,7 @@"qrcode": "^1.5.4","react": "^18.3.1","react-code-input": "^3.10.1",+ "react-complex-tree": "^2.6.1","react-day-picker": "^9.4.3","react-dom": "^18.3.1","react-helmet": "^6.1.0",diff --git a/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceDetails.module.css b/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceDetails.module.cssdeleted file mode 100644index 00ca0b770f..0000000000--- a/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceDetails.module.css+++ /dev/null@@ -1,133 +0,0 @@-/* credits: https://iamkate.com/code/tree-views/ */-.tree {- --spacing: 1.5rem;- --radius: 4px;-}--.tree li {- display: block;- position: relative;- padding-left: calc(2 * var(--spacing) - var(--radius) - 2px);-}--.tree ul {- margin-left: calc(var(--radius) - var(--spacing));- padding-left: 0;-}--.tree ul li {- border-left: 2px solid #888;- min-height: 2.5rem;-}--.tree ul li:last-child {- border-color: transparent;-}--.tree ul li::before {- content: "";- display: block;- position: absolute;- top: calc(var(--spacing) / -1);- left: -2px;- width: calc(var(--spacing) + 2px);- height: calc(var(--spacing) + 13px);- border: solid #888;- border-radius: 0 0 0 8px;- border-width: 0 0 2px 2px;- transition: all 200ms linear;-}--.details[open] summary ~ * {- animation: sweep 0.5s ease-in-out;-}--@keyframes sweep {- 0% {- opacity: 0;- margin-left: -10px;- }- 100% {- opacity: 1;- margin-left: 0px;- }-}--.tree summary {- display: block;- cursor: pointer;- min-height: 2.5rem;-}--.tree summary::marker,-.tree summary::-webkit-details-marker {- display: none;-}--.tree summary:focus {- outline: none;-}--.tree summary:focus-visible {- outline: 1px dotted #000;-}--.tree li::after,-.tree summary::before {- content: "";- display: block;- position: absolute;- top: calc(var(--spacing) / 2 - var(--radius));- left: calc(var(--spacing) - var(--radius) - 1px);- width: calc(2 * var(--radius));- height: calc(2 * var(--radius));- border-radius: 50%;- background: #ddd;-}--.tree summary::before {- z-index: 1;- background: #ddd 0 0;-}--.tree details[open] > summary::before {- background-position: calc(-2 * var(--radius)) 0;-}--.collapsibleContent {- /*overflow-y: hidden;*/-}-.collapsibleContent[data-state="open"] {- animation: slideDown 300ms ease-out;-}-.collapsibleContent[data-state="closed"] {- animation: slideUp 300ms ease-out;-}--@keyframes slideDown {- 0% {- height: 0;- opacity: 0;- }- 50% {- opacity: 0;- }- 100% {- height: var(--radix-collapsible-content-height);- opacity: 1;- }-}--@keyframes slideUp {- 0% {- height: var(--radix-collapsible-content-height);- opacity: 1;- }- 50% {- opacity: 0;- }- 100% {- height: 0;- opacity: 0;- }-}diff --git a/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceDetails.tsx b/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceDetails.tsxindex 0b6daf8895..8a452da469 100644--- a/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceDetails.tsx+++ b/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceDetails.tsx@@ -1,23 +1,32 @@-/* eslint-disable no-nested-ternary */-import { useEffect, useState } from "react";+import { useEffect, useMemo } from "react";+import {+ StaticTreeDataProvider,+ Tree,+ TreeItem,+ TreeItemIndex,+ UncontrolledTreeEnvironment+} from "react-complex-tree";import {- faChevronRight,faExclamationTriangle,faEye,- faEyeSlash+ faEyeSlash,+ faProjectDiagram} from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import * as Collapsible from "@radix-ui/react-collapsible";import { AxiosError } from "axios";-import { twMerge } from "tailwind-merge";import { createNotification } from "@app/components/notifications";import { FormControl, FormLabel, SecretInput, Spinner, Tooltip } from "@app/components/v2";import { useProject } from "@app/context";-import { useGetSecretReferenceTree } from "@app/hooks/api";-import { ApiErrorTypes, TApiErrors, TSecretReferenceTraceNode } from "@app/hooks/api/types";+import { useGetSecretReferences, useGetSecretReferenceTree } from "@app/hooks/api";+import {+ ApiErrorTypes,+ TApiErrors,+ TSecretDependencyTreeNode,+ TSecretReferenceTraceNode+} from "@app/hooks/api/types";-import style from "./SecretReferenceDetails.module.css";+import "./SecretReferenceTree.css";type Props = {environment: string;@@ -29,103 +38,395 @@ const INTERPOLATION_SYNTAX_REG = /\${([^}]+)}/;export const hasSecretReference = (value: string | undefined) =>value ? INTERPOLATION_SYNTAX_REG.test(value) : false;-const createNodeId = (node: TSecretReferenceTraceNode): string =>- `${node.environment}:${node.secretPath}:${node.key}`;+type TreeNodeData = {+ title: string;+ value?: string;+ rootValue?: string;+ isRoot?: boolean;+ isNested?: boolean;+};++const createNodeId = (node: TSecretReferenceTraceNode, parentId?: string): string => {+ const baseId = `${node.environment}:${node.secretPath}:${node.key}`;+ return parentId ? `${parentId}>${baseId}` : baseId;+};-const isCircularReference = (+// Convert TSecretReferenceTraceNode to react-complex-tree format+const convertToTreeItems = (node: TSecretReferenceTraceNode,- visitedPath: Set<string>-): boolean => {- const nodeId = createNodeId(node);- return visitedPath.has(nodeId);+ secretKey: string,+ visitedPath: Set<string> = new Set(),+ parentId?: string+): Record<TreeItemIndex, TreeItem<TreeNodeData>> => {+ const items: Record<TreeItemIndex, TreeItem<TreeNodeData>> = {};+ const nodeId = createNodeId(node, parentId);++ // Check for circular reference+ const circularKey = `${node.environment}:${node.secretPath}:${node.key}`;+ const isCircular = visitedPath.has(circularKey);+ const newVisitedPath = new Set([...visitedPath, circularKey]);++ const displayName = parentId+ ? `${node.environment}${node.secretPath === "/" ? "" : node.secretPath.split("/").join(".")}.${node.key}`+ : secretKey;++ const childIds: TreeItemIndex[] = [];++ if (!isCircular) {+ node.children.forEach((child) => {+ const childId = createNodeId(child, nodeId);+ childIds.push(childId);+ const childItems = convertToTreeItems(child, secretKey, newVisitedPath, nodeId);+ Object.assign(items, childItems);+ });+ }++ items[nodeId] = {+ index: nodeId,+ isFolder: childIds.length > 0,+ children: childIds,+ data: {+ title: displayName,+ value: node.value,+ isRoot: !parentId+ }+ };++ // Add a hidden root container that has this node as its only child+ if (!parentId) {+ items.root = {+ index: "root",+ isFolder: true,+ children: [nodeId],+ data: { title: "root", isRoot: false }+ };+ }++ return items;+};++// Invert the dependency tree so leaf nodes become roots+// This transforms "A is referenced by B is referenced by C" into "C → B → A"+// which reads as "C references B which references A"+const invertDependencyTree = (tree: TSecretDependencyTreeNode): TSecretDependencyTreeNode[] => {+ // Collect all paths from root to leaves+ const paths: TSecretDependencyTreeNode[][] = [];++ const collectPaths = (+ node: TSecretDependencyTreeNode,+ currentPath: TSecretDependencyTreeNode[],+ visited: Set<string>+ ) => {+ const nodeKey = `${node.environment}:${node.secretPath}:${node.key}`;+ if (visited.has(nodeKey)) return;++ const newPath = [...currentPath, node];+ const newVisited = new Set([...visited, nodeKey]);++ if (node.children.length === 0) {+ // Leaf node - save this path+ paths.push(newPath);+ } else {+ // Continue traversing+ node.children.forEach((child) => collectPaths(child, newPath, newVisited));+ }+ };++ collectPaths(tree, [], new Set());++ // If no paths (only root with no children), return empty+ if (paths.length === 0) return [];++ // Build inverted trees from paths+ // Each path becomes a chain: leaf → ... → root+ const invertedRoots: Map<string, TSecretDependencyTreeNode> = new Map();++ paths.forEach((path) => {+ // Reverse the path so leaf is first, root is last+ const reversed = [...path].reverse();++ // Build the chain+ let currentNode: TSecretDependencyTreeNode | null = null;++ reversed.forEach((node, idx) => {+ const nodeKey = `${node.environment}:${node.secretPath}:${node.key}`;+ const isLeaf = idx === 0;++ if (isLeaf) {+ // Check if we already have this leaf as a root+ if (invertedRoots.has(nodeKey)) {+ currentNode = invertedRoots.get(nodeKey)!;+ } else {+ currentNode = {+ key: node.key,+ environment: node.environment,+ secretPath: node.secretPath,+ children: []+ };+ invertedRoots.set(nodeKey, currentNode);+ }+ } else if (currentNode) {+ // Check if this node already exists as a child+ const existingChild = currentNode.children.find(+ (c) =>+ c.key === node.key &&+ c.environment === node.environment &&+ c.secretPath === node.secretPath+ );++ if (existingChild) {+ currentNode = existingChild;+ } else {+ const newNode: TSecretDependencyTreeNode = {+ key: node.key,+ environment: node.environment,+ secretPath: node.secretPath,+ children: []+ };+ currentNode.children.push(newNode);+ currentNode = newNode;+ }+ }+ });+ });++ return Array.from(invertedRoots.values());+};++// Convert dependency tree from API to react-complex-tree format+// The tree is inverted so that leaf nodes (top-level dependents) are shown first+const convertDependencyTreeToItems = (+ tree: TSecretDependencyTreeNode,+ rootSecretKey: string+): { items: Record<TreeItemIndex, TreeItem<TreeNodeData>>; topLevelIds: string[] } => {+ const items: Record<TreeItemIndex, TreeItem<TreeNodeData>> = {};++ // Invert the tree so dependencies flow naturally (top → bottom)+ const invertedRoots = invertDependencyTree(tree);++ // If no dependents, return empty+ if (invertedRoots.length === 0) {+ return { items: {}, topLevelIds: [] };+ }++ const processNode = (+ node: TSecretDependencyTreeNode,+ parentId: string | undefined,+ depth: number,+ visited: Set<string>+ ): string => {+ const nodeKey = `${node.environment}:${node.secretPath}:${node.key}`;+ const nodeId = parentId ? `${parentId}>${nodeKey}` : nodeKey;++ // Check for circular reference+ if (visited.has(nodeKey)) {+ return nodeId;+ }+ const newVisited = new Set([...visited, nodeKey]);++ // Check if this is the original root secret (the one being viewed)+ const isOriginalRoot = node.key === rootSecretKey && depth > 0;+ const displayName = `${node.environment}${node.secretPath === "/" ? "" : node.secretPath.split("/").join(".")}.${node.key}`;++ const childIds: string[] = [];+ node.children.forEach((child) => {+ const childId = processNode(child, nodeId, depth + 1, newVisited);+ childIds.push(childId);+ });++ items[nodeId] = {+ index: nodeId,+ isFolder: childIds.length > 0,+ children: childIds,+ data: {+ title: displayName,+ isRoot: isOriginalRoot,+ isNested: depth > 0+ }+ };++ return nodeId;+ };++ const topLevelIds: string[] = [];+ invertedRoots.forEach((root) => {+ const rootId = processNode(root, undefined, 0, new Set());+ topLevelIds.push(rootId);+ });++ // Add hidden root container+ items.root = {+ index: "root",+ isFolder: true,+ children: topLevelIds,+ data: { title: "root", isRoot: false }+ };++ return { items, topLevelIds };};const hasCircularReferences = (node: TSecretReferenceTraceNode,visitedPath: Set<string> = new Set()): boolean => {- const nodeId = createNodeId(node);+ const nodeId = `${node.environment}:${node.secretPath}:${node.key}`;if (visitedPath.has(nodeId)) {return true;}const newVisitedPath = new Set([...visitedPath, nodeId]);-return node.children.some((child) => hasCircularReferences(child, newVisitedPath));};-export const SecretReferenceNode = ({- node,- isRoot,- secretKey,- visitedPath = new Set()+// Custom tree item renderer+const renderItemTitle = ({+ item,+ isDependency}: {- node: TSecretReferenceTraceNode;- isRoot?: boolean;- secretKey?: string;- visitedPath?: Set<string>;+ item: TreeItem<TreeNodeData>;+ isDependency?: boolean;+}) => {+ const { title, value, isRoot } = item.data;++ return (+ <span className="flex items-center gap-1">+ <span className={isRoot ? "font-medium" : ""}>{title}</span>+ {!isDependency && (+ <Tooltip className="max-w-md break-words" content={value || "No value"}>+ <span className={`px-1 text-xs ${value ? "text-mineshaft-400" : "text-red-400"}`}>+ <FontAwesomeIcon icon={value ? faEye : faEyeSlash} size="sm" />+ </span>+ </Tooltip>+ )}+ </span>+ );+};++const SecretTree = ({+ isDependency,+ items,+ rootId,+ treeId,+ defaultExpandedIds = []+}: {+ isDependency?: boolean;+ items: Record<TreeItemIndex, TreeItem<TreeNodeData>>;+ rootId: string;+ treeId: string;+ defaultExpandedIds?: string[];}) => {- const [isOpen, setIsOpen] = useState(false);+ const dataProvider = useMemo(+ () =>+ new StaticTreeDataProvider(items, (item, newName) => ({+ ...item,+ data: { ...item.data, title: newName }+ })),+ [items]+ );++ return (+ <UncontrolledTreeEnvironment+ dataProvider={dataProvider}+ getItemTitle={(item) => item.data.title}+ viewState={{+ [treeId]: {+ expandedItems: defaultExpandedIds+ }+ }}+ canDragAndDrop={false}+ canDropOnFolder={false}+ canReorderItems={false}+ renderItemTitle={(props) => renderItemTitle({ ...props, isDependency })}+ >+ <Tree treeId={treeId} rootItem={rootId} />+ </UncontrolledTreeEnvironment>+ );+};++const SecretDependencyTree = ({ secretPath, environment, secretKey }: Props) => {+ const { currentProject } = useProject();+ const projectId = currentProject?.id || "";++ const { data, isPending, isError, error } = useGetSecretReferences(+ {+ secretPath,+ environment,+ projectId,+ secretKey+ },+ { enabled: Boolean(projectId && environment && secretPath && secretKey) }+ );- const nodeId = createNodeId(node);- const isCircular = !isRoot && isCircularReference(node, visitedPath);+ const tree = data?.tree;- const newVisitedPath = isCircular ? visitedPath : new Set([...visitedPath, nodeId]);+ const treeItems = useMemo(() => {+ if (!tree) return { items: {}, rootId: "", topLevelIds: [] };+ const { items, topLevelIds } = convertDependencyTreeToItems(tree, secretKey);+ return { items, rootId: "root", topLevelIds };+ }, [tree, secretKey]);- const safeChildren = isCircular- ? []- : node.children.filter((child) => !isCircularReference(child, newVisitedPath));- const hasChildren = safeChildren.length > 0;+ useEffect(() => {+ if (error instanceof AxiosError) {+ const err = error?.response?.data as TApiErrors;++ if (err?.error === ApiErrorTypes.CustomForbiddenError) {+ createNotification({+ title: "You don't have permission to view dependency tree",+ text: "You don't have permission to view one or more of the dependent secrets.",+ type: "error"+ });+ return;+ }+ createNotification({+ title: "Error fetching secret dependency tree",+ text: "Please try again later.",+ type: "error"+ });+ }+ }, [error]);++ if (isPending) {+ return (+ <div className="flex items-center justify-center py-4">+ <Spinner className="text-mineshaft-400" />+ </div>+ );+ }++ const hasDependencies = tree && tree.children?.length > 0;++ if (!hasDependencies) {+ return (+ <div className="flex items-center justify-center py-4">+ <span className="text-mineshaft-400">No secrets reference this secret</span>+ </div>+ );+ }return (- <li>- <Collapsible.Root open={isOpen} className="" onOpenChange={setIsOpen}>- <Collapsible.Trigger- className={twMerge(- hasChildren && "decoration-bunker-4ø00 underline-offset-4 data-[state=open]:underline",- "data-[state=open]:[&>svg]:rotate-90 data-[state=open]:[&>svg]:text-yellow-500"- )}- disabled={!hasChildren}- >- {hasChildren && (- <FontAwesomeIcon- icon={faChevronRight}- className="d mr-2 text-mineshaft-400 transition-transform duration-300 ease-linear"- aria-hidden- />- )}- {isRoot- ? secretKey- : `${node.environment}${- node.secretPath === "/" ? "" : node.secretPath.split("/").join(".")- }.${node.key}`}- <Tooltip className="max-w-md break-words" content={node.value}>- <span- className={twMerge(- "ml-1 px-1 text-xs text-mineshaft-400",- !node.value && "text-red-400"- )}- >- <FontAwesomeIcon icon={node.value ? faEye : faEyeSlash} />- </span>- </Tooltip>- </Collapsible.Trigger>- <Collapsible.Content className={twMerge("mt-4", style.collapsibleContent)}>- {hasChildren && (- <ul>- {safeChildren.map((el, index) => (- <SecretReferenceNode- node={el}- key={`${el.key}-${index + 1}`}- visitedPath={newVisitedPath}- />- ))}- </ul>- )}- </Collapsible.Content>- </Collapsible.Root>- </li>+ <div>+ <div className="secret-tree-container relative max-h-96 thin-scrollbar overflow-auto rounded-md border border-mineshaft-600 bg-bunker-700 p-3 text-sm text-mineshaft-200">+ {isError && (+ <div className="flex items-center justify-center py-4">+ <FontAwesomeIcon icon={faExclamationTriangle} className="mr-2 text-red-500" />+ <p className="text-red-500">Error fetching secret dependency tree</p>+ </div>+ )}+ {!isError && treeItems.rootId && (+ <SecretTree+ isDependency+ items={treeItems.items}+ rootId={treeItems.rootId}+ treeId="dependency-tree"+ defaultExpandedIds={treeItems.topLevelIds}+ />+ )}+ </div>+ <div className="mt-2 text-xs text-mineshaft-400">+ Shows secrets that depend on this secret. Each level references the one below it.+ </div>+ </div>);};@@ -143,9 +444,16 @@ export const SecretReferenceTree = ({ secretPath, environment, secretKey }: Propconst tree = data?.tree;const secretValue = data?.value;- // Check if the tree contains circular referencesconst hasCirculars = tree ? hasCircularReferences(tree) : false;+ const treeItems = useMemo(() => {+ if (!tree) return { items: {}, rootId: "", expandId: "" };+ const items = convertToTreeItems(tree, secretKey);+ const actualRootId = createNodeId(tree);+ // Return "root" as rootId since that's the container, and actualRootId for expanding+ return { items, rootId: "root", expandId: actualRootId };+ }, [tree, secretKey]);+useEffect(() => {if (error instanceof AxiosError) {const err = error?.response?.data as TApiErrors;@@ -174,13 +482,7 @@ export const SecretReferenceTree = ({ secretPath, environment, secretKey }: Prop);}- if (tree?.children?.length === 0) {- return (- <div className="flex items-center justify-center py-4">- <span className="text-mineshaft-400">This secret does not contain references</span>- </div>- );- }+ const hasReferences = tree && tree.children?.length > 0;return (<div>@@ -200,22 +502,47 @@ export const SecretReferenceTree = ({ secretPath, environment, secretKey }: PropcontainerClassName="text-bunker-300 hover:border-primary-400/50 border border-mineshaft-600 bg-bunker-700 px-2 py-1.5"/></FormControl>- <FormLabel className="mb-2" label="Reference Tree" />- <div className="relative max-h-96 thin-scrollbar overflow-auto rounded-md border border-mineshaft-600 bg-bunker-700 py-6 text-sm text-mineshaft-200">- {isError ? (++ <FormLabel+ tooltipText="Overview of all secrets across your project that this secret references. Note that you are only able to view the references that you have access to."+ className="mb-2"+ label="Reference Tree"+ />+ <div className="secret-tree-container relative max-h-96 thin-scrollbar overflow-auto rounded-md border border-mineshaft-600 bg-bunker-700 p-3 text-sm text-mineshaft-200">+ {isError && (<div className="flex items-center justify-center py-4"><FontAwesomeIcon icon={faExclamationTriangle} className="mr-2 text-red-500" /><p className="text-red-500">Error fetching secret reference tree</p></div>- ) : tree ? (- <ul className={style.tree}>- <SecretReferenceNode node={tree} isRoot secretKey={secretKey} />- </ul>- ) : null}+ )}+ {!isError && hasReferences && treeItems.rootId && (+ <SecretTree+ items={treeItems.items}+ rootId={treeItems.rootId}+ treeId="reference-tree"+ defaultExpandedIds={[treeItems.expandId]}+ />+ )}+ {!isError && !hasReferences && (+ <div className="flex items-center justify-center py-4">+ <span className="text-mineshaft-400">This secret does not contain references</span>+ </div>+ )}</div>- <div className="mt-2 text-sm text-mineshaft-400">+ <div className="mt-2 text-xs text-mineshaft-400">Click a secret key to view its sub-references.</div>++ <FormLabel+ tooltipText="Overview of all secrets across your project that this secret is referenced by. Note that you are only able to view the references that you have access to."+ className="mt-6 mb-2"+ label="Dependency Tree"+ />+ <SecretDependencyTree+ secretPath={secretPath}+ environment={environment}+ secretKey={secretKey}+ /></div>);};diff --git a/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceTree.css b/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceTree.cssnew file mode 100644index 0000000000..6a63cafd1a--- /dev/null+++ b/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceTree.css@@ -0,0 +1,129 @@+.secret-tree-container .rct-tree-root {+ padding: 0;+ list-style: none;+}++.secret-tree-container .rct-tree-root > li {+ list-style: none;+}++.secret-tree-container ul {+ list-style: none;+ padding: 0;+ margin: 0;+}++.secret-tree-container .rct-tree-item-li {+ list-style: none;+ padding: 0;+ margin: 0;+}++.secret-tree-container .rct-tree-item-title-container {+ display: flex;+ align-items: center;+ padding: 3px 0;+ border-radius: 4px;+ cursor: default;+}++.secret-tree-container .rct-tree-item-title-container-selected,+.secret-tree-container .rct-tree-item-title-container-focused {+ outline: none;+ background-color: transparent;+}++.secret-tree-container .rct-tree-item-arrow {+ width: 16px;+ height: 16px;+ display: flex;+ align-items: center;+ justify-content: center;+ color: #5e6875;+ flex-shrink: 0;+ margin-right: 4px;+}++.secret-tree-container .rct-tree-item-arrow-isFolder {+ cursor: pointer;+}++.secret-tree-container .rct-tree-item-arrow-isFolder:hover {+ color: #9ca3af;+}++/* Top-level items - minimal indentation, no line */+.secret-tree-container .rct-tree-items-container {+ padding-left: 0;+ margin-left: 0;+ border-left: none;+}++/* Nested items - indentation with connector line */+.secret-tree-container .rct-tree-items-container .rct-tree-items-container {+ padding-left: 12px;+ margin-left: 8px;+ border-left: 1px solid #3b3f47;+}++.secret-tree-container .rct-tree-item-button {+ background: none;+ border: none;+ padding: 0;+ margin: 0;+ font: inherit;+ color: inherit;+ cursor: default;+ display: flex;+ align-items: center;+ width: 100%;+ text-align: left;+}++/* Custom arrow using CSS */+.secret-tree-container .rct-tree-item-arrow::before {+ content: "";+ border: solid #5e6875;+ border-width: 0 1.5px 1.5px 0;+ display: inline-block;+ padding: 2.5px;+ transform: rotate(-45deg);+ transition: transform 150ms ease, border-color 150ms ease;+}++.secret-tree-container .rct-tree-item-arrow-expanded::before {+ transform: rotate(45deg);+ border-color: #eab308;+}++.secret-tree-container .rct-tree-item-arrow:not(.rct-tree-item-arrow-isFolder)::before {+ visibility: hidden;+}++/* Remove default SVG arrow */+.secret-tree-container .rct-tree-item-arrow svg {+ display: none;+}++/* Disable drag and drop visuals */+.secret-tree-container .rct-tree-drag-between-line {+ display: none;+}++.secret-tree-container .rct-tree-item-li-dragging-over {+ background: transparent;+}++/* Hide search input */+.secret-tree-container .rct-tree-search-input {+ display: none;+}++/* Focus states - keep minimal */+.secret-tree-container .rct-tree-item-title-container:focus {+ outline: none;+}++.secret-tree-container .rct-tree-item-title-container:focus-visible {+ outline: none;+}diff --git a/frontend/src/hooks/api/secrets/queries.tsx b/frontend/src/hooks/api/secrets/queries.tsxindex 37d2f5a9cd..554ffe2cf4 100644--- a/frontend/src/hooks/api/secrets/queries.tsx+++ b/frontend/src/hooks/api/secrets/queries.tsx@@ -24,7 +24,7 @@ import {TGetSecretReferencesDTO,TGetSecretReferenceTreeDTO,TGetSecretVersionValue,- TSecretReference,+ TSecretDependencyTreeNode,TSecretReferenceTraceNode,TSecretVersionValue} from "./types";@@ -346,16 +346,15 @@ export const useGetSecretReferenceTree = (dto: TGetSecretReferenceTreeDTO) =>});export const fetchSecretReferences = async (dto: TGetSecretReferencesDTO) => {- const { data } = await apiRequest.get<{ references: TSecretReference[]; totalCount: number }>(- `/api/v4/secrets/${encodeURIComponent(dto.secretKey)}/secret-references`,- {- params: {- projectId: dto.projectId,- secretPath: dto.secretPath,- environment: dto.environment- }+ const { data } = await apiRequest.get<{+ tree: TSecretDependencyTreeNode;+ }>(`/api/v4/secrets/${encodeURIComponent(dto.secretKey)}/reference-dependency-tree`, {+ params: {+ projectId: dto.projectId,+ secretPath: dto.secretPath,+ environment: dto.environment}- );+ });return data;};diff --git a/frontend/src/hooks/api/secrets/types.ts b/frontend/src/hooks/api/secrets/types.tsindex d5576e5da9..0fc58d9832 100644--- a/frontend/src/hooks/api/secrets/types.ts+++ b/frontend/src/hooks/api/secrets/types.ts@@ -271,12 +271,11 @@ export type TGetSecretReferencesDTO = {projectId: string;};-export type TSecretReference = {- secretKey: string;- secretId: string;+export type TSecretDependencyTreeNode = {+ key: string;environment: string;secretPath: string;- referenceType: "nested" | "local";+ children: TSecretDependencyTreeNode[];};export type SecretAccessListEntry = {diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/MoveSecretsModal.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/MoveSecretsModal.tsxindex f1d363d602..0d27c05b8d 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/MoveSecretsModal.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/MoveSecretsModal.tsx@@ -94,25 +94,28 @@ export const MoveSecretsModal = ({// aggregate all references and so we can calculate total count including hidden onesconst allReferences = referenceQueries- .filter((refQueries) => refQueries.data)+ .filter((refQueries) => refQueries.data?.tree).flatMap((q, idx) =>- (q.data?.references || []).map((ref) => ({ ...ref, movedSecretKey: secretsToMove[idx].key }))+ (q.data?.tree.children || []).map((child) => ({+ secretKey: child.key,+ environment: child.environment,+ secretPath: child.secretPath,+ movedSecretKey: secretsToMove[idx].key+ }))).filter((ref, index, self) =>index ===self.findIndex(- (r) => r.secretId === ref.secretId && r.movedSecretKey === ref.movedSecretKey+ (r) =>+ r.secretKey === ref.secretKey &&+ r.environment === ref.environment &&+ r.secretPath === ref.secretPath &&+ r.movedSecretKey === ref.movedSecretKey));- const totalReferenceCount = referenceQueries.reduce(- (sum, queryResult) => sum + (queryResult.data?.totalCount || 0),- 0- );- const hiddenReferenceCount = totalReferenceCount - allReferences.length;-- const hasReferences = totalReferenceCount > 0;+ const hasReferences = allReferences.length > 0;const isLoadingReferences = referenceQueries.some((refQueries) => refQueries.isLoading);const handleFormSubmit = (data: TFormSchema) => {@@ -193,7 +196,7 @@ export const MoveSecretsModal = ({<FontAwesomeIcon icon={faWarning} className="h-5 w-5" /></div><p className="text-sm text-yellow-500">- {totalReferenceCount} secret{totalReferenceCount !== 1 ? "s" : ""} will have+ {allReferences.length} secret{allReferences.length !== 1 ? "s" : ""} will havetheir references updated to match the path after the secret has been moved.</p></div>@@ -210,7 +213,9 @@ export const MoveSecretsModal = ({</THead><TBody>{allReferences.map((ref) => (- <Tr key={`${ref.secretId}-${ref.movedSecretKey}`}>+ <Tr+ key={`${ref.secretKey}-${ref.environment}-${ref.secretPath}-${ref.movedSecretKey}`}+ ><Td><FontAwesomeIcon icon={faKey} className="h-4 w-4 text-gray-400" /></Td>@@ -223,12 +228,6 @@ export const MoveSecretsModal = ({</Table></div>)}- {hiddenReferenceCount > 0 && (- <p className="mt-2 text-xs text-mineshaft-400">- + {hiddenReferenceCount} additional secret{hiddenReferenceCount !== 1 ? "s" : ""}{" "}- you don't have access to view- </p>- )}</div>)}<div className="mt-7 flex items-center">diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CommitForm/CommitForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CommitForm/CommitForm.tsxindex 8b28fb884f..bdd7057451 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CommitForm/CommitForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CommitForm/CommitForm.tsx@@ -367,8 +367,9 @@ export const CommitForm: React.FC<CommitFormProps> = ({const map: Record<string, number> = {};secretsBeingRenamed.forEach((secretKey, idx) => {const queryResult = referenceQueries[idx];- if (queryResult?.data) {- map[secretKey] = queryResult.data.totalCount;+ if (queryResult?.data?.tree) {+ // Count direct references from tree children+ map[secretKey] = queryResult.data.tree.children?.length ?? 0;}});return map;diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsxindex 5c4e8ad506..9137572275 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx@@ -875,7 +875,7 @@ export const SecretDetailSidebar = ({leftIcon={<FontAwesomeIcon icon={faProjectDiagram} />}onClick={() => handlePopUpOpen("secretReferenceTree", secretKey)}>- Secret Reference Tree+ Secret References</Button><Tooltip content="Copy Secret ID" className="z-100"><IconButton