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
test: add unit tests for various gateway connection functions
Victor Hugo dos Santosa62b6e7c50e2
diff --git a/backend/src/ee/services/dynamic-secret/providers/kubernetes.test.ts b/backend/src/ee/services/dynamic-secret/providers/kubernetes.test.tsnew file mode 100644index 0000000000..a725d8a5df--- /dev/null+++ b/backend/src/ee/services/dynamic-secret/providers/kubernetes.test.ts@@ -0,0 +1,162 @@+/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { KubernetesProvider } from "./kubernetes";+import { KubernetesAuthMethod, KubernetesCredentialType } from "./models";++// Asserts the k8sHttpClient factory inside KubernetesProvider:+// - direct path (isGatewayProxied=false, caller-asserted):+// * uses safeRequest (never request)+// * translates ca / sslRejectUnauthorized into safeRequest's flat options+// * drops the caller's pre-built httpsAgent+// * always sets allowPrivateIps: true (in-cluster RFC1918 / link-local)+// - gateway path (isGatewayProxied=true via $gatewayProxyWrapper):+// * uses raw request (never safeRequest)+// * preserves the gateway-supplied httpsAgent+//+// We drive this through the exported KubernetesProvider.validateConnection+// using the Static credential type (single GET) to keep the test minimal.++const { safeGetMock, safePostMock, safeDeleteMock, rawGetMock, rawPostMock, rawDeleteMock } = vi.hoisted(() => ({+ safeGetMock: vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number }>>(),+ safePostMock: vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number }>>(),+ safeDeleteMock: vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number }>>(),+ rawGetMock: vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number }>>(),+ rawPostMock: vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number }>>(),+ rawDeleteMock: vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number }>>()+}));++vi.mock("@app/lib/validator", () => ({+ blockLocalAndPrivateIpAddresses: vi.fn(async () => undefined),+ safeRequest: {+ get: (...args: unknown[]) => safeGetMock(...args),+ post: (...args: unknown[]) => safePostMock(...args),+ delete: (...args: unknown[]) => safeDeleteMock(...args)+ }+}));++vi.mock("@app/lib/config/request", () => ({+ request: {+ get: (...args: unknown[]) => rawGetMock(...args),+ post: (...args: unknown[]) => rawPostMock(...args),+ delete: (...args: unknown[]) => rawDeleteMock(...args)+ },+ createRequestClient: () => ({+ interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() } },+ request: vi.fn(),+ get: vi.fn(),+ post: vi.fn(),+ delete: vi.fn()+ }),+ axiosResponseInterceptor: (r: unknown) => r+}));++vi.mock("@app/lib/gateway", () => ({+ GatewayProxyProtocol: { Tcp: "tcp", Http: "http" },+ GatewayHttpProxyActions: { UseGatewayK8sServiceAccount: "use-gateway-k8s-sa" },+ withGatewayProxy: async (cb: (port: number, agent: unknown) => Promise<unknown>, opts: any) =>+ cb(1234, opts?.httpsAgent)+}));++vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({+ withGatewayV2Proxy: async (cb: (port: number) => Promise<unknown>) => cb(5678)+}));++vi.mock("./templateUtils", () => ({+ generateUsername: vi.fn(async () => "dynamic-secret-sa-abc123")+}));++vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isDevelopmentMode: false }) }));+vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));++const STATIC_INPUT_BASE = {+ credentialType: KubernetesCredentialType.Static,+ serviceAccountName: "my-sa",+ namespace: "default",+ audiences: [],+ authMethod: KubernetesAuthMethod.Api,+ clusterToken: "tok-abc",+ url: "https://k8s.example.com:6443",+ sslEnabled: true,+ ca: "-----BEGIN CERTIFICATE-----\nFAKECACERT==\n-----END CERTIFICATE-----",+ sslRejectUnauthorized: true+};++describe("KubernetesProvider — k8sHttpClient dispatch", () => {+ beforeEach(() => {+ for (const m of [safeGetMock, safePostMock, safeDeleteMock, rawGetMock, rawPostMock, rawDeleteMock]) {+ m.mockReset();+ m.mockResolvedValue({ data: {}, status: 200 });+ }+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("direct call (no gatewayId) → safeRequest.get with ca/rejectUnauthorized flat + allowPrivateIps + no httpsAgent", async () => {+ const provider = KubernetesProvider({+ gatewayService: { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,+ gatewayV2Service: { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any+ });++ await provider.validateConnection({ ...STATIC_INPUT_BASE });++ expect(safeGetMock).toHaveBeenCalledTimes(1);+ expect(rawGetMock).not.toHaveBeenCalled();++ const [, opts] = safeGetMock.mock.calls[0];+ expect(opts.allowPrivateIps).toBe(true);+ expect(opts.ca).toBe(STATIC_INPUT_BASE.ca);+ expect(opts.rejectUnauthorized).toBe(true);+ // Direct mode must drop the caller's pre-built httpsAgent — safeRequest+ // builds its own pinned agent from the flat options above.+ expect(opts.httpsAgent).toBeUndefined();+ });++ it("gateway path ($gatewayProxyWrapper asserts isGatewayProxied=true) → raw request.get with httpsAgent preserved", async () => {+ const gatewayDetails = { relayHost: "relay", gateway: { id: "g" }, relay: { id: "r" } };+ const provider = KubernetesProvider({+ gatewayService: { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,+ gatewayV2Service: {+ getPlatformConnectionDetailsByGatewayId: vi.fn(async () => gatewayDetails)+ } as any+ });++ await provider.validateConnection({+ ...STATIC_INPUT_BASE,+ gatewayId: "gw-k8s"+ });++ expect(rawGetMock).toHaveBeenCalledTimes(1);+ expect(safeGetMock).not.toHaveBeenCalled();++ const [, opts] = rawGetMock.mock.calls[0];+ // Gateway path preserves the caller's https.Agent (carrying the relay TLS+ // context). The gateway already constrains the originally configured target.+ expect(opts.httpsAgent).toBeDefined();+ // It must NOT leak safeRequest-only flat TLS opts into the raw-request call.+ expect(opts.allowPrivateIps).toBeUndefined();+ expect(opts.ca).toBeUndefined();+ expect(opts.rejectUnauthorized).toBeUndefined();+ });++ it("direct call with sslEnabled=false does NOT forward ca / rejectUnauthorized (only allowPrivateIps stays)", async () => {+ const provider = KubernetesProvider({+ gatewayService: { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,+ gatewayV2Service: { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any+ });++ await provider.validateConnection({+ ...STATIC_INPUT_BASE,+ sslEnabled: false,+ ca: undefined+ });++ expect(safeGetMock).toHaveBeenCalledTimes(1);+ const [, opts] = safeGetMock.mock.calls[0];+ expect(opts.allowPrivateIps).toBe(true);+ expect(opts.ca).toBeUndefined();+ expect(opts.rejectUnauthorized).toBeUndefined();+ });+});diff --git a/backend/src/services/app-connection/github/github-connection-fns.test.ts b/backend/src/services/app-connection/github/github-connection-fns.test.tsnew file mode 100644index 0000000000..95726c1dac--- /dev/null+++ b/backend/src/services/app-connection/github/github-connection-fns.test.ts@@ -0,0 +1,143 @@+/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { requestWithGitHubGateway } from "./github-connection-fns";++// Asserts the "requestWithGitHubGateway" wrapper correctly routes:+// - direct (no gatewayId) -> safeRequest.request+// - gateway v1 (fnGetGatewayClientTlsByGatewayId only)+// - gateway v2 (getPlatformConnectionDetailsByGatewayId returns details)+// and never leaks a gateway call onto safeRequest or vice-versa.++const { safeRequestMock, httpRequestMock, withGatewayProxyMock, withGatewayV2ProxyMock, verifyHostInputValidityMock } =+ vi.hoisted(() => ({+ safeRequestMock:+ vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),+ httpRequestMock:+ vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),+ // withGatewayProxy({ callback }, options) -> invoke callback(1234) and return its result+ withGatewayProxyMock: vi.fn(async (cb: (port: number) => Promise<unknown>) => cb(1234)),+ withGatewayV2ProxyMock: vi.fn(async (cb: (port: number) => Promise<unknown>) => cb(5678)),+ verifyHostInputValidityMock: vi.fn(async ({ host }: { host: string }) => [host] as string[])+ }));++vi.mock("@app/lib/validator", () => ({+ safeRequest: { request: (...args: unknown[]) => safeRequestMock(...args) },+ blockLocalAndPrivateIpAddresses: vi.fn(async () => undefined)+}));++vi.mock("@app/lib/config/request", () => ({+ request: { request: (...args: unknown[]) => httpRequestMock(...args) },+ createRequestClient: () => ({+ interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() } },+ request: (...args: unknown[]) => httpRequestMock(...args),+ get: vi.fn(),+ post: vi.fn(),+ delete: vi.fn()+ }),+ axiosResponseInterceptor: (r: unknown) => r+}));++vi.mock("@app/lib/gateway", () => ({+ GatewayProxyProtocol: { Tcp: "tcp", Http: "http" },+ withGatewayProxy: (cb: (port: number) => Promise<unknown>, options: unknown) => withGatewayProxyMock(cb, options)+}));++vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({+ withGatewayV2Proxy: (cb: (port: number) => Promise<unknown>, options: unknown) => withGatewayV2ProxyMock(cb, options)+}));++vi.mock("@app/ee/services/dynamic-secret/dynamic-secret-fns", () => ({+ verifyHostInputValidity: verifyHostInputValidityMock+}));++vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isDevelopmentMode: false }) }));+vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn() } }));++const BASE_REQ = {+ url: "https://api.github.com/app",+ method: "GET" as const,+ headers: { Accept: "application/vnd.github+json" }+};++const okAxiosResponse = { data: { ok: true }, status: 200, headers: {} };++describe("requestWithGitHubGateway", () => {+ beforeEach(() => {+ safeRequestMock.mockReset();+ safeRequestMock.mockResolvedValue(okAxiosResponse);+ httpRequestMock.mockReset();+ httpRequestMock.mockResolvedValue(okAxiosResponse);+ withGatewayProxyMock.mockClear();+ withGatewayV2ProxyMock.mockClear();+ verifyHostInputValidityMock.mockClear();+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("routes through safeRequest when gatewayId is null (direct path)", async () => {+ await requestWithGitHubGateway(+ { gatewayId: null },+ { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,+ { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any,+ BASE_REQ+ );++ expect(safeRequestMock).toHaveBeenCalledTimes(1);+ expect(httpRequestMock).not.toHaveBeenCalled();+ expect(withGatewayProxyMock).not.toHaveBeenCalled();+ expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();+ expect(safeRequestMock.mock.calls[0][0]).toMatchObject({ url: BASE_REQ.url, method: "GET" });+ });++ it("routes through gateway v2 (raw request) when v2 connection details are supplied", async () => {+ const v2Details = { relayHost: "relay.example", gateway: { id: "g1" }, relay: { id: "r1" } };++ await requestWithGitHubGateway(+ { gatewayId: "gw-123" },+ { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,+ { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any,+ BASE_REQ,+ v2Details as any+ );++ expect(safeRequestMock).not.toHaveBeenCalled();+ expect(withGatewayV2ProxyMock).toHaveBeenCalledTimes(1);+ expect(withGatewayProxyMock).not.toHaveBeenCalled();+ expect(httpRequestMock).toHaveBeenCalledTimes(1);++ const call = httpRequestMock.mock.calls[0][0];+ expect(String(call.url)).toContain("localhost:5678");+ expect(call.headers.Host).toBe("api.github.com");+ expect(call.httpsAgent).toBeDefined();+ });++ it("falls back to gateway v1 (raw request) when no v2 details are supplied", async () => {+ const fnGetGatewayClientTlsByGatewayId = vi.fn(async () => ({+ relayPort: 9999,+ relayHost: "relay.v1",+ tlsOptions: {},+ identityId: "i",+ orgId: "o"+ }));++ await requestWithGitHubGateway(+ { gatewayId: "gw-123" },+ { fnGetGatewayClientTlsByGatewayId } as any,+ { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any,+ BASE_REQ+ );++ expect(safeRequestMock).not.toHaveBeenCalled();+ expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();+ expect(withGatewayProxyMock).toHaveBeenCalledTimes(1);+ expect(httpRequestMock).toHaveBeenCalledTimes(1);+ expect(fnGetGatewayClientTlsByGatewayId).toHaveBeenCalledWith("gw-123");++ const call = httpRequestMock.mock.calls[0][0];+ expect(String(call.url)).toContain("localhost:1234");+ expect(call.headers.Host).toBe("api.github.com");+ });+});diff --git a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.test.ts b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.test.tsnew file mode 100644index 0000000000..dd15c5c461--- /dev/null+++ b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.test.ts@@ -0,0 +1,157 @@+/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { GatewayVersion } from "@app/lib/gateway/types";++import { requestWithHCVaultGateway } from "./hc-vault-connection-fns";++// Asserts the "requestWithHCVaultGateway" wrapper correctly routes:+// - direct (no gatewayId) -> safeRequest.request+// - gateway v2 (v2 connection details) -> raw request via withGatewayV2Proxy+// - gateway v1 (fallback when v2 absent) -> raw request via withGatewayProxy++const { safeRequestMock, httpRequestMock, withGatewayProxyMock, withGatewayV2ProxyMock, verifyHostInputValidityMock } =+ vi.hoisted(() => ({+ safeRequestMock:+ vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),+ httpRequestMock:+ vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),+ withGatewayProxyMock: vi.fn(async (cb: (port: number) => Promise<unknown>) => cb(1234)),+ withGatewayV2ProxyMock: vi.fn(async (cb: (port: number) => Promise<unknown>) => cb(5678)),+ verifyHostInputValidityMock: vi.fn(async ({ host }: { host: string }) => [host] as string[])+ }));++vi.mock("@app/lib/validator", () => ({+ safeRequest: { request: (...args: unknown[]) => safeRequestMock(...args) }+}));++vi.mock("@app/lib/config/request", () => ({+ request: { request: (...args: unknown[]) => httpRequestMock(...args) },+ createRequestClient: () => ({+ interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() } },+ request: (...args: unknown[]) => httpRequestMock(...args),+ get: vi.fn(),+ post: vi.fn(),+ delete: vi.fn()+ }),+ axiosResponseInterceptor: (r: unknown) => r+}));++vi.mock("@app/lib/gateway", () => ({+ GatewayProxyProtocol: { Tcp: "tcp", Http: "http" },+ withGatewayProxy: (cb: (port: number) => Promise<unknown>, options: unknown) => withGatewayProxyMock(cb, options)+}));++vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({+ withGatewayV2Proxy: (cb: (port: number) => Promise<unknown>, options: unknown) => withGatewayV2ProxyMock(cb, options)+}));++vi.mock("@app/ee/services/dynamic-secret/dynamic-secret-fns", () => ({+ verifyHostInputValidity: verifyHostInputValidityMock+}));++vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isDevelopmentMode: false }) }));+vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn() } }));++const BASE_REQ = {+ url: "https://vault.example.com:8200/v1/auth/token/lookup-self",+ method: "GET" as const,+ headers: { "X-Vault-Token": "t" }+};++const okAxiosResponse = { data: { ok: true }, status: 200, headers: {} };++describe("requestWithHCVaultGateway", () => {+ beforeEach(() => {+ safeRequestMock.mockReset();+ safeRequestMock.mockResolvedValue(okAxiosResponse);+ httpRequestMock.mockReset();+ httpRequestMock.mockResolvedValue(okAxiosResponse);+ withGatewayProxyMock.mockClear();+ withGatewayV2ProxyMock.mockClear();+ verifyHostInputValidityMock.mockClear();+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("routes through safeRequest when gatewayId is absent", async () => {+ await requestWithHCVaultGateway(+ { gatewayId: null },+ { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,+ { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any,+ BASE_REQ+ );++ expect(safeRequestMock).toHaveBeenCalledTimes(1);+ expect(httpRequestMock).not.toHaveBeenCalled();+ expect(withGatewayProxyMock).not.toHaveBeenCalled();+ expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();+ expect(safeRequestMock.mock.calls[0][0]).toMatchObject({ url: BASE_REQ.url, method: "GET" });+ });++ it("routes through gateway v2 (raw request) when v2 details resolve", async () => {+ const v2Details = { relayHost: "relay.example", gateway: { id: "g1" }, relay: { id: "r1" } };+ const getPlatformConnectionDetailsByGatewayId = vi.fn(async () => v2Details);++ await requestWithHCVaultGateway(+ { gatewayId: "gw-vault" },+ { fnGetGatewayClientTlsByGatewayId: vi.fn() } as any,+ { getPlatformConnectionDetailsByGatewayId } as any,+ BASE_REQ+ );++ expect(safeRequestMock).not.toHaveBeenCalled();+ expect(withGatewayV2ProxyMock).toHaveBeenCalledTimes(1);+ expect(withGatewayProxyMock).not.toHaveBeenCalled();+ expect(httpRequestMock).toHaveBeenCalledTimes(1);+ const call = httpRequestMock.mock.calls[0][0];+ expect(String(call.url)).toContain("localhost:5678");+ expect(call.headers.Host).toBe("vault.example.com");+ });++ it("falls back to gateway v1 (raw request) when v2 details are null", async () => {+ const getPlatformConnectionDetailsByGatewayId = vi.fn(async () => null);+ const fnGetGatewayClientTlsByGatewayId = vi.fn(async () => ({+ relayPort: 9999,+ relayHost: "relay.v1",+ tlsOptions: {},+ identityId: "i",+ orgId: "o"+ }));++ await requestWithHCVaultGateway(+ { gatewayId: "gw-vault" },+ { fnGetGatewayClientTlsByGatewayId } as any,+ { getPlatformConnectionDetailsByGatewayId } as any,+ BASE_REQ+ );++ expect(safeRequestMock).not.toHaveBeenCalled();+ expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();+ expect(withGatewayProxyMock).toHaveBeenCalledTimes(1);+ expect(httpRequestMock).toHaveBeenCalledTimes(1);+ expect(fnGetGatewayClientTlsByGatewayId).toHaveBeenCalledWith("gw-vault");+ });++ it("uses pre-supplied V1 gateway details without calling the DAL again", async () => {+ const fnGetGatewayClientTlsByGatewayId = vi.fn();++ await requestWithHCVaultGateway(+ { gatewayId: "gw-vault" },+ { fnGetGatewayClientTlsByGatewayId } as any,+ { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any,+ BASE_REQ,+ {+ gatewayVersion: GatewayVersion.V1,+ details: { relayPort: 1, relayHost: "h", tlsOptions: {}, identityId: "i", orgId: "o" } as any,+ target: { host: "vault.example.com", port: 8200 }+ }+ );++ expect(fnGetGatewayClientTlsByGatewayId).not.toHaveBeenCalled();+ expect(withGatewayProxyMock).toHaveBeenCalledTimes(1);+ expect(httpRequestMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/backend/src/services/app-connection/netscaler/netscaler-connection-fns.test.ts b/backend/src/services/app-connection/netscaler/netscaler-connection-fns.test.tsnew file mode 100644index 0000000000..10859cc5b1--- /dev/null+++ b/backend/src/services/app-connection/netscaler/netscaler-connection-fns.test.ts@@ -0,0 +1,136 @@+/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { executeNetScalerOperationWithGateway } from "./netscaler-connection-fns";++// Asserts the "executeNetScalerOperationWithGateway" helper:+// - direct path (no gatewayId) uses safeRequest with rejectUnauthorized/ca+// forwarded as flat options (never a pre-built https.Agent)+// - gateway v2 path uses raw request via withGatewayV2Proxy and passes+// ca/rejectUnauthorized through a locally-built httpsAgent+// - gateway path without resolvable v2 connection details throws++const { safeRequestMock, httpRequestMock, withGatewayV2ProxyMock } = vi.hoisted(() => ({+ safeRequestMock:+ vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),+ httpRequestMock:+ vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),+ withGatewayV2ProxyMock: vi.fn(async (cb: (port: number) => Promise<unknown>) => cb(5678))+}));++vi.mock("@app/lib/validator", () => ({+ safeRequest: { request: (...args: unknown[]) => safeRequestMock(...args) }+}));++vi.mock("@app/lib/config/request", () => ({+ request: { request: (...args: unknown[]) => httpRequestMock(...args) },+ createRequestClient: () => ({+ interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() } },+ request: (...args: unknown[]) => httpRequestMock(...args),+ get: vi.fn(),+ post: vi.fn(),+ delete: vi.fn()+ }),+ axiosResponseInterceptor: (r: unknown) => r+}));++vi.mock("@app/lib/gateway", () => ({+ GatewayProxyProtocol: { Tcp: "tcp", Http: "http" }+}));++vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({+ withGatewayV2Proxy: (cb: (port: number) => Promise<unknown>, options: unknown) => withGatewayV2ProxyMock(cb, options)+}));++vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isDevelopmentMode: false }) }));+vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn() } }));++const CREDS = {+ hostname: "netscaler.example.com",+ port: 443,+ username: "u",+ password: "p",+ sslRejectUnauthorized: true,+ sslCertificate: "-----BEGIN CERTIFICATE-----\nMIIBASEFAKE==\n-----END CERTIFICATE-----"+};++const okDataResponse = { data: { ok: true }, status: 200, headers: {} };++describe("executeNetScalerOperationWithGateway", () => {+ beforeEach(() => {+ safeRequestMock.mockReset();+ safeRequestMock.mockResolvedValue(okDataResponse);+ httpRequestMock.mockReset();+ httpRequestMock.mockResolvedValue(okDataResponse);+ withGatewayV2ProxyMock.mockClear();+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("direct path routes through safeRequest with rejectUnauthorized/ca as flat options", async () => {+ const result = await executeNetScalerOperationWithGateway(+ { gatewayId: null, credentials: CREDS },+ undefined,+ async (makeRequest) =>+ makeRequest<{ ok: boolean }>({+ url: `https://${CREDS.hostname}:${CREDS.port}/nitro/v1/config/login`,+ method: "POST",+ data: { login: {} }+ })+ );++ expect(result).toEqual({ ok: true });+ expect(safeRequestMock).toHaveBeenCalledTimes(1);+ expect(httpRequestMock).not.toHaveBeenCalled();+ expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();++ const opts = safeRequestMock.mock.calls[0][0];+ expect(opts.rejectUnauthorized).toBe(true);+ expect(opts.ca).toEqual([CREDS.sslCertificate]);+ expect(opts.httpsAgent).toBeUndefined();+ });++ it("gateway v2 path routes through raw request with httpsAgent carrying ca/rejectUnauthorized", async () => {+ const v2Details = { relayHost: "relay.example", gateway: { id: "g1" }, relay: { id: "r1" } };+ const getPlatformConnectionDetailsByGatewayId = vi.fn(async () => v2Details);++ await executeNetScalerOperationWithGateway(+ { gatewayId: "gw-nsc", credentials: CREDS },+ { getPlatformConnectionDetailsByGatewayId } as any,+ async (makeRequest) =>+ makeRequest<{ ok: boolean }>({+ url: `https://${CREDS.hostname}:${CREDS.port}/nitro/v1/config/login`,+ method: "POST",+ data: { login: {} }+ })+ );++ expect(safeRequestMock).not.toHaveBeenCalled();+ expect(withGatewayV2ProxyMock).toHaveBeenCalledTimes(1);+ expect(httpRequestMock).toHaveBeenCalledTimes(1);++ const call = httpRequestMock.mock.calls[0][0];+ expect(String(call.url)).toContain("localhost:5678");+ expect(call.headers.Host).toBe(CREDS.hostname);+ expect(call.httpsAgent).toBeDefined();+ expect(call.rejectUnauthorized).toBeUndefined();+ expect(call.ca).toBeUndefined();+ });++ it("throws when a gateway is set but v2 details are not resolvable", async () => {+ const getPlatformConnectionDetailsByGatewayId = vi.fn(async () => null);++ await expect(+ executeNetScalerOperationWithGateway(+ { gatewayId: "gw-nsc", credentials: CREDS },+ { getPlatformConnectionDetailsByGatewayId } as any,+ async (makeRequest) => makeRequest<{ ok: boolean }>({ url: "https://x", method: "GET" })+ )+ ).rejects.toThrow(/no platform connection details/i);++ expect(safeRequestMock).not.toHaveBeenCalled();+ expect(httpRequestMock).not.toHaveBeenCalled();+ });+});diff --git a/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.test.ts b/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.test.tsnew file mode 100644index 0000000000..be6282212f--- /dev/null+++ b/backend/src/services/app-connection/venafi-tpp/venafi-tpp-connection-fns.test.ts@@ -0,0 +1,120 @@+/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { requestWithVenafiTppGateway } from "./venafi-tpp-connection-fns";++// Asserts the "requestWithVenafiTppGateway" wrapper:+// - direct (no gatewayId) -> safeRequest.request+// - gateway v2 -> raw request via withGatewayV2Proxy+// - no v2 gateway details available -> throws (v1 not supported)++const { safeRequestMock, httpRequestMock, withGatewayV2ProxyMock, verifyHostInputValidityMock } = vi.hoisted(() => ({+ safeRequestMock:+ vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),+ httpRequestMock:+ vi.fn<(...args: any[]) => Promise<{ data: unknown; status: number; headers: Record<string, unknown> }>>(),+ withGatewayV2ProxyMock: vi.fn(async (cb: (port: number) => Promise<unknown>) => cb(5678)),+ verifyHostInputValidityMock: vi.fn(async ({ host }: { host: string }) => [host] as string[])+}));++vi.mock("@app/lib/validator/validate-url", () => ({+ safeRequest: { request: (...args: unknown[]) => safeRequestMock(...args) }+}));++vi.mock("@app/lib/config/request", () => ({+ request: { request: (...args: unknown[]) => httpRequestMock(...args) },+ createRequestClient: () => ({+ interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() } },+ request: (...args: unknown[]) => httpRequestMock(...args),+ get: vi.fn(),+ post: vi.fn(),+ delete: vi.fn()+ }),+ axiosResponseInterceptor: (r: unknown) => r+}));++vi.mock("@app/lib/gateway", () => ({+ GatewayProxyProtocol: { Tcp: "tcp", Http: "http" }+}));++vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({+ withGatewayV2Proxy: (cb: (port: number) => Promise<unknown>, options: unknown) => withGatewayV2ProxyMock(cb, options)+}));++vi.mock("@app/ee/services/dynamic-secret/dynamic-secret-fns", () => ({+ verifyHostInputValidity: verifyHostInputValidityMock+}));++vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({ isDevelopmentMode: false }) }));+vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn() } }));++const BASE_REQ = {+ url: "https://venafi.example.com/vedsdk/certificates",+ method: "GET" as const,+ headers: { Authorization: "Bearer x" }+};++const okAxiosResponse = { data: { ok: true }, status: 200, headers: {} };++describe("requestWithVenafiTppGateway", () => {+ beforeEach(() => {+ safeRequestMock.mockReset();+ safeRequestMock.mockResolvedValue(okAxiosResponse);+ httpRequestMock.mockReset();+ httpRequestMock.mockResolvedValue(okAxiosResponse);+ withGatewayV2ProxyMock.mockClear();+ verifyHostInputValidityMock.mockClear();+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("routes through safeRequest when gatewayId is absent", async () => {+ await requestWithVenafiTppGateway(+ { gatewayId: null },+ { getPlatformConnectionDetailsByGatewayId: vi.fn() } as any,+ BASE_REQ+ );++ expect(safeRequestMock).toHaveBeenCalledTimes(1);+ expect(httpRequestMock).not.toHaveBeenCalled();+ expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();+ expect(safeRequestMock.mock.calls[0][0]).toMatchObject({ url: BASE_REQ.url });+ });++ it("routes through gateway v2 when v2 details resolve", async () => {+ const v2Details = { relayHost: "relay.example", gateway: { id: "g1" }, relay: { id: "r1" } };+ const getPlatformConnectionDetailsByGatewayId = vi.fn(async () => v2Details);++ await requestWithVenafiTppGateway(+ { gatewayId: "gw-venafi" },+ { getPlatformConnectionDetailsByGatewayId } as any,+ BASE_REQ+ );++ expect(safeRequestMock).not.toHaveBeenCalled();+ expect(withGatewayV2ProxyMock).toHaveBeenCalledTimes(1);+ expect(httpRequestMock).toHaveBeenCalledTimes(1);+ const call = httpRequestMock.mock.calls[0][0];+ expect(String(call.url)).toContain("localhost:5678");+ expect(call.headers.Host).toBe("venafi.example.com");+ expect(call.httpsAgent).toBeDefined();+ });++ it("throws when a gateway is set but no v2 details are resolvable (v1 not supported)", async () => {+ const getPlatformConnectionDetailsByGatewayId = vi.fn(async () => null);++ await expect(+ requestWithVenafiTppGateway(+ { gatewayId: "gw-venafi" },+ { getPlatformConnectionDetailsByGatewayId } as any,+ BASE_REQ+ )+ ).rejects.toThrow(/v2 gateways/i);++ expect(safeRequestMock).not.toHaveBeenCalled();+ expect(httpRequestMock).not.toHaveBeenCalled();+ expect(withGatewayV2ProxyMock).not.toHaveBeenCalled();+ });+});diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.tsnew file mode 100644index 0000000000..003882de21--- /dev/null+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.test.ts@@ -0,0 +1,188 @@+/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { identityKubernetesAuthServiceFactory } from "./identity-kubernetes-auth-service";+import { IdentityKubernetesAuthTokenReviewMode } from "./identity-kubernetes-auth-types";++// Asserts the interaction of $resolveEffectiveVerifyTlsCertificate with+// safeRequest.post in the "raw" token-review path:+// - the resolved boolean flows into the flat `rejectUnauthorized` option+// - ca is passed as a flat string, not wrapped in a pre-built https.Agent+// - caCert === "" always forces rejectUnauthorized=false, regardless of+// the stored verifyTlsCertificate flag+//+// We drive the factory's login() far enough to hit safeRequest.post and+// then have the mock throw so we can inspect the captured call options.++const { safePostMock, rawPostMock } = vi.hoisted(() => ({+ safePostMock: vi.fn(),+ rawPostMock: vi.fn()+}));++vi.mock("@app/lib/validator", () => ({+ safeRequest: { post: (...args: unknown[]) => safePostMock(...args) }+}));++vi.mock("@app/lib/config/request", () => ({+ request: { post: (...args: unknown[]) => rawPostMock(...args) },+ createRequestClient: () => ({+ interceptors: { request: { use: vi.fn() }, response: { use: vi.fn() } },+ request: vi.fn(),+ get: vi.fn(),+ post: vi.fn(),+ delete: vi.fn()+ }),+ axiosResponseInterceptor: (r: unknown) => r+}));++vi.mock("@app/lib/config/env", () => ({+ getConfig: () => ({ OTEL_TELEMETRY_COLLECTION_ENABLED: false, isDevelopmentMode: false })+}));+vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));++vi.mock("@app/lib/request-context/request-memoizer", () => ({+ requestMemoize: async <T>(_k: string, fetcher: () => Promise<T>) => fetcher()+}));++// Mock the gateway modules to avoid loading @infisical/quic native bindings.+vi.mock("@app/lib/gateway", () => ({+ GatewayProxyProtocol: { Tcp: "tcp", Http: "http" },+ GatewayHttpProxyActions: { UseGatewayK8sServiceAccount: "use-gateway-k8s-sa" },+ withGatewayProxy: vi.fn()+}));+vi.mock("@app/lib/gateway/types", () => ({+ GatewayProxyProtocol: { Tcp: "tcp", Http: "http" },+ GatewayHttpProxyActions: { UseGatewayK8sServiceAccount: "use-gateway-k8s-sa" },+ GatewayVersion: { V1: "v1", V2: "v2" }+}));+vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({+ withGatewayV2Proxy: vi.fn()+}));++vi.mock("@app/lib/request-context/memo-keys", () => ({+ requestMemoKeys: { identityFindById: (id: string) => `id:${id}`, orgFindById: (id: string) => `org:${id}` }+}));++vi.mock("@app/lib/request-context/request-context-keys", () => ({+ RequestContextKey: { Ip: "ip", UserAgent: "ua", Memoizer: "mem" }+}));++// Required to avoid loading the real fastify request context wrapper+vi.mock("@fastify/request-context", () => ({ requestContext: { get: () => undefined } }));++vi.mock("@app/lib/telemetry/metrics", () => ({+ authAttemptCounter: { add: vi.fn() },+ AuthAttemptAuthMethod: { KUBERNETES_AUTH: "kubernetes-auth" },+ AuthAttemptAuthResult: { FAILURE: "failure", SUCCESS: "success" }+}));++type KubernetesAuthRecord = Record<string, unknown>;++const buildService = (kubernetesAuthRecord: KubernetesAuthRecord, caCertPlainText: string) => {+ const decryptor = vi.fn(({ cipherTextBlob }: { cipherTextBlob: Buffer | null }) =>+ Buffer.from(cipherTextBlob ? caCertPlainText : "")+ );++ return identityKubernetesAuthServiceFactory({+ identityDAL: { findById: vi.fn(async () => ({ id: "i-1", orgId: "o-1", name: "test-identity" })) } as any,+ identityKubernetesAuthDAL: {+ findOne: vi.fn(async () => kubernetesAuthRecord),+ create: vi.fn(),+ transaction: vi.fn(),+ updateById: vi.fn(),+ delete: vi.fn()+ } as any,+ identityAccessTokenDAL: { create: vi.fn(), delete: vi.fn() } as any,+ membershipIdentityDAL: { findOne: vi.fn(), update: vi.fn(), getIdentityById: vi.fn() } as any,+ permissionService: { getOrgPermission: vi.fn(), getProjectPermission: vi.fn() } as any,+ licenseService: { getPlan: vi.fn() } as any,+ kmsService: {+ createCipherPairWithDataKey: vi.fn(async () => ({ decryptor, encryptor: vi.fn() }))+ } as any,+ gatewayService: {} as any,+ gatewayV2Service: {} as any,+ gatewayDAL: { find: vi.fn() } as any,+ gatewayV2DAL: { find: vi.fn() } as any,+ gatewayPoolService: { getPlatformConnectionDetailsByPoolId: vi.fn(), pickRandomHealthyGateway: vi.fn() } as any,+ gatewayPoolDAL: { findById: vi.fn() } as any,+ orgDAL: {+ findById: vi.fn(async () => ({ id: "o-1", name: "test-org", rootOrgId: null })),+ findOne: vi.fn(),+ findEffectiveOrgMembership: vi.fn()+ } as any+ });+};++const BASE_AUTH_RECORD = {+ identityId: "i-1",+ kubernetesHost: "https://k8s.example.com:6443",+ tokenReviewMode: IdentityKubernetesAuthTokenReviewMode.Api,+ gatewayId: null,+ gatewayV2Id: null,+ gatewayPoolId: null,+ allowedAudience: null,+ allowedNamespaces: null,+ allowedNames: null,+ encryptedKubernetesTokenReviewerJwt: Buffer.from("ciphertext"),+ encryptedKubernetesCaCertificate: Buffer.from("ciphertext")+};++describe("identityKubernetesAuthService — $resolveEffectiveVerifyTlsCertificate → safeRequest", () => {+ beforeEach(() => {+ safePostMock.mockReset();+ // Throw so login() exits before the token-review result is parsed — we+ // only care about the args safeRequest.post received.+ safePostMock.mockRejectedValue(new Error("short-circuit for test"));+ rawPostMock.mockReset();+ rawPostMock.mockRejectedValue(new Error("should not be called"));+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("passes rejectUnauthorized=true + ca as flat options when caCert present and verify=true", async () => {+ const svc = buildService(+ { ...BASE_AUTH_RECORD, verifyTlsCertificate: true },+ "-----BEGIN CERTIFICATE-----\nREALCACERT==\n-----END CERTIFICATE-----"+ );++ await expect(svc.login({ identityId: "i-1", jwt: "service-account-jwt" })).rejects.toThrow();++ expect(safePostMock).toHaveBeenCalledTimes(1);+ expect(rawPostMock).not.toHaveBeenCalled();++ const [, , opts] = safePostMock.mock.calls[0];+ expect(opts.rejectUnauthorized).toBe(true);+ expect(opts.ca).toBe("-----BEGIN CERTIFICATE-----\nREALCACERT==\n-----END CERTIFICATE-----");+ expect(opts.allowPrivateIps).toBe(true);+ expect(opts.httpsAgent).toBeUndefined();+ });++ it("collapses rejectUnauthorized to false when caCert is empty (even if stored verify=true)", async () => {+ const svc = buildService({ ...BASE_AUTH_RECORD, verifyTlsCertificate: true }, "");++ await expect(svc.login({ identityId: "i-1", jwt: "service-account-jwt" })).rejects.toThrow();++ expect(safePostMock).toHaveBeenCalledTimes(1);+ const [, , opts] = safePostMock.mock.calls[0];+ expect(opts.rejectUnauthorized).toBe(false);+ expect(opts.ca).toBeUndefined();+ expect(opts.httpsAgent).toBeUndefined();+ });++ it("passes rejectUnauthorized=false when caCert present but stored verify=false", async () => {+ const svc = buildService(+ { ...BASE_AUTH_RECORD, verifyTlsCertificate: false },+ "-----BEGIN CERTIFICATE-----\nREALCACERT==\n-----END CERTIFICATE-----"+ );++ await expect(svc.login({ identityId: "i-1", jwt: "service-account-jwt" })).rejects.toThrow();++ expect(safePostMock).toHaveBeenCalledTimes(1);+ const [, , opts] = safePostMock.mock.calls[0];+ expect(opts.rejectUnauthorized).toBe(false);+ expect(opts.ca).toBe("-----BEGIN CERTIFICATE-----\nREALCACERT==\n-----END CERTIFICATE-----");+ expect(opts.httpsAgent).toBeUndefined();+ });+});