Skip to content

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

feat(errors): introduce ClientClosedRequestError and handle client disconnections

Victor Hugo dos Santosd9f355fb146c
diff --git a/backend/src/lib/errors/classify.ts b/backend/src/lib/errors/classify.ts
index 1b33dc30b5..90bb639214 100644
--- a/backend/src/lib/errors/classify.ts
+++ b/backend/src/lib/errors/classify.ts
@@ -6,6 +6,7 @@ import { hasPostgresErrorCode, PostgresErrorCode } from "@app/lib/errors/postgre
import {
BadRequestError,
+ ClientClosedRequestError,
CryptographyError,
DatabaseError,
ForbiddenRequestError,
@@ -77,6 +78,7 @@ export const classifyError = (err: unknown): ErrorType => {
if (err instanceof ScimRequestError) return "scim";
if (err instanceof OidcAuthError) return "oidc";
if (err instanceof InternalServerError) return "internal";
+ if (err instanceof ClientClosedRequestError) return "network";
if (isAwsError(err, "ThrottlingException")) return "rate_limit";
diff --git a/backend/src/lib/errors/index.ts b/backend/src/lib/errors/index.ts
index 6f8c001a65..20544cfa66 100644
--- a/backend/src/lib/errors/index.ts
+++ b/backend/src/lib/errors/index.ts
@@ -36,6 +36,22 @@ export class GatewayTimeoutError extends Error {
}
}
+// Thrown to stop work for a request whose client has already disconnected. No one receives the response.
+export class ClientClosedRequestError extends Error {
+ name: string;
+
+ constructor({ message }: { message?: string } = {}) {
+ super(message || "The client closed the connection before the request completed");
+ this.name = "ClientClosedRequestError";
+ }
+}
+
+export const throwIfClientDisconnected = (signal?: AbortSignal) => {
+ if (signal?.aborted) {
+ throw new ClientClosedRequestError();
+ }
+};
+
export class UnauthorizedError extends Error {
name: string;
diff --git a/backend/src/server/lib/client-disconnect.test.ts b/backend/src/server/lib/client-disconnect.test.ts
new file mode 100644
index 0000000000..ed3e3cbc37
--- /dev/null
+++ b/backend/src/server/lib/client-disconnect.test.ts
@@ -0,0 +1,53 @@
+import { EventEmitter } from "node:events";
+
+import { FastifyReply } from "fastify";
+import { describe, expect, test } from "vitest";
+
+import { ClientClosedRequestError, throwIfClientDisconnected } from "@app/lib/errors";
+
+import { getClientDisconnectSignal } from "./client-disconnect";
+
+const makeReply = (state: { destroyed?: boolean; writableEnded?: boolean } = {}) => {
+ const raw = Object.assign(new EventEmitter(), { destroyed: false, writableEnded: false, ...state });
+ return { reply: { raw } as unknown as FastifyReply, raw };
+};
+
+describe("getClientDisconnectSignal", () => {
+ test("stays open while the request is in flight", () => {
+ const { reply } = makeReply();
+ expect(getClientDisconnectSignal(reply).aborted).toBe(false);
+ });
+
+ test("aborts when the connection closes before the response is written", () => {
+ const { reply, raw } = makeReply();
+ const signal = getClientDisconnectSignal(reply);
+ raw.emit("close");
+ expect(signal.aborted).toBe(true);
+ });
+
+ test("does not abort when close follows a completed response", () => {
+ const { reply, raw } = makeReply();
+ const signal = getClientDisconnectSignal(reply);
+ raw.writableEnded = true;
+ raw.emit("close");
+ expect(signal.aborted).toBe(false);
+ });
+
+ test("is already aborted when the connection closed before the handler asked", () => {
+ const { reply } = makeReply({ destroyed: true });
+ expect(getClientDisconnectSignal(reply).aborted).toBe(true);
+ });
+});
+
+describe("throwIfClientDisconnected", () => {
+ test("does nothing without a signal or with an open one", () => {
+ expect(() => throwIfClientDisconnected()).not.toThrow();
+ expect(() => throwIfClientDisconnected(new AbortController().signal)).not.toThrow();
+ });
+
+ test("throws ClientClosedRequestError once aborted", () => {
+ const controller = new AbortController();
+ controller.abort();
+ expect(() => throwIfClientDisconnected(controller.signal)).toThrow(ClientClosedRequestError);
+ });
+});
diff --git a/backend/src/server/lib/client-disconnect.ts b/backend/src/server/lib/client-disconnect.ts
new file mode 100644
index 0000000000..4821573270
--- /dev/null
+++ b/backend/src/server/lib/client-disconnect.ts
@@ -0,0 +1,21 @@
+import { FastifyReply } from "fastify";
+
+// Aborts when the connection closes before the response has been written. A response that completes
+// normally also emits "close", so writableEnded is what separates a finished request from an abandoned one.
+export const getClientDisconnectSignal = (reply: FastifyReply): AbortSignal => {
+ const controller = new AbortController();
+ const res = reply.raw;
+
+ if (res.destroyed && !res.writableEnded) {
+ controller.abort();
+ return controller.signal;
+ }
+
+ res.once("close", () => {
+ if (!res.writableEnded) {
+ controller.abort();
+ }
+ });
+
+ return controller.signal;
+};
diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.ts
index 388e54666b..56eb5c2570 100644
--- a/backend/src/server/plugins/error-handler.ts
+++ b/backend/src/server/plugins/error-handler.ts
@@ -8,6 +8,7 @@ import { AcmeError } from "@app/ee/services/pki-acme/pki-acme-errors";
import { getConfig } from "@app/lib/config/env";
import {
BadRequestError,
+ ClientClosedRequestError,
ConflictError,
CryptographyError,
DatabaseError,
@@ -50,7 +51,9 @@ enum HttpStatusCodes {
// eslint-disable-next-line @typescript-eslint/no-shadow
InternalServerError = 500,
GatewayTimeout = 504,
- TooManyRequests = 429
+ TooManyRequests = 429,
+ // Non-standard (nginx convention). The client is gone, so this only reaches logs and metrics.
+ ClientClosedRequest = 499
}
export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider) => {
@@ -73,6 +76,7 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
// avoid stack serialization; keep full-stack logging for unexpected / server errors.
const isExpectedClientError =
error instanceof BadRequestError ||
+ error instanceof ClientClosedRequestError ||
error instanceof NotFoundError ||
error instanceof ConflictError ||
error instanceof UnauthorizedError ||
@@ -219,6 +223,13 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
error: error.name,
details: error.details
});
+ } else if (error instanceof ClientClosedRequestError) {
+ void res.status(HttpStatusCodes.ClientClosedRequest).send({
+ reqId: req.id,
+ statusCode: HttpStatusCodes.ClientClosedRequest,
+ message: error.message,
+ error: error.name
+ });
} else if (error instanceof ConflictError) {
void res
.status(HttpStatusCodes.Conflict)
diff --git a/backend/src/server/routes/v3/deprecated-secret-router.ts b/backend/src/server/routes/v3/deprecated-secret-router.ts
index d37199ac0c..ac4ddbd186 100644
--- a/backend/src/server/routes/v3/deprecated-secret-router.ts
+++ b/backend/src/server/routes/v3/deprecated-secret-router.ts
@@ -8,6 +8,7 @@ import { AUDIT_LOG_SENSITIVE_VALUE } from "@app/lib/config/const";
import { BadRequestError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
import { secretsLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { getClientDisconnectSignal } from "@app/server/lib/client-disconnect";
import { BaseSecretNameSchema, SecretNameSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { getUserAgentType } from "@app/server/plugins/audit-log";
@@ -336,7 +337,8 @@ export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider)
includeImports: req.query.include_imports,
recursive: req.query.recursive,
tagSlugs: req.query.tagSlugs,
- ifNoneMatch: req.headers["if-none-match"]
+ ifNoneMatch: req.headers["if-none-match"],
+ abortSignal: getClientDisconnectSignal(reply)
});
const { secrets, imports, etag, notModified } = result;
diff --git a/backend/src/server/routes/v4/secret-router.ts b/backend/src/server/routes/v4/secret-router.ts
index db82009321..1008481523 100644
--- a/backend/src/server/routes/v4/secret-router.ts
+++ b/backend/src/server/routes/v4/secret-router.ts
@@ -8,6 +8,7 @@ import { AUDIT_LOG_SENSITIVE_VALUE } from "@app/lib/config/const";
import { BadRequestError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
import { secretsLimit } from "@app/server/config/rateLimiter";
+import { getClientDisconnectSignal } from "@app/server/lib/client-disconnect";
import { BaseSecretNameSchema, SecretNameSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { getUserAgentType } from "@app/server/plugins/audit-log";
@@ -219,7 +220,8 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
includeImports: req.query.includeImports,
recursive: req.query.recursive,
tagSlugs: req.query.tagSlugs,
- ifNoneMatch: req.headers["if-none-match"]
+ ifNoneMatch: req.headers["if-none-match"],
+ abortSignal: getClientDisconnectSignal(reply)
});
const { secrets, imports, etag, notModified } = result;
diff --git a/backend/src/services/integration-auth/integration-sync-secret.ts b/backend/src/services/integration-auth/integration-sync-secret.ts
index d5f1c778cd..b7469d4fd8 100644
--- a/backend/src/services/integration-auth/integration-sync-secret.ts
+++ b/backend/src/services/integration-auth/integration-sync-secret.ts
@@ -3815,7 +3815,8 @@ const syncSecretsCloudflarePages = async ({
]);
if (getSecretsRes) {
- const toDeleteKeys = Object.keys(getSecretsRes).filter((key) => !Object.keys(secrets).includes(key));
+ const secretKeys = new Set(Object.keys(secrets));
+ const toDeleteKeys = Object.keys(getSecretsRes).filter((key) => !secretKeys.has(key));
const toDeleteEntries: [string, null][] = toDeleteKeys.map((key) => [key, null]);
secretEntries = [...secretEntries, ...toDeleteEntries];
}
@@ -3899,8 +3900,9 @@ const syncSecretsCloudflareWorkers = async ({
// get deleted secrets list
const deletedSecretKeys: string[] = [];
if (getSecretsRes) {
+ const secretKeys = new Set(Object.keys(secrets));
getSecretsRes.forEach((secretRes) => {
- if (!Object.keys(secrets).includes(secretRes.name)) {
+ if (!secretKeys.has(secretRes.name)) {
deletedSecretKeys.push(secretRes.name);
}
});
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.test.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.test.ts
new file mode 100644
index 0000000000..1ff8d4e7e2
--- /dev/null
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.test.ts
@@ -0,0 +1,301 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+import { TSecretFolders } from "@app/db/schemas";
+import { logger } from "@app/lib/logger";
+
+import { buildHierarchy, expandSecretReferencesGroupedByPath, generatePaths } from "./secret-v2-bridge-fns";
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }
+}));
+
+type TPath = { path: string; folderId: string };
+
+const folder = (id: string, name: string, parentId: string | null) =>
+ ({
+ id,
+ name,
+ parentId,
+ envId: "env-1",
+ version: 1,
+ isReserved: false,
+ createdAt: new Date(0),
+ updatedAt: new Date(0)
+ }) as TSecretFolders;
+
+const ROOT = folder("root-id", "root", null);
+
+const buildChain = (depth: number) => {
+ const folders = [ROOT];
+ let parent = ROOT.id;
+ for (let i = 0; i < depth; i += 1) {
+ const id = `d-${i}`;
+ folders.push(folder(id, `level-${i}`, parent));
+ parent = id;
+ }
+ return folders;
+};
+
+// Paths for d-0..d-(count-1) of buildChain, rooted at the environment root.
+const chainPaths = (count: number): TPath[] => {
+ const paths: TPath[] = [{ path: "/", folderId: ROOT.id }];
+ let current = "/";
+ for (let i = 0; i < count; i += 1) {
+ current = `${current}/level-${i}`;
+ paths.push({ path: current, folderId: `d-${i}` });
+ }
+ return paths;
+};
+
+// Park-Miller PRNG so the random tree is reproducible across runs.
+const seededRandom = (seed: number) => {
+ let state = seed;
+ return () => {
+ state = (state * 16807) % 2147483647;
+ return (state - 1) / 2147483646;
+ };
+};
+
+const buildRandomTree = (size: number, seed: number) => {
+ const rand = seededRandom(seed);
+ const folders = [ROOT];
+ for (let i = 0; i < size; i += 1) {
+ const parent = folders[Math.floor(rand() * folders.length)];
+ folders.push(folder(`r-${i}`, `n-${i}`, parent.id));
+ }
+ // Shuffle so sibling order comes from input order, not creation order.
+ for (let i = folders.length - 1; i > 0; i -= 1) {
+ const j = Math.floor(rand() * (i + 1));
+ [folders[i], folders[j]] = [folders[j], folders[i]];
+ }
+ return folders;
+};
+
+describe("generatePaths", () => {
+ beforeEach(() => {
+ vi.mocked(logger.info).mockClear();
+ });
+
+ test("returns an empty list for an environment with no folders", () => {
+ expect(generatePaths(buildHierarchy([]))).toEqual([]);
+ });
+
+ test("emits the root as '/' and its descendants with a double slash", () => {
+ const map = buildHierarchy([ROOT, folder("a", "a", ROOT.id), folder("b", "b", "a")]);
+ expect(generatePaths(map)).toEqual([
+ { path: "/", folderId: "root-id" },
+ { path: "//a", folderId: "a" },
+ { path: "//a/b", folderId: "b" }
+ ]);
+ });
+
+ test("emits parent then subtree, in children order (depth-first pre-order)", () => {
+ const map = buildHierarchy([
+ ROOT,
+ folder("a", "a", ROOT.id),
+ folder("b", "b", ROOT.id),
+ folder("a1", "a1", "a"),
+ folder("b1", "b1", "b"),
+ folder("a2", "a2", "a")
+ ]);
+ expect(generatePaths(map).map((p) => p.folderId)).toEqual(["root-id", "a", "a1", "a2", "b", "b1"]);
+ });
+
+ test("returns every folder of a wide tree in pre-order", () => {
+ const width = 500;
+ const grandchildren = 4;
+ const folders = [ROOT];
+ const expected: TPath[] = [{ path: "/", folderId: ROOT.id }];
+ for (let i = 0; i < width; i += 1) {
+ folders.push(folder(`c-${i}`, `child-${i}`, ROOT.id));
+ expected.push({ path: `//child-${i}`, folderId: `c-${i}` });
+ for (let j = 0; j < grandchildren; j += 1) {
+ folders.push(folder(`g-${i}-${j}`, `grandchild-${j}`, `c-${i}`));
+ expected.push({ path: `//child-${i}/grandchild-${j}`, folderId: `g-${i}-${j}` });
+ }
+ }
+
+ expect(generatePaths(buildHierarchy(folders))).toEqual(expected);
+ expect(logger.info).not.toHaveBeenCalled();
+ });
+
+ test("returns a deep tree within the limit in full", () => {
+ expect(generatePaths(buildHierarchy(buildChain(19)))).toEqual(chainPaths(19));
+ expect(logger.info).not.toHaveBeenCalled();
+ });
+
+ test("does not log when the deepest folders sit at the limit with nothing below them", () => {
+ expect(generatePaths(buildHierarchy(buildChain(20)))).toEqual(chainPaths(20));
+ expect(logger.info).not.toHaveBeenCalled();
+ });
+
+ test("stops at depth 20 on a tree deeper than 20 levels and logs counts, not the folder map", () => {
+ const folders = buildChain(35);
+ // Extra branches around the cutoff so several folders sit exactly at the limit.
+ folders.push(folder("side-17", "side", "d-17"), folder("side-18", "side", "d-18"), folder("side-19", "x", "d-19"));
+
+ const actual = generatePaths(buildHierarchy(folders));
+
+ // Root is depth 0, so d-19 (depth 20) is the last level emitted and its children are cut.
+ const ids = actual.map((p) => p.folderId);
+ expect(ids).toEqual(expect.arrayContaining(["d-19", "side-17", "side-18"]));
+ expect(ids).not.toContain("d-20");
+ expect(ids).not.toContain("side-19");
+ expect(actual).toHaveLength(1 + 20 + 2);
+
+ // d-19 and side-18 both sit at the limit, but only d-19 has children that get skipped.
+ expect(logger.info).toHaveBeenCalledTimes(1);
+ const [[message]] = vi.mocked(logger.info).mock.calls as unknown as [[string]];
+ expect(message).toContain("[depthLimitedFolderCount=1]");
+ expect(message).toContain("[sampleFolderIds=d-19]");
+ expect(message).not.toContain("level-");
+ expect(message.length).toBeLessThan(500);
+ });
+
+ test("emits each reachable folder once, under its parent's path, before its own subtree", () => {
+ for (const seed of [1, 7, 42, 1337]) {
+ const folders = buildRandomTree(3000, seed);
+ const byId = new Map(folders.map((f) => [f.id, f]));
+ const paths = generatePaths(buildHierarchy(folders));
+
+ expect(paths).toHaveLength(folders.length);
+ expect(new Set(paths.map((p) => p.folderId)).size).toBe(folders.length);
+
+ const indexById = new Map(paths.map((p, i) => [p.folderId, i]));
+ const pathById = new Map(paths.map((p) => [p.folderId, p.path]));
+ for (const { folderId, path } of paths) {
+ const { parentId, name } = byId.get(folderId) as TSecretFolders;
+ if (!parentId) {
+ expect(path).toBe("/");
+ } else {
+ expect(path).toBe(`${pathById.get(parentId)}/${name}`);
+ expect(indexById.get(parentId)).toBeLessThan(indexById.get(folderId) as number);
+ }
+ }
+ }
+ });
+
+ test("treats top-level folders not named root as '/<name>'", () => {
+ const map = buildHierarchy([folder("x", "x", null), folder("y", "y", "x"), ROOT, folder("z", "z", ROOT.id)]);
+ expect(generatePaths(map)).toEqual([
+ { path: "/x", folderId: "x" },
+ { path: "/x/y", folderId: "y" },
+ { path: "/", folderId: "root-id" },
+ { path: "//z", folderId: "z" }
+ ]);
+ });
+
+ test("ignores folders that are unreachable from the top level, including parent cycles", () => {
+ const map = buildHierarchy([ROOT, folder("p", "p", "q"), folder("q", "q", "p")]);
+ expect(generatePaths(map)).toEqual([{ path: "/", folderId: "root-id" }]);
+ });
+
+ test("honors explicit parentId, basePath and depth arguments", () => {
+ const map = buildHierarchy(buildChain(30));
+ // Starting at depth 5 below d-2, d-18 lands on the depth-20 limit.
+ const expected: TPath[] = [];
+ let current = "/base";
+ for (let i = 3; i <= 18; i += 1) {
+ current = `${current}/level-${i}`;
+ expected.push({ path: current, folderId: `d-${i}` });
+ }
+ expect(generatePaths(map, "d-2", "/base", 5)).toEqual(expected);
+ });
+});
+
+type TTestSecret = {
+ secretKey: string;
+ secretPath: string;
+ secretValue: string;
+ skipMultilineEncoding?: boolean | null;
+};
+
+describe("expandSecretReferencesGroupedByPath", () => {
+ const makeSecret = (secretPath: string, secretKey: string, secretValue = `ref-${secretKey}`): TTestSecret => ({
+ secretPath,
+ secretKey,
+ secretValue
+ });
+
+ test("expands every secret in place and reports no errors when all expansions succeed", async () => {
+ const secrets = [makeSecret("/a", "A1"), makeSecret("/b", "B1"), makeSecret("/a", "A2")];
+ const expand = vi.fn(async ({ secretKey }: { secretKey: string }) => `expanded-${secretKey}`);
+
+ const errors = await expandSecretReferencesGroupedByPath({
+ secrets,
+ environment: "dev",
+ expandSecretReferences: expand
+ });
+
+ expect(errors).toEqual([]);
+ expect(secrets.map((s) => s.secretValue)).toEqual(["expanded-A1", "expanded-B1", "expanded-A2"]);
+ expect(expand).toHaveBeenCalledWith(
+ expect.objectContaining({ secretKey: "B1", secretPath: "/b", environment: "dev", value: "ref-B1" })
+ );
+ });
+
+ test("stores an empty string when the expander returns undefined", async () => {
+ const secrets = [makeSecret("/a", "A1")];
+ await expandSecretReferencesGroupedByPath({
+ secrets,
+ environment: "dev",
+ expandSecretReferences: async () => undefined
+ });
+ expect(secrets[0].secretValue).toBe("");
+ });
+
+ test("attributes each rejection to the path of the secret that failed", async () => {
+ // Interleaved paths so group order differs from input order.
+ const secrets = [
+ makeSecret("/a", "A1"),
+ makeSecret("/b", "B1"),
+ makeSecret("/c", "C1"),
+ makeSecret("/a", "A2"),
+ makeSecret("/c", "C2"),
+ makeSecret("/b", "B2")
+ ];
+ const failing = new Set(["B2", "C1", "C2"]);
+
+ const errors = await expandSecretReferencesGroupedByPath({
+ secrets,
+ environment: "dev",
+ expandSecretReferences: async ({ secretKey, secretPath }) => {
+ if (failing.has(secretKey)) throw new Error(`cannot expand ${secretKey} in ${secretPath}`);
+ return `ok-${secretKey}`;
+ }
+ });
+
+ expect(errors).toEqual([
+ { path: "/b", error: "cannot expand B2 in /b" },
+ { path: "/c", error: "cannot expand C1 in /c" },
+ { path: "/c", error: "cannot expand C2 in /c" }
+ ]);
+ for (const error of errors) {
+ const [, key, pathInMessage] = /cannot expand (\S+) in (\S+)/.exec(error.error) ?? [];
+ expect(pathInMessage).toBe(error.path);
+ expect(secrets.find((s) => s.secretKey === key)?.secretPath).toBe(error.path);
+ }
+
+ expect(secrets.find((s) => s.secretKey === "A1")?.secretValue).toBe("ok-A1");
+ expect(secrets.find((s) => s.secretKey === "B2")?.secretValue).toBe("ref-B2");
+ });
+
+ test("keeps the mapping correct across many paths", async () => {
+ const pathCount = 2000;
+ const secrets = Array.from({ length: pathCount }, (_, i) => makeSecret(`/p-${i}`, `K${i}`));
+
+ const errors = await expandSecretReferencesGroupedByPath({
+ secrets,
+ environment: "dev",
+ expandSecretReferences: async ({ secretKey, secretPath }) => {
+ if (Number(secretKey.slice(1)) % 7 === 0) throw new Error(`fail:${secretPath}`);
+ return secretKey;
+ }
+ });
+
+ expect(errors).toHaveLength(Math.ceil(pathCount / 7));
+ for (const error of errors) {
+ expect(error.error).toBe(`fail:${error.path}`);
+ }
+ });
+});
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts
index 2685d116d8..caec3f6dee 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-fns.ts
@@ -499,48 +499,134 @@ export const buildHierarchy = (folders: TSecretFolders[]): FolderMap => {
return map;
};
+const GENERATE_PATHS_MAX_DEPTH = 20;
+const GENERATE_PATHS_MAX_LOGGED_FOLDER_IDS = 5;
+
+// Depth-first pre-order: each folder, then its subtree, in children order.
export const generatePaths = (
map: FolderMap,
parentId: string = "null",
basePath: string = "",
currentDepth: number = 0
): { path: string; folderId: string }[] => {
- const children = map[parentId || "null"] || [];
- let paths: { path: string; folderId: string }[] = [];
+ const paths: { path: string; folderId: string }[] = [];
+ const depthLimitedFolderIds: string[] = [];
+ let depthLimitedFolderCount = 0;
- children.forEach((child) => {
- // Determine if this is the root folder of the environment. If no parentId is present and the name is root, it's the root folder
- const isRootFolder = child.name === "root" && !child.parentId;
+ const visit = (visitParentId: string, visitBasePath: string, depth: number) => {
+ const children = map[visitParentId || "null"] || [];
- // Form the current path based on the base path and the current child
- // eslint-disable-next-line no-nested-ternary
- const currPath = basePath === "" ? (isRootFolder ? "/" : `/${child.name}`) : `${basePath}/${child.name}`;
+ for (const child of children) {
+ // Determine if this is the root folder of the environment. If no parentId is present and the name is root, it's the root folder
+ const isRootFolder = child.name === "root" && !child.parentId;
- // Add the current path
- paths.push({
- path: currPath,
- folderId: child.id
- });
+ const currPath =
+ // eslint-disable-next-line no-nested-ternary
+ visitBasePath === "" ? (isRootFolder ? "/" : `/${child.name}`) : `${visitBasePath}/${child.name}`;
- // We make sure that the recursion depth doesn't exceed 20.
- // We do this to create "circuit break", basically to ensure that we can't encounter any potential memory leaks.
- if (currentDepth >= 20) {
- logger.info(`generatePaths: Recursion depth exceeded 20, breaking out of recursion [map=${JSON.stringify(map)}]`);
- return;
+ paths.push({
+ path: currPath,
+ folderId: child.id
+ });
+
+ // Circuit breaker: a parentId cycle in the folder data would otherwise recurse forever.
+ if (depth >= GENERATE_PATHS_MAX_DEPTH) {
+ if (map[child.id]?.length) {
+ depthLimitedFolderCount += 1;
+ if (depthLimitedFolderIds.length < GENERATE_PATHS_MAX_LOGGED_FOLDER_IDS) {
+ depthLimitedFolderIds.push(child.id);
+ }
+ }
+ } else {
+ visit(child.id, currPath, depth + 1);
+ }
}
- // Recursively generate paths for children, passing down the formatted path
- const childPaths = generatePaths(map, child.id, currPath, currentDepth + 1);
- paths = paths.concat(
- childPaths.map((p) => ({
- path: p.path,
- folderId: p.folderId
- }))
+ };
+
+ visit(parentId, basePath, currentDepth);
+
+ if (depthLimitedFolderCount > 0) {
+ logger.info(
+ `generatePaths: Recursion depth exceeded ${GENERATE_PATHS_MAX_DEPTH}, skipping deeper folders [depthLimitedFolderCount=${depthLimitedFolderCount}] [pathCount=${paths.length}] [sampleFolderIds=${depthLimitedFolderIds.join(",")}]`
);
- });
+ }
return paths;
};
+type TExpandableSecret = {
+ secretKey: string;
+ secretPath: string;
+ secretValue: string;
+ skipMultilineEncoding?: boolean | null;
+};
+
+export type TSecretReferenceExpansionError = { path: string; error: string };
+
+// Expands every secret's value in place and returns one entry per failed expansion, tagged with the
+// secret's path.
+export const expandSecretReferencesGroupedByPath = async <T extends TExpandableSecret>({
+ secrets,
+ environment,
+ expandSecretReferences
+}: {
+ secrets: T[];
+ environment: string;
+ expandSecretReferences: (input: {
+ value?: string;
+ secretPath: string;
+ environment: string;
+ skipMultilineEncoding?: boolean | null;
+ secretKey: string;
+ }) => Promise<string | undefined>;
+}): Promise<TSecretReferenceExpansionError[]> => {
+ const secretsGroupByPath = groupBy(secrets, (i) => i.secretPath);
+ // One key list shared by the promise fan-out and the error mapping, so result indexes always line up.
+ const groupedPaths = Object.keys(secretsGroupByPath);
+
+ const settledPromises = await Promise.allSettled(
+ groupedPaths.map((groupedPath) =>
+ Promise.allSettled(
+ secretsGroupByPath[groupedPath].map(async (secret) => {
+ const expandedSecretValue = await expandSecretReferences({
+ value: secret.secretValue,
+ secretPath: groupedPath,
+ environment,
+ skipMultilineEncoding: secret.skipMultilineEncoding,
+ secretKey: secret.secretKey
+ });
+ // eslint-disable-next-line no-param-reassign
+ secret.secretValue = expandedSecretValue || "";
+ })
+ )
+ )
+ );
+
+ const errors: TSecretReferenceExpansionError[] = [];
+ settledPromises.forEach((outerResult, outerIndex) => {
+ const groupedPath = groupedPaths[outerIndex];
+
+ if (outerResult.status === "rejected") {
+ errors.push({
+ path: groupedPath,
+ error: `Failed to process secret group: ${outerResult.reason}`
+ });
+ return;
+ }
+
+ outerResult.value.forEach((innerResult) => {
+ if (innerResult.status === "rejected") {
+ errors.push({
+ path: groupedPath,
+ error: (innerResult.reason as Error).message
+ });
+ }
+ });
+ });
+
+ return errors;
+};
+
type TRecursivelyFetchSecretsFromFoldersArg = {
folderDAL: Pick<TSecretFolderDALFactory, "find">;
projectEnvDAL: Pick<TProjectEnvDALFactory, "findOne">;
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
index c9f62dc9d1..f942bde510 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
@@ -31,7 +31,7 @@ import { withCache } from "@app/lib/cache/with-cache";
import { generateCacheKeyFromBuffer, generateCacheKeyFromData } from "@app/lib/crypto/cache";
import { utcDayStamp } from "@app/lib/dates";
import { DatabaseErrorCode } from "@app/lib/error-codes";
-import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { BadRequestError, ForbiddenRequestError, NotFoundError, throwIfClientDisconnected } from "@app/lib/errors";
import { diff, groupBy, takeDistinctKeyScanWindow } from "@app/lib/fn";
import { setKnexStringValue } from "@app/lib/knex";
import { logger } from "@app/lib/logger";
@@ -88,6 +88,7 @@ import {
buildHierarchy,
createFetchFolderSecretsWithImports,
createRelativeImportExpander,
+ expandSecretReferencesGroupedByPath,
fnSecretBulkDelete,
fnSecretBulkInsert,
fnSecretBulkUpdate,
@@ -1336,6 +1337,7 @@ export const secretV2BridgeServiceFactory = ({
personalOverridesBehavior,
throwOnMissingReadValuePermission = true,
ifNoneMatch,
+ abortSignal,
...params
} = dto;
@@ -1494,6 +1496,8 @@ export const secretV2BridgeServiceFactory = ({
filters: params
});
+ throwIfClientDisconnected(abortSignal);
+
let secrets: typeof unfilteredSecrets = [];
if (personalOverridesBehavior === PersonalOverridesBehavior.IncludeAll) {
@@ -1649,46 +1653,11 @@ export const secretV2BridgeServiceFactory = ({
});
if (shouldExpandSecretReferences) {
- const secretsGroupByPath = groupBy(decryptedSecrets, (i) => i.secretPath);
- const settledPromises = await Promise.allSettled(
- Object.keys(secretsGroupByPath).map((groupedPath) =>
- Promise.allSettled(
- secretsGroupByPath[groupedPath].map(async (decryptedSecret, index) => {
- const expandedSecretValue = await expandSecretReferences({
- value: decryptedSecret.secretValue,
- secretPath: groupedPath,
- environment,
- skipMultilineEncoding: decryptedSecret.skipMultilineEncoding,
- secretKey: decryptedSecret.secretKey
- });
- // eslint-disable-next-line no-param-reassign
- secretsGroupByPath[groupedPath][index].secretValue = expandedSecretValue || "";
- })
- )
- )
- );
- const errors: { path: string; error: string }[] = [];
-
- settledPromises.forEach((outerResult: PromiseSettledResult<PromiseSettledResult<void>[]>, outerIndex) => {
- const groupedPath = Object.keys(secretsGroupByPath)[outerIndex];
-
- if (outerResult.status === "rejected") {
- errors.push({
- path: groupedPath,
- error: `Failed to process secret group: ${outerResult.reason}`
- });
- } else {
- // Check inner promise results
- outerResult.value.forEach((innerResult: PromiseSettledResult<void>) => {
- if (innerResult.status === "rejected") {
- const reason = innerResult.reason as ForbiddenRequestError;
- errors.push({
- path: groupedPath,
- error: reason.message
- });
- }
- });
- }
+ throwIfClientDisconnected(abortSignal);
+ const errors = await expandSecretReferencesGroupedByPath({
+ secrets: decryptedSecrets,
+ environment,
+ expandSecretReferences
});
if (errors.length > 0) {
throw new ForbiddenRequestError({
@@ -1715,6 +1684,8 @@ export const secretV2BridgeServiceFactory = ({
return { ...payload, etag: computedEtag };
}
+ throwIfClientDisconnected(abortSignal);
+
const secretImports = await secretImportDAL.findByFolderIds(paths.map((p) => p.folderId));
const allowedImports = secretImports.filter(({ isReplication }) => !isReplication);
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
index 912b654661..a6d9f2c810 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
@@ -69,6 +69,7 @@ export type TGetSecretsDTO = {
keys?: string[];
excludeRotatedSecrets?: boolean;
ifNoneMatch?: string;
+ abortSignal?: AbortSignal;
} & TProjectPermission;
export type TGetSecretsMissingReadValuePermissionDTO = Omit<
diff --git a/backend/src/services/secret/secret-fns.ts b/backend/src/services/secret/secret-fns.ts
index 0481fca62c..ed77030270 100644
--- a/backend/src/services/secret/secret-fns.ts
+++ b/backend/src/services/secret/secret-fns.ts
@@ -9,7 +9,6 @@ import {
SecretType,
TableName,
TSecretBlindIndexes,
- TSecretFolders,
TSecrets
} from "@app/db/schemas";
import { hasSecretReadValueOrDescribePermission } from "@app/ee/services/permission/permission-fns";
@@ -20,12 +19,13 @@ import { buildSecretBlindIndexFromName } from "@app/lib/crypto";
import { crypto, SymmetricKeySize } from "@app/lib/crypto/cryptography";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { groupBy, unique } from "@app/lib/fn";
-import { logger } from "@app/lib/logger";
import { recordLegacyRootKeyUsageMetric } from "@app/lib/telemetry/metrics";
import { getAllSecretReferences } from "@app/services/secret-v2-bridge/secret-reference-fns";
import {
+ buildHierarchy,
fnSecretBulkInsert as fnSecretV2BridgeBulkInsert,
- fnSecretBulkUpdate as fnSecretV2BridgeBulkUpdate
+ fnSecretBulkUpdate as fnSecretV2BridgeBulkUpdate,
+ generatePaths
} from "@app/services/secret-v2-bridge/secret-v2-bridge-fns";
import { ActorAuthMethod, ActorType } from "../auth/auth-type";
@@ -85,67 +85,6 @@ type TGetPathsDTO = {
};
};
-// Introduce a new interface for mapping parent IDs to their children
-interface FolderMap {
- [parentId: string]: TSecretFolders[];
-}
-const buildHierarchy = (folders: TSecretFolders[]): FolderMap => {
- const map: FolderMap = {};
- map.null = []; // Initialize mapping for root directory
-
- folders.forEach((folder) => {
- const parentId = folder.parentId || "null";
- if (!map[parentId]) {
- map[parentId] = [];
- }
- map[parentId].push(folder);
- });
-
- return map;
-};
-
-const generatePaths = (
- map: FolderMap,
- parentId: string = "null",
- basePath: string = "",
- currentDepth: number = 0
-): { path: string; folderId: string }[] => {
- const children = map[parentId || "null"] || [];
- let paths: { path: string; folderId: string }[] = [];
-
- children.forEach((child) => {
- // Determine if this is the root folder of the environment. If no parentId is present and the name is root, it's the root folder
- const isRootFolder = child.name === "root" && !child.parentId;
-
- // Form the current path based on the base path and the current child
- // eslint-disable-next-line no-nested-ternary
- const currPath = basePath === "" ? (isRootFolder ? "/" : `/${child.name}`) : `${basePath}/${child.name}`;
-
- // Add the current path
- paths.push({
- path: currPath,
- folderId: child.id
- });
-
- // We make sure that the recursion depth doesn't exceed 20.
- // We do this to create "circuit break", basically to ensure that we can't encounter any potential memory leaks.
- if (currentDepth >= 20) {
- logger.info(`generatePaths: Recursion depth exceeded 20, breaking out of recursion [map=${JSON.stringify(map)}]`);
- return;
- }
- // Recursively generate paths for children, passing down the formatted path
- const childPaths = generatePaths(map, child.id, currPath, currentDepth + 1);
- paths = paths.concat(
- childPaths.map((p) => ({
- path: p.path,
- folderId: p.folderId
- }))
- );
- });
-
- return paths;
-};
-
export const recursivelyGetSecretPaths = ({
folderDAL,
projectEnvDAL,
diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.ts
index 0cdc96ef90..8f6493e122 100644
--- a/backend/src/services/secret/secret-service.ts
+++ b/backend/src/services/secret/secret-service.ts
@@ -1454,11 +1454,13 @@ export const secretServiceFactory = ({
tagSlugs = [],
throwOnMissingReadValuePermission = true,
ifNoneMatch,
+ abortSignal,
...paramsV2
}: TGetSecretsRawDTO) => {
const { botKey, shouldUseSecretV2Bridge } = await projectBotService.getBotKey(projectId);
if (shouldUseSecretV2Bridge) {
const result = await secretV2BridgeService.getSecrets({
+ abortSignal,
projectId,
expandSecretReferences,
personalOverridesBehavior,
diff --git a/backend/src/services/secret/secret-types.ts b/backend/src/services/secret/secret-types.ts
index 0ecf5b57a2..1b68703984 100644
--- a/backend/src/services/secret/secret-types.ts
+++ b/backend/src/services/secret/secret-types.ts
@@ -244,6 +244,7 @@ export type TGetSecretsRawDTO = {
includeMetadataInSearch?: boolean;
excludeRotatedSecrets?: boolean;
ifNoneMatch?: string;
+ abortSignal?: AbortSignal;
} & TProjectPermission;
export type TGetSecretAccessListDTO = {