Skip to content

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

feat: add a fallback so it is possible list only paths the token has access

adilson78872c27320e
diff --git a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts
index 3c489ffaf1..3948ce09ef 100644
--- a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts
+++ b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts
@@ -70,6 +70,10 @@ const isGateway404Error = (error: unknown): boolean => {
return error instanceof BadRequestError && error.message?.includes("Request failed with status code 404");
};
+const isGateway403Error = (error: unknown): boolean => {
+ return error instanceof BadRequestError && error.message?.includes("Request failed with status code 403");
+};
+
const isGateway301Error = (error: unknown): boolean => {
return error instanceof BadRequestError && error.message?.includes("Request failed with status code 301");
};
@@ -727,6 +731,80 @@ class NamespaceHeaderNotSupportedError extends Error {
}
}
+const isRootNamespace = (namespace: string) => namespace === "/" || namespace === "root" || !namespace;
+
+// Fallback for restricted Vault tokens that lack permission to list a mount from its root.
+// We ask Vault for the resultant ACL of the current token and derive the sub-paths within the
+// given mount that the token is authorized for. These are returned relative to the mount, with the
+// trailing slash preserved: an entry with a trailing slash (e.g. "team-a/") is a folder the caller
+// should recurse into, while an entry without one (e.g. "team-a/db") is a concrete secret path.
+const listHCVaultAccessiblePathsFromAcl = async (
+ namespace: string,
+ mountPath: string,
+ instanceUrl: string,
+ accessToken: string,
+ connection: THCVaultConnection,
+ gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">,
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
+ gatewayDetails?: TGatewayDetails
+): Promise<string[]> => {
+ const fetchResultantAcl = (skipNamespaceHeader: boolean) =>
+ requestWithHCVaultGateway<{
+ data: {
+ exact_paths?: Record<string, { capabilities: string[] }>;
+ glob_paths?: Record<string, { capabilities: string[] }>;
+ };
+ }>(
+ connection,
+ gatewayService,
+ gatewayV2Service,
+ {
+ url: `${instanceUrl}/v1/sys/internal/ui/resultant-acl`,
+ method: "GET",
+ headers: {
+ "X-Vault-Token": accessToken,
+ ...(skipNamespaceHeader ? {} : { "X-Vault-Namespace": namespace })
+ }
+ },
+ gatewayDetails
+ );
+
+ // vault 1.0.0 does not support namespace root or /, responding with a 301 when the namespace header is sent.
+ let data;
+ try {
+ ({ data } = await fetchResultantAcl(isRootNamespace(namespace)));
+ } catch (error) {
+ if (
+ !isRootNamespace(namespace) &&
+ ((error instanceof AxiosError && error.response?.status === 301) || isGateway301Error(error))
+ ) {
+ ({ data } = await fetchResultantAcl(true));
+ } else {
+ throw error;
+ }
+ }
+
+ // ACL paths follow the pattern $NS/$MOUNT/... When the namespace is root there is no namespace segment, so the paths start
+ // directly with the mount. We strip both the namespace and the mount to get a path relative to the
+ // mount, keeping the trailing slash so the caller can tell folders ("team-a/") from secrets ("team-a/db").
+ const nsPrefix = isRootNamespace(namespace) ? "" : `${removeTrailingSlash(namespace)}/`;
+ const mountPrefix = `${removeTrailingSlash(mountPath)}/`;
+
+ const collectRelativePaths = (paths?: Record<string, { capabilities: string[] }>): string[] => {
+ if (!paths) return [];
+
+ return Object.keys(paths)
+ .map((path) => (nsPrefix && path.startsWith(nsPrefix) ? path.slice(nsPrefix.length) : path))
+ .filter((path) => path.startsWith(mountPrefix))
+ .map((path) => path.slice(mountPrefix.length))
+ .filter((path) => removeTrailingSlash(path).length > 0); // drop the bare mount root (can't list it anyway)
+ };
+
+ const relativePaths = [...collectRelativePaths(data.data.exact_paths), ...collectRelativePaths(data.data.glob_paths)];
+
+ return Array.from(new Set(relativePaths));
+};
+
export const listHCVaultSecretPaths = async (
namespace: string,
connection: THCVaultConnection,
@@ -753,6 +831,8 @@ export const listHCVaultSecretPaths = async (
path = secretPath ? `${mountPath}/${secretPath}` : mountPath;
}
+ logger.info(path, "Path!!!");
+
try {
const { data } = await requestWithHCVaultGateway<{
data: {
@@ -825,6 +905,30 @@ export const listHCVaultSecretPaths = async (
return secretPathsArrays.flat();
};
+ // Recurse from each currentPath in parallel, retrying without the namespace header if Vault rejects it.
+ const recurseFromPaths = async (
+ cleanMountPath: string,
+ kvVersion: "1" | "2",
+ limiter: ReturnType<typeof createConcurrencyLimiter>,
+ currentPaths: string[]
+ ): Promise<string[]> => {
+ const arrays = await Promise.all(
+ currentPaths.map(async (currentPath) => {
+ try {
+ return await recursivelyGetAllPaths(cleanMountPath, kvVersion, limiter, currentPath);
+ } catch (error) {
+ // Vault rejected the namespace header (301 on root/"/"), retry without it.
+ if (error instanceof NamespaceHeaderNotSupportedError) {
+ return recursivelyGetAllPaths(cleanMountPath, kvVersion, limiter, currentPath, true);
+ }
+ throw error;
+ }
+ })
+ );
+
+ return arrays.flat();
+ };
+
// Get all mounts
const mounts = await listHCVaultMounts(connection, gatewayService, gatewayV2Service, namespace);
@@ -852,6 +956,36 @@ export const listHCVaultSecretPaths = async (
if (error instanceof NamespaceHeaderNotSupportedError) {
return recursivelyGetAllPaths(cleanMountPath, kvVersion, limiter, "", true);
}
+
+ // Restricted tokens may lack permission to list the mount from its root, returning a 403 on the
+ // first listing. Fall back to the token's resultant ACL to discover the sub-paths it can access.
+ if ((error instanceof AxiosError && error.response?.status === 403) || isGateway403Error(error)) {
+ const accessiblePaths = await listHCVaultAccessiblePathsFromAcl(
+ namespace,
+ cleanMountPath,
+ instanceUrl,
+ accessToken,
+ connection,
+ gatewayService,
+ gatewayV2Service,
+ gatewayDetails
+ );
+
+ // ACL entries without a trailing slash are concrete secret paths, so we append them directly
+ // (no listing/recursion needed). Entries with a trailing slash are folders we recurse into.
+ const directSecretPaths = accessiblePaths
+ .filter((path) => !path.endsWith("/"))
+ .map((path) => `${cleanMountPath}/${path}`);
+
+ const folderPaths = accessiblePaths
+ .filter((path) => path.endsWith("/"))
+ .map((path) => removeTrailingSlash(path));
+
+ const recursedSecretPaths = await recurseFromPaths(cleanMountPath, kvVersion, limiter, folderPaths);
+
+ return Array.from(new Set([...directSecretPaths, ...recursedSecretPaths]));
+ }
+
throw error;
}
})