Skip to content

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

feat(telemetry): add metrics for safeRequest agent pool management

Victor Hugo dos Santos24eb0189e840
diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.ts
index 9430d7c3ad..8181f1b94f 100644
--- a/backend/src/lib/telemetry/metrics.ts
+++ b/backend/src/lib/telemetry/metrics.ts
@@ -10,6 +10,7 @@ import type { Knex } from "knex";
import { classifyError } from "@app/lib/errors/classify";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
+import { getAgentPoolStats } from "@app/lib/validator/safe-request";
import { getConfig } from "../config/env";
@@ -417,6 +418,23 @@ export const recordSecretCacheWriteMetric = (params: { bytes: number; stored: bo
}
};
+// -- safeRequest HTTPS agent pool (InfisicalCore meter) ----------------------------------------
+// The pool is bounded, so a 201st distinct TLS signature costs the least recently used entry its
+// connection. Non-zero for a sustained window means the cap is too low and should be raised.
+export const safeRequestAgentEvictionCounter = infisicalCoreMeter.createCounter(
+ "infisical.safe_request.agent_eviction.count",
+ {
+ description:
+ "Agents evicted from the safeRequest connection pool because it was at capacity. Non-zero for a sustained window means raise AGENT_CACHE_MAX.",
+ unit: "{eviction}"
+ }
+);
+
+export const recordSafeRequestAgentEvictionMetric = () => {
+ if (!isTelemetryEnabled()) return;
+ safeRequestAgentEvictionCounter.add(1);
+};
+
export const coreHttpErrorCounter = infisicalCoreMeter.createCounter("infisical.core.http.error.count", {
description: "API errors with bounded error classification. Labels limited to InfisicalCore View allowlist.",
unit: "{error}"
@@ -808,6 +826,20 @@ export const registerInfrastructureMetrics = (db: Knex) => {
result.observe(pool.numFree?.() ?? 0, { "db.pool.state": "free" });
result.observe(pool.numPendingAcquires?.() ?? 0, { "db.pool.state": "pending" });
});
+
+ // safeRequest agent pool: an in-memory Map size, so it's cheap to observe on every export.
+ // Read alongside infisical.safe_request.agent_eviction.count — size pinned at max with a
+ // non-zero eviction rate is the signal that the cap is too low.
+ const agentPoolGauge = meter.createObservableGauge("infisical.safe_request.agent_pool.size", {
+ description: "Agents currently held in the safeRequest connection pool.",
+ unit: "{agent}"
+ });
+
+ agentPoolGauge.addCallback((result) => {
+ if (!isTelemetryEnabled()) return;
+ const { size, max } = getAgentPoolStats();
+ result.observe(size, { "pool.max": String(max) });
+ });
};
// -- Legacy root-key usage (InfisicalCore meter) -----------------------------------------------------
diff --git a/backend/src/lib/validator/safe-request.agent-pool.socket.test.ts b/backend/src/lib/validator/safe-request.agent-pool.socket.test.ts
index 1ab5069bff..845baf7fdf 100644
--- a/backend/src/lib/validator/safe-request.agent-pool.socket.test.ts
+++ b/backend/src/lib/validator/safe-request.agent-pool.socket.test.ts
@@ -47,15 +47,12 @@ const selfSignedCert = () => {
return { key: forge.pki.privateKeyToPem(keys.privateKey), cert: forge.pki.certificateToPem(cert) };
};
-const post = (agent: https.Agent, port: number) =>
+const post = (agent: https.Agent, port: number, path = "/apis/authentication.k8s.io/v1/tokenreviews") =>
new Promise<number>((resolve, reject) => {
- const req = https.request(
- { host: "127.0.0.1", port, path: "/apis/authentication.k8s.io/v1/tokenreviews", method: "POST", agent },
- (res) => {
- res.resume();
- res.on("end", () => resolve(res.statusCode ?? 0));
- }
- );
+ const req = https.request({ host: "127.0.0.1", port, path, method: "POST", agent }, (res) => {
+ res.resume();
+ res.on("end", () => resolve(res.statusCode ?? 0));
+ });
req.on("error", reject);
req.end("{}");
});
@@ -75,8 +72,13 @@ describe("shared https agent pool (real sockets)", () => {
server = https.createServer({ key, cert }, (req, res) => {
handledRequests += 1;
// Mirror the 401 the fleet was actually getting back from TokenReview.
- res.writeHead(401, { "content-type": "application/json" });
- res.end(JSON.stringify({ kind: "Status", code: 401 }));
+ const reply = () => {
+ res.writeHead(401, { "content-type": "application/json" });
+ res.end(JSON.stringify({ kind: "Status", code: 401 }));
+ };
+ // /slow holds the response open so a request can be caught mid-flight.
+ if (req.url?.includes("slow")) setTimeout(reply, 400);
+ else reply();
});
// Keep idle connections open the way a real API server / LB does, so a leaked
// socket stays visibly leaked instead of being tidied up by the server.
@@ -140,4 +142,28 @@ describe("shared https agent pool (real sockets)", () => {
expect(await openConnections(server)).toBe(0);
});
+
+ it("lets an in-flight request finish when its agent is evicted, instead of resetting it", async () => {
+ const busy = getSharedHttpsAgent({ rejectUnauthorized: false, servername: "inflight.test" });
+ const pending = post(busy, port, "/slow");
+ // Let the socket move from the pool into the agent's active set before evicting.
+ await new Promise((resolve) => {
+ setTimeout(resolve, 80);
+ });
+
+ // The pool is process-wide, so this is one caller's traffic evicting another's
+ // agent. Destroying it outright would reset a request that is already on the wire.
+ for (let i = 0; i < 250; i += 1) {
+ getSharedHttpsAgent({ rejectUnauthorized: false, servername: `drain-pressure-${i}.test` });
+ }
+
+ await expect(pending).resolves.toBe(401);
+
+ // Draining must not become a second way to leak: with maxFreeSockets at zero the
+ // socket closes on release instead of returning to a pool nothing can reach.
+ await new Promise((resolve) => {
+ setTimeout(resolve, 150);
+ });
+ expect(await openConnections(server)).toBe(0);
+ });
});
diff --git a/backend/src/lib/validator/safe-request.test.ts b/backend/src/lib/validator/safe-request.test.ts
index 8dfcbfea96..17f54096a6 100644
--- a/backend/src/lib/validator/safe-request.test.ts
+++ b/backend/src/lib/validator/safe-request.test.ts
@@ -385,6 +385,44 @@ describe("safe-request SSRF helpers", () => {
expect(destroySpy).toHaveBeenCalled();
});
+ it("leaves an agent with a request still on it undestroyed, closing it on release instead", () => {
+ const busy = getSharedHttpsAgent({ ca: CA_A, rejectUnauthorized: true, servername: "busy.example.com" });
+ const destroySpy = vi.spyOn(busy, "destroy");
+ const idleSocket = { destroy: vi.fn() };
+ // One socket mid-request, one idle. The pool is process-wide, so evicting on
+ // another caller's traffic must not reset the request already on the wire.
+ (busy as any).sockets = { "busy.example.com:443:": [{}] };
+ (busy as any).freeSockets = { "busy.example.com:443:": [idleSocket] };
+
+ for (let i = 0; i < 250; i += 1) {
+ getSharedHttpsAgent({ ca: CA_A, rejectUnauthorized: true, servername: `busy-evict-${i}.example.com` });
+ }
+
+ expect(destroySpy).not.toHaveBeenCalled();
+ expect(idleSocket.destroy).toHaveBeenCalled();
+ // Zero free slots means the in-flight socket closes on release rather than
+ // returning to a pool that can no longer reach it.
+ expect(busy.maxFreeSockets).toBe(0);
+ });
+
+ it("warns when the pool runs at capacity, without ever logging the CA in the cache key", async () => {
+ const { logger } = await import("@app/lib/logger");
+ // The warn is throttled, so move past the window rather than depending on
+ // which earlier test last warned.
+ const nowSpy = vi.spyOn(Date, "now").mockReturnValue(Date.now() + 3_600_000);
+ (logger.warn as any).mockClear();
+
+ for (let i = 0; i < 250; i += 1) {
+ getSharedHttpsAgent({ ca: CA_A, rejectUnauthorized: true, servername: `warn-${i}.example.com` });
+ }
+
+ expect(logger.warn).toHaveBeenCalled();
+ const line = (logger.warn as any).mock.calls[0][0] as string;
+ expect(line).toContain("agent pool at capacity");
+ expect(line).not.toContain("BEGIN CERTIFICATE");
+ nowSpy.mockRestore();
+ });
+
it("keeps a recently used agent alive while colder entries are evicted", () => {
const hot = getSharedHttpsAgent({ ca: CA_B, rejectUnauthorized: true, servername: "hot.example.com" });
const hotDestroy = vi.spyOn(hot, "destroy");
diff --git a/backend/src/lib/validator/safe-request.ts b/backend/src/lib/validator/safe-request.ts
index a2a65f139d..304597e3c0 100644
--- a/backend/src/lib/validator/safe-request.ts
+++ b/backend/src/lib/validator/safe-request.ts
@@ -12,6 +12,7 @@ import { getConfig } from "@app/lib/config/env";
import { request } from "@app/lib/config/request";
import { logger } from "@app/lib/logger";
import { sanitizeUrlForLog } from "@app/lib/logger/sanitize-url";
+import { recordSafeRequestAgentEvictionMetric } from "@app/lib/telemetry/metrics";
import { BadRequestError } from "../errors";
import { isPrivateIp } from "../ip/ipRange";
@@ -177,18 +178,46 @@ const agentCache = new Map<string, http.Agent | https.Agent>();
// A keepAlive agent's idle sockets keep the agent itself reachable through their
// own event listeners, so dropping the map entry frees neither: the agent is
// never collected and each pooled socket holds its fd (and the peer's connection
-// slot) for the life of the process. Every eviction has to destroy the agent.
+// slot) for the life of the process. Every eviction has to release those sockets.
+//
+// destroy() would ECONNRESET in-flight requests on this process-wide pool. Close
+// idle sockets now and set maxFreeSockets to 0 so they close on release instead.
+const releaseEvictedAgent = (agent: http.Agent | https.Agent) => {
+ // eslint-disable-next-line no-param-reassign -- releasing the agent is the whole point
+ agent.maxFreeSockets = 0;
+ Object.values(agent.freeSockets).forEach((sockets) => sockets?.forEach((socket) => socket.destroy()));
+ if (!Object.keys(agent.sockets).length) agent.destroy();
+};
+
+const hostnameFromCacheKey = (key: string) => key.split("|")[1] || "unknown";
+
+const EVICTION_WARN_INTERVAL_MS = 60_000;
+let evictionsSinceLastWarn = 0;
+let lastEvictionWarnAt = 0;
+
const evictLeastRecentlyUsedAgents = () => {
while (agentCache.size >= AGENT_CACHE_MAX) {
const oldest = agentCache.entries().next();
if (oldest.done) return;
const [key, agent] = oldest.value;
agentCache.delete(key);
- agent.destroy();
- logger.debug(`safeRequest: evicted least recently used agent [cacheSize=${agentCache.size}]`);
+ releaseEvictedAgent(agent);
+ recordSafeRequestAgentEvictionMetric();
+
+ evictionsSinceLastWarn += 1;
+ const now = Date.now();
+ if (now - lastEvictionWarnAt >= EVICTION_WARN_INTERVAL_MS) {
+ logger.warn(
+ `safeRequest: agent pool at capacity, evicting least recently used [cacheSize=${agentCache.size}] [max=${AGENT_CACHE_MAX}] [evictionsSinceLastWarn=${evictionsSinceLastWarn}] [evictedHostname=${hostnameFromCacheKey(key)}]`
+ );
+ lastEvictionWarnAt = now;
+ evictionsSinceLastWarn = 0;
+ }
}
};
+export const getAgentPoolStats = () => ({ size: agentCache.size, max: AGENT_CACHE_MAX });
+
const buildAgentCacheKey = (
validated: TValidatedHost | undefined,
protocol: string,