Skip to content

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

feat(validator): implement shared HTTPS agent pooling and enhance Kubernetes auth functions

Victor Hugo dos Santos4f6638bf398e
diff --git a/backend/src/ee/services/resource-auth-method/kubernetes-gateway-executor.ts b/backend/src/ee/services/resource-auth-method/kubernetes-gateway-executor.ts
index 79c8b2f741..2f968664ba 100644
--- a/backend/src/ee/services/resource-auth-method/kubernetes-gateway-executor.ts
+++ b/backend/src/ee/services/resource-auth-method/kubernetes-gateway-executor.ts
@@ -1,8 +1,7 @@
-import https from "node:https";
-
import { request as httpRequest } from "@app/lib/config/request";
import { GatewayHttpProxyActions, GatewayProxyProtocol } from "@app/lib/gateway";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { getSharedHttpsAgent } from "@app/lib/validator/safe-request";
import { TGatewayV2ConnectionDetails } from "../gateway-v2/gateway-v2-types";
import { TKubernetesRequestExecutor } from "./kubernetes-auth-fns";
@@ -52,7 +51,7 @@ export const buildGatewayKubernetesExecutor = ({
// no TLS session for us to configure here.
const httpsAgent = isGatewayReviewer
? undefined
- : new https.Agent({
+ : getSharedHttpsAgent({
ca: caCertificate || undefined,
rejectUnauthorized: verifyTlsCertificate ?? true,
servername: targetHost
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
new file mode 100644
index 0000000000..1ab5069bff
--- /dev/null
+++ b/backend/src/lib/validator/safe-request.agent-pool.socket.test.ts
@@ -0,0 +1,143 @@
+/* eslint-disable @typescript-eslint/no-explicit-any */
+import https from "node:https";
+import type { AddressInfo } from "node:net";
+
+import forge from "node-forge";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+import { getSharedHttpsAgent } from "./safe-request";
+
+// Like `safe-request.socket.test.ts`, this drives real sockets against a loopback
+// server rather than mocking the transport, because the properties under test are
+// connect-time ones: that a pooled agent actually reuses its TLS connection, and
+// that evicting one closes the socket it was holding. A dropped keepAlive agent is
+// kept reachable by its own idle sockets' listeners, so "the cache forgot it" and
+// "the fd is released" are different claims and only the socket can tell them apart.
+const { configState } = vi.hoisted(() => ({
+ configState: {
+ isDevelopmentMode: false,
+ ALLOW_INTERNAL_IP_CONNECTIONS: true,
+ SAFE_REQUEST_FORCE_DIRECT_EGRESS: false,
+ SITE_URL: "https://infisical.example",
+ REDIS_URL: "redis://internal-redis:6379",
+ DB_HOST: "internal-db"
+ }
+}));
+
+vi.mock("@app/lib/config/env", () => ({ getConfig: () => configState }));
+vi.mock("@app/ee/services/dynamic-secret/dynamic-secret-fns", () => ({
+ verifyHostInputValidity: vi.fn(async () => undefined)
+}));
+vi.mock("@app/lib/logger", () => ({
+ logger: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }
+}));
+
+const selfSignedCert = () => {
+ const keys = forge.pki.rsa.generateKeyPair(2048);
+ const cert = forge.pki.createCertificate();
+ cert.publicKey = keys.publicKey;
+ cert.serialNumber = "01";
+ cert.validity.notBefore = new Date(Date.now() - 60_000);
+ cert.validity.notAfter = new Date(Date.now() + 60 * 60_000);
+ const attrs = [{ name: "commonName", value: "localhost" }];
+ cert.setSubject(attrs);
+ cert.setIssuer(attrs);
+ cert.setExtensions([{ name: "subjectAltName", altNames: [{ type: 2, value: "localhost" }] }]);
+ cert.sign(keys.privateKey, forge.md.sha256.create());
+ return { key: forge.pki.privateKeyToPem(keys.privateKey), cert: forge.pki.certificateToPem(cert) };
+};
+
+const post = (agent: https.Agent, port: number) =>
+ 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));
+ }
+ );
+ req.on("error", reject);
+ req.end("{}");
+ });
+
+const openConnections = (server: https.Server) =>
+ new Promise<number>((resolve, reject) => {
+ server.getConnections((err, count) => (err ? reject(err) : resolve(count)));
+ });
+
+describe("shared https agent pool (real sockets)", () => {
+ let server: https.Server;
+ let port: number;
+ let handledRequests = 0;
+
+ beforeAll(async () => {
+ const { key, cert } = selfSignedCert();
+ 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 }));
+ });
+ // 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.
+ server.keepAliveTimeout = 120_000;
+ await new Promise<void>((resolve) => {
+ server.listen(0, "127.0.0.1", () => resolve());
+ });
+ port = (server.address() as AddressInfo).port;
+ }, 30_000);
+
+ afterAll(async () => {
+ await new Promise<void>((resolve) => {
+ server.close(() => resolve());
+ });
+ });
+
+ it("serves many TokenReviews over a single connection when the host and CA are unchanged", async () => {
+ const before = handledRequests;
+ const agent = getSharedHttpsAgent({ rejectUnauthorized: false, servername: "reuse.test" });
+
+ for (let i = 0; i < 25; i += 1) {
+ // Sequential on purpose: concurrent requests legitimately open parallel
+ // sockets, which would not distinguish pooling from per-request agents.
+ // eslint-disable-next-line no-await-in-loop
+ expect(await post(agent, port)).toBe(401);
+ }
+
+ expect(handledRequests - before).toBe(25);
+ expect(await openConnections(server)).toBe(1);
+
+ agent.destroy();
+ });
+
+ it("holds exactly one idle socket open between calls, and releases it on destroy", async () => {
+ const agent = getSharedHttpsAgent({ rejectUnauthorized: false, servername: "idle.test" });
+ await post(agent, port);
+
+ expect(await openConnections(server)).toBe(1);
+
+ agent.destroy();
+ await new Promise((resolve) => {
+ setTimeout(resolve, 100);
+ });
+
+ expect(await openConnections(server)).toBe(0);
+ });
+
+ it("closes the sockets of agents the pool evicts, instead of stranding them for the process lifetime", async () => {
+ const victim = getSharedHttpsAgent({ rejectUnauthorized: false, servername: "victim.test" });
+ await post(victim, port);
+ expect(await openConnections(server)).toBe(1);
+
+ // Push past AGENT_CACHE_MAX so the victim is evicted as least recently used.
+ for (let i = 0; i < 250; i += 1) {
+ getSharedHttpsAgent({ rejectUnauthorized: false, servername: `pressure-${i}.test` });
+ }
+
+ await new Promise((resolve) => {
+ setTimeout(resolve, 100);
+ });
+
+ 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 21655cd23c..8dfcbfea96 100644
--- a/backend/src/lib/validator/safe-request.test.ts
+++ b/backend/src/lib/validator/safe-request.test.ts
@@ -4,7 +4,7 @@ import type { Agent as HttpsAgent } from "node:https";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { buildSsrfSafeAgent, safeRequest, validateAndPinUrl } from "./safe-request";
+import { buildSsrfSafeAgent, getSharedHttpsAgent, safeRequest, validateAndPinUrl } from "./safe-request";
type MockedRequestFn = (config: unknown) => Promise<{
data: unknown;
@@ -337,6 +337,68 @@ describe("safe-request SSRF helpers", () => {
});
});
+ describe("getSharedHttpsAgent (pooling + eviction)", () => {
+ const CA_A = "-----BEGIN CERTIFICATE-----\nAAA\n-----END CERTIFICATE-----";
+ const CA_B = "-----BEGIN CERTIFICATE-----\nBBB\n-----END CERTIFICATE-----";
+
+ it("returns the same agent for an identical ca / rejectUnauthorized / servername signature", () => {
+ const first = getSharedHttpsAgent({ ca: CA_A, rejectUnauthorized: true, servername: "k8s.example.com" });
+ const second = getSharedHttpsAgent({ ca: CA_A, rejectUnauthorized: true, servername: "k8s.example.com" });
+ expect(second).toBe(first);
+ });
+
+ it("returns a distinct agent when the CA differs, so a rotated CA is never served from the old pool entry", () => {
+ const withCaA = getSharedHttpsAgent({ ca: CA_A, rejectUnauthorized: true, servername: "k8s.example.com" });
+ const withCaB = getSharedHttpsAgent({ ca: CA_B, rejectUnauthorized: true, servername: "k8s.example.com" });
+ expect(withCaB).not.toBe(withCaA);
+ expect(withCaB.options.ca).toBe(CA_B);
+ });
+
+ it("returns a distinct agent when rejectUnauthorized or servername differ", () => {
+ const base = getSharedHttpsAgent({ ca: CA_A, rejectUnauthorized: true, servername: "k8s.example.com" });
+ expect(getSharedHttpsAgent({ ca: CA_A, rejectUnauthorized: false, servername: "k8s.example.com" })).not.toBe(
+ base
+ );
+ expect(getSharedHttpsAgent({ ca: CA_A, rejectUnauthorized: true, servername: "other.example.com" })).not.toBe(
+ base
+ );
+ expect(getSharedHttpsAgent({ ca: CA_A, rejectUnauthorized: true })).not.toBe(base);
+ });
+
+ it("keeps connections alive and bounds sockets, so repeat TokenReviews reuse one connection", () => {
+ const agent = getSharedHttpsAgent({ ca: CA_A, rejectUnauthorized: true, servername: "keepalive.example.com" });
+ expect(agent.options.keepAlive).toBe(true);
+ expect(agent.maxSockets).toBe(50);
+ expect(agent.maxFreeSockets).toBe(10);
+ });
+
+ it("destroys the least recently used agent on eviction rather than dropping the reference", () => {
+ const victim = getSharedHttpsAgent({ ca: CA_A, rejectUnauthorized: true, servername: "victim.example.com" });
+ const destroySpy = vi.spyOn(victim, "destroy");
+
+ // A dropped keepAlive agent is never collected (its idle sockets keep it
+ // reachable) and holds an fd per pooled socket, so eviction must destroy it.
+ for (let i = 0; i < 250; i += 1) {
+ getSharedHttpsAgent({ ca: CA_A, rejectUnauthorized: true, servername: `evict-${i}.example.com` });
+ }
+
+ expect(destroySpy).toHaveBeenCalled();
+ });
+
+ 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");
+
+ for (let i = 0; i < 150; i += 1) {
+ getSharedHttpsAgent({ ca: CA_B, rejectUnauthorized: true, servername: `lru-${i}.example.com` });
+ // Touch the hot entry so it stays at the recent end of the pool.
+ expect(getSharedHttpsAgent({ ca: CA_B, rejectUnauthorized: true, servername: "hot.example.com" })).toBe(hot);
+ }
+
+ expect(hotDestroy).not.toHaveBeenCalled();
+ });
+ });
+
describe("safeRequest dispatch", () => {
it("validates the URL, builds a pinned agent, and forwards to the underlying axios with maxRedirects:0", async () => {
requestRequestMock.mockResolvedValueOnce({ data: { ok: true }, status: 200, headers: {} });
diff --git a/backend/src/lib/validator/safe-request.ts b/backend/src/lib/validator/safe-request.ts
index 6bd79e0914..a2a65f139d 100644
--- a/backend/src/lib/validator/safe-request.ts
+++ b/backend/src/lib/validator/safe-request.ts
@@ -169,11 +169,26 @@ const hasAgentCustomization = (opts: TBuildAgentOptions): boolean =>
// Pool of agents keyed by connection signature for connection reuse across
// repeated calls. The cache key includes the validated IP set so DNS record
-// changes naturally produce a fresh entry. The hard cap is cleared wholesale
-// when exceeded — misses just rebuild.
+// changes naturally produce a fresh entry. Insertion order doubles as LRU
+// recency, so eviction at the cap drops the least recently used entry.
const AGENT_CACHE_MAX = 200;
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.
+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}]`);
+ }
+};
+
const buildAgentCacheKey = (
validated: TValidatedHost | undefined,
protocol: string,
@@ -249,14 +264,14 @@ const buildPinnedAgent = (
const cacheKey = buildAgentCacheKey(validated, protocol, opts);
const cached = agentCache.get(cacheKey);
if (cached) {
+ // Re-insert so the map's insertion order tracks recency of use.
+ agentCache.delete(cacheKey);
+ agentCache.set(cacheKey, cached);
logger.debug(`safeRequest: pinned agent cache hit [hostname=${validated?.hostname ?? "n/a"}]`);
return cached;
}
- if (agentCache.size >= AGENT_CACHE_MAX) {
- logger.info(`safeRequest: pinned agent cache full, clearing [size=${agentCache.size}]`);
- agentCache.clear();
- }
+ evictLeastRecentlyUsedAgents();
const agent = constructAgent(validated, protocol, opts);
agentCache.set(cacheKey, agent);
@@ -298,6 +313,21 @@ export const buildSsrfSafeAgent = async (
});
};
+type TSharedHttpsAgentOptions = {
+ ca?: string;
+ rejectUnauthorized: boolean;
+ servername?: string;
+};
+
+// A pooled https.Agent for callers that customize TLS (custom CA, SNI, verification
+// toggle) but cannot go through `safeRequest` (gateway paths, for example)
+//
+// The point of pooling here is that building one per request re-parses the CA into a
+// fresh OpenSSL trust store and forces a full TLS handshake every time, with no session
+// reuse: an agent's TLS session cache is per-agent.
+export const getSharedHttpsAgent = (options: TSharedHttpsAgentOptions): https.Agent =>
+ buildPinnedAgent(undefined, "https:", options) as https.Agent;
+
type TSafeRequestExtras = {
allowPrivateIps?: boolean;
addressFamily?: 4 | 6;
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-fns.test.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-fns.test.ts
new file mode 100644
index 0000000000..8ac82a5a41
--- /dev/null
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-fns.test.ts
@@ -0,0 +1,90 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ extractK8sUsername,
+ getKubernetesHostname,
+ getKubernetesServerName,
+ withKubernetesHostScheme
+} from "./identity-kubernetes-auth-fns";
+
+describe("withKubernetesHostScheme", () => {
+ it("leaves an explicit scheme alone and defaults the rest to https", () => {
+ expect(withKubernetesHostScheme("https://k8s.example.com:6443")).toBe("https://k8s.example.com:6443");
+ expect(withKubernetesHostScheme("http://k8s.example.com")).toBe("http://k8s.example.com");
+ expect(withKubernetesHostScheme("k8s.example.com:6443")).toBe("https://k8s.example.com:6443");
+ });
+});
+
+describe("getKubernetesServerName", () => {
+ it.each([
+ ["https://k8s.example.com:6443", "k8s.example.com"],
+ ["https://k8s.example.com", "k8s.example.com"],
+ ["http://k8s.example.com:8080", "k8s.example.com"],
+ ["k8s.example.com:6443", "k8s.example.com"],
+ ["k8s.example.com", "k8s.example.com"],
+ ["https://cluster.mk8s.us-north1.nebius.cloud:443", "cluster.mk8s.us-north1.nebius.cloud"]
+ ])("keeps the host name for %s", (host, expected) => {
+ expect(getKubernetesServerName(host)).toBe(expected);
+ });
+
+ // SNI carries host names only (RFC 6066); sending an IP literal makes strict servers
+ // reject the handshake, and the cert is matched on its IP SANs instead.
+ it.each([["https://10.0.0.1:6443"], ["https://10.0.0.1"], ["10.0.0.1:6443"], ["10.0.0.1"]])(
+ "returns undefined for the IPv4 host %s",
+ (host) => {
+ expect(getKubernetesServerName(host)).toBeUndefined();
+ }
+ );
+
+ // The previous lastIndexOf(":") split truncated "[::1]:6443" to "[::1]" and a bare
+ // "::1" to ":", neither of which isIP recognises, so both were sent as SNI.
+ it.each([["https://[2001:db8::1]:6443"], ["https://[2001:db8::1]"], ["[2001:db8::1]:6443"], ["https://[::1]:6443"]])(
+ "returns undefined for the IPv6 host %s rather than a truncated name",
+ (host) => {
+ expect(getKubernetesServerName(host)).toBeUndefined();
+ }
+ );
+
+ it("returns undefined rather than throwing for an unparseable host", () => {
+ expect(getKubernetesServerName("")).toBeUndefined();
+ expect(getKubernetesServerName("https://")).toBeUndefined();
+ expect(getKubernetesServerName("http://[not-an-ipv6")).toBeUndefined();
+ });
+
+ it("ignores a path or query on the configured host", () => {
+ expect(getKubernetesServerName("https://k8s.example.com:6443/apis")).toBe("k8s.example.com");
+ expect(getKubernetesServerName("https://k8s.example.com?x=1")).toBe("k8s.example.com");
+ });
+});
+
+describe("getKubernetesHostname", () => {
+ // The tunnelled gateway request is addressed to localhost, so the certificate identity
+ // check has nothing but this to go on — an IP host has to survive it.
+ it.each([
+ ["https://10.0.0.1:6443", "10.0.0.1"],
+ ["10.0.0.1", "10.0.0.1"],
+ ["https://[2001:db8::1]:6443", "2001:db8::1"],
+ ["https://k8s.example.com:6443", "k8s.example.com"],
+ ["k8s.example.com", "k8s.example.com"]
+ ])("returns the bare host for %s", (host, expected) => {
+ expect(getKubernetesHostname(host)).toBe(expected);
+ });
+
+ it("returns undefined for an unparseable host", () => {
+ expect(getKubernetesHostname("")).toBeUndefined();
+ expect(getKubernetesHostname("https://")).toBeUndefined();
+ });
+});
+
+describe("extractK8sUsername", () => {
+ it("splits a service account username into namespace and name", () => {
+ expect(extractK8sUsername("system:serviceaccount:default:infisical-auth")).toEqual({
+ namespace: "default",
+ name: "infisical-auth"
+ });
+ });
+
+ it("rejects a username that is not a service account", () => {
+ expect(() => extractK8sUsername("kubernetes-admin")).toThrow(/Invalid Kubernetes service account username/);
+ });
+});
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-fns.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-fns.ts
index 9841ae001e..4f9c1200e0 100644
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-fns.ts
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-fns.ts
@@ -10,15 +10,34 @@ const SCHEME_PREFIX = "^https?://";
export const withKubernetesHostScheme = (kubernetesHost: string) =>
new RE2(SCHEME_PREFIX).test(kubernetesHost) ? kubernetesHost : `https://${kubernetesHost}`;
+// The host as a bare name or address: scheme, port and IPv6 brackets removed. Parsing rather
+// than splitting on the last colon is what makes IPv6 come out right; the split truncates
+// "[::1]:6443" to "[::1]" and a bare "::1" to ":".
+export const getKubernetesHostname = (kubernetesHost: string): string | undefined => {
+ let hostname: string;
+ try {
+ ({ hostname } = new URL(withKubernetesHostScheme(kubernetesHost)));
+ } catch {
+ return undefined;
+ }
+
+ // `new URL` keeps IPv6 literals bracketed, which isIP does not recognize.
+ if (hostname.startsWith("[") && hostname.endsWith("]")) {
+ hostname = hostname.slice(1, -1);
+ }
+
+ return hostname || undefined;
+};
+
// Undefined for a bare IP: SNI carries host names only, so an IP host is matched on IP SANs.
// Passing the IP as SNI makes verification fail outright.
-export const getKubernetesServerName = (kubernetesHost: string) => {
- let servername = new RE2(SCHEME_PREFIX).replace(kubernetesHost, "");
- const lastColonIndex = servername.lastIndexOf(":");
- if (lastColonIndex !== -1) {
- servername = servername.substring(0, lastColonIndex);
- }
- return isIP(servername) ? undefined : servername;
+//
+// Only correct when the request is addressed to the Kubernetes host itself, so that Node can
+// fall back to the URL host for the certificate identity check. A request tunnelled through a
+// gateway is addressed to localhost and needs getKubernetesHostname instead.
+export const getKubernetesServerName = (kubernetesHost: string): string | undefined => {
+ const hostname = getKubernetesHostname(kubernetesHost);
+ return !hostname || isIP(hostname) ? undefined : hostname;
};
/**
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
index 31a9e84b7b..b07a76ff50 100644
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
@@ -55,7 +55,7 @@ import {
authAttemptCounter,
recordAuthAttemptMetric
} from "@app/lib/telemetry/metrics";
-import { safeRequest } from "@app/lib/validator/safe-request";
+import { getSharedHttpsAgent, safeRequest } from "@app/lib/validator/safe-request";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -69,7 +69,12 @@ import { TOrgDALFactory } from "../org/org-dal";
import { validateIdentityUpdateForSuperAdminPrivileges } from "../super-admin/super-admin-fns";
import { TIdentityKubernetesAuthDALFactory } from "./identity-kubernetes-auth-dal";
import { handleAxiosError, isKnownError, KubernetesAuthErrorContext } from "./identity-kubernetes-auth-error-handlers";
-import { extractK8sUsername, getKubernetesServerName, withKubernetesHostScheme } from "./identity-kubernetes-auth-fns";
+import {
+ extractK8sUsername,
+ getKubernetesHostname,
+ getKubernetesServerName,
+ withKubernetesHostScheme
+} from "./identity-kubernetes-auth-fns";
import {
IdentityKubernetesAuthTokenReviewMode,
TAttachKubernetesAuthDTO,
@@ -151,7 +156,7 @@ export const identityKubernetesAuthServiceFactory = ({
): Promise<T> => {
let gatewayHttpsAgent: https.Agent | undefined;
if (!inputs.reviewTokenThroughGateway) {
- gatewayHttpsAgent = new https.Agent({
+ gatewayHttpsAgent = getSharedHttpsAgent({
ca: inputs.caCert || undefined,
rejectUnauthorized: inputs.verifyTlsCertificate ?? true,
servername: inputs.targetHost
@@ -221,15 +226,7 @@ export const identityKubernetesAuthServiceFactory = ({
targetPort: inputs.targetPort,
relayDetails,
// only needed for TCP protocol, because the gateway as reviewer will use the pod's CA cert for auth directly
- ...(!inputs.reviewTokenThroughGateway
- ? {
- httpsAgent: new https.Agent({
- ca: inputs.caCert || undefined,
- rejectUnauthorized: inputs.verifyTlsCertificate ?? true,
- servername: inputs.targetHost
- })
- }
- : {})
+ ...(gatewayHttpsAgent ? { httpsAgent: gatewayHttpsAgent } : {})
}
);
@@ -365,6 +362,7 @@ export const identityKubernetesAuthServiceFactory = ({
}
const servername = getKubernetesServerName(identityKubernetesAuth.kubernetesHost);
+ const tunnelServername = getKubernetesHostname(identityKubernetesAuth.kubernetesHost);
const baseUrl = port ? `${host}:${port}` : withKubernetesHostScheme(host);
const url = `${baseUrl}/apis/authentication.k8s.io/v1/tokenreviews`;
const body = {
@@ -389,10 +387,10 @@ export const identityKubernetesAuthServiceFactory = ({
isThroughGateway
? request.post<TCreateTokenReviewResponse>(url, body, {
...config,
- httpsAgent: new https.Agent({
+ httpsAgent: getSharedHttpsAgent({
ca: caCert || undefined,
rejectUnauthorized: identityKubernetesAuth.verifyTlsCertificate,
- servername
+ servername: tunnelServername
})
})
: safeRequest.post<TCreateTokenReviewResponse>(url, body, {