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
refactor: enhance Kubernetes authentication functions and improve request handling
Victor Hugo dos Santos5fde2b473795
diff --git a/backend/src/ee/services/resource-auth-method/kubernetes-auth-fns.ts b/backend/src/ee/services/resource-auth-method/kubernetes-auth-fns.tsindex 9b3090a3c5..b20ed3d248 100644--- a/backend/src/ee/services/resource-auth-method/kubernetes-auth-fns.ts+++ b/backend/src/ee/services/resource-auth-method/kubernetes-auth-fns.ts@@ -1,8 +1,5 @@-import { isIP } from "node:net";-import { AxiosError } from "axios";import picomatch from "picomatch";-import RE2 from "re2";import { BadRequestError, UnauthorizedError } from "@app/lib/errors";import { logger } from "@app/lib/logger";@@ -12,7 +9,11 @@ import {handleAxiosError,KubernetesAuthErrorContext} from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-error-handlers";-import { extractK8sUsername } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-fns";+import {+ extractK8sUsername,+ getKubernetesServerName,+ withKubernetesHostScheme+} from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-fns";import { TCreateTokenReviewResponse } from "@app/services/identity-kubernetes-auth/identity-kubernetes-auth-types";import { ResourceAuthLoginFailureReason } from "./resource-auth-method-fns";@@ -29,16 +30,6 @@ const TOKEN_REVIEW_MAX_RESPONSE_BYTES = 64 * 1024;// The host is operator-supplied and the backend POSTs to it on every login, so without this an// org admin could use the auth config to reach hosts inside our own network. Does a DNS lookup,// so call it outside a transaction.-// Undefined for a bare IP: SNI carries host names only, so an IP host is matched on IP SANs.-const toServerName = (kubernetesHost: string) => {- let servername = new RE2("^https?://").replace(kubernetesHost, "");- const lastColonIndex = servername.lastIndexOf(":");- if (lastColonIndex !== -1) {- servername = servername.substring(0, lastColonIndex);- }- return isIP(servername) ? undefined : servername;-};-// One shape for both routes to the API server: straight out from Infisical, or tunnelled through a// gateway. Callers below only deal in paths, so nothing downstream has to know which is in play.export type TKubernetesRequestExecutor = <T = unknown>(@@ -48,9 +39,6 @@ export type TKubernetesRequestExecutor = <T = unknown>(headers?: Record<string, string>) => Promise<{ status: number; data: T }>;-const withScheme = (kubernetesHost: string) =>- new RE2("^https?://").test(kubernetesHost) ? kubernetesHost : `https://${kubernetesHost}`;-export const buildDirectKubernetesExecutor = ({kubernetesHost,caCertificate,@@ -60,7 +48,7 @@ export const buildDirectKubernetesExecutor = ({caCertificate?: string;verifyTlsCertificate: boolean;}): TKubernetesRequestExecutor => {- const baseUrl = withScheme(kubernetesHost);+ const baseUrl = withKubernetesHostScheme(kubernetesHost);return async <T>(method: "get" | "post", path: string, body?: object, headers?: Record<string, string>) => {// Fresh per call: an abort signal must not be shared between requests.@@ -68,7 +56,7 @@ export const buildDirectKubernetesExecutor = ({headers,ca: caCertificate || undefined,rejectUnauthorized: verifyTlsCertificate,- servername: toServerName(kubernetesHost),+ servername: getKubernetesServerName(kubernetesHost),timeout: TOKEN_REVIEW_TIMEOUT_MS,signal: AbortSignal.timeout(TOKEN_REVIEW_TIMEOUT_MS),maxContentLength: TOKEN_REVIEW_MAX_RESPONSE_BYTES,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.tsindex e840471968..9841ae001e 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@@ -1,5 +1,26 @@+import { isIP } from "node:net";++import RE2 from "re2";+import { BadRequestError } from "@app/lib/errors";+const SCHEME_PREFIX = "^https?://";++// The stored host may omit a scheme. URL parsing, SSRF validation and Axios all need one.+export const withKubernetesHostScheme = (kubernetesHost: string) =>+ new RE2(SCHEME_PREFIX).test(kubernetesHost) ? kubernetesHost : `https://${kubernetesHost}`;++// 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;+};+/*** Extracts the K8s service account name and namespace* from the username in this format: system:serviceaccount:default:infisical-authdiff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.tsindex 20d3cbe306..31a9e84b7b 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,6 +55,7 @@ import {authAttemptCounter,recordAuthAttemptMetric} from "@app/lib/telemetry/metrics";+import { safeRequest } from "@app/lib/validator/safe-request";import { ActorType } from "../auth/auth-type";import { TIdentityDALFactory } from "../identity/identity-dal";@@ -68,7 +69,7 @@ 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 } from "./identity-kubernetes-auth-fns";+import { extractK8sUsername, getKubernetesServerName, withKubernetesHostScheme } from "./identity-kubernetes-auth-fns";import {IdentityKubernetesAuthTokenReviewMode,TAttachKubernetesAuthDTO,@@ -84,6 +85,11 @@ import {validateTokenReviewerPermissions} from "./identity-kubernetes-auth-validators";+const TOKEN_REVIEW_TIMEOUT_MS = 10_000;+// A TokenReview response is a few KB; the largest part is the echoed token, itself capped at 8KB+// by the route schema. Bounded so an operator-supplied host cannot make us buffer an arbitrary body.+const TOKEN_REVIEW_MAX_RESPONSE_BYTES = 64 * 1024;+type TIdentityKubernetesAuthServiceFactoryDep = {identityDAL: Pick<TIdentityDALFactory, "findById">;identityKubernetesAuthDAL: Pick<@@ -147,7 +153,7 @@ export const identityKubernetesAuthServiceFactory = ({if (!inputs.reviewTokenThroughGateway) {gatewayHttpsAgent = new https.Agent({ca: inputs.caCert || undefined,- rejectUnauthorized: inputs.verifyTlsCertificate ?? false,+ rejectUnauthorized: inputs.verifyTlsCertificate ?? true,servername: inputs.targetHost});}@@ -219,7 +225,7 @@ export const identityKubernetesAuthServiceFactory = ({? {httpsAgent: new https.Agent({ca: inputs.caCert || undefined,- rejectUnauthorized: inputs.verifyTlsCertificate ?? false,+ rejectUnauthorized: inputs.verifyTlsCertificate ?? true,servername: inputs.targetHost})}@@ -295,14 +301,6 @@ export const identityKubernetesAuthServiceFactory = ({};};- const $resolveEffectiveVerifyTlsCertificate = (- caCert: string | null | undefined,- storedVerify: boolean | null | undefined- ): boolean => {- if (!caCert?.length) return false;- return storedVerify ?? false;- };-const login = async ({ identityId, jwt: serviceAccountJwt, organizationSlug }: TLoginKubernetesAuthDTO) => {const authMetricStartTime = performance.now();const appCfg = getConfig();@@ -340,7 +338,14 @@ export const identityKubernetesAuthServiceFactory = ({caCert = decryptor({ cipherTextBlob: identityKubernetesAuth.encryptedKubernetesCaCertificate }).toString();}- const tokenReviewCallbackRaw = async (host = identityKubernetesAuth.kubernetesHost, port?: number) => {+ const tokenReviewCallbackRaw = async ({+ host = identityKubernetesAuth.kubernetesHost,+ port,+ // The gateway tunnels to a local proxy port, so the hop safeRequest would validate is+ // localhost rather than the Kubernetes host, and the host it does reach sits in the+ // gateway's network rather than ours.+ isThroughGateway = false+ }: { host?: string | null; port?: number; isThroughGateway?: boolean } = {}) => {logger.info({ host, port }, "tokenReviewCallbackRaw: Processing kubernetes token review using raw API");if (!host || !identityKubernetesAuth.kubernetesHost) {@@ -359,84 +364,78 @@ export const identityKubernetesAuthServiceFactory = ({tokenReviewerJwt = serviceAccountJwt;}- let servername = identityKubernetesAuth.kubernetesHost;- if (servername.startsWith("https://") || servername.startsWith("http://")) {- servername = new RE2("^https?:\\/\\/").replace(servername, "");- }-- // get the last colon index, if it has a port, remove it, including the colon- const lastColonIndex = servername.lastIndexOf(":");- if (lastColonIndex !== -1) {- servername = servername.substring(0, lastColonIndex);- }-- const baseUrl = port ? `${host}:${port}` : host;-- const res = await request- .post<TCreateTokenReviewResponse>(- `${baseUrl}/apis/authentication.k8s.io/v1/tokenreviews`,- {- apiVersion: "authentication.k8s.io/v1",- kind: "TokenReview",- spec: {- token: serviceAccountJwt,- ...(identityKubernetesAuth.allowedAudience- ? { audiences: [identityKubernetesAuth.allowedAudience] }- : {})- }- },- {- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${tokenReviewerJwt}`- },- signal: AbortSignal.timeout(10000),- timeout: 10000,- httpsAgent: new https.Agent({+ const servername = getKubernetesServerName(identityKubernetesAuth.kubernetesHost);+ const baseUrl = port ? `${host}:${port}` : withKubernetesHostScheme(host);+ const url = `${baseUrl}/apis/authentication.k8s.io/v1/tokenreviews`;+ const body = {+ apiVersion: "authentication.k8s.io/v1",+ kind: "TokenReview",+ spec: {+ token: serviceAccountJwt,+ ...(identityKubernetesAuth.allowedAudience ? { audiences: [identityKubernetesAuth.allowedAudience] } : {})+ }+ };+ const config = {+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${tokenReviewerJwt}`+ },+ signal: AbortSignal.timeout(TOKEN_REVIEW_TIMEOUT_MS),+ timeout: TOKEN_REVIEW_TIMEOUT_MS,+ maxContentLength: TOKEN_REVIEW_MAX_RESPONSE_BYTES+ };++ const res = await (+ isThroughGateway+ ? request.post<TCreateTokenReviewResponse>(url, body, {+ ...config,+ httpsAgent: new https.Agent({+ ca: caCert || undefined,+ rejectUnauthorized: identityKubernetesAuth.verifyTlsCertificate,+ servername+ })+ })+ : safeRequest.post<TCreateTokenReviewResponse>(url, body, {+ ...config,ca: caCert || undefined,- rejectUnauthorized: $resolveEffectiveVerifyTlsCertificate(- caCert,- identityKubernetesAuth.verifyTlsCertificate- ),+ rejectUnauthorized: identityKubernetesAuth.verifyTlsCertificate,servername})- }- )- .catch((err) => {- const tokenReviewerJwtSnippet = `${tokenReviewerJwt?.substring?.(0, 10) || ""}...${tokenReviewerJwt?.substring?.(tokenReviewerJwt.length - 10) || ""}`;- const serviceAccountJwtSnippet = `${serviceAccountJwt?.substring?.(0, 10) || ""}...${serviceAccountJwt?.substring?.(serviceAccountJwt.length - 10) || ""}`;-- if (err instanceof AxiosError) {- logger.error(- {- response: err.response,- host,- port,- tokenReviewerJwtSnippet,- serviceAccountJwtSnippet,- code: err.code- },- "tokenReviewCallbackRaw: Kubernetes token review request error (request error)"- );-- throw handleAxiosError(err, { host, port }, KubernetesAuthErrorContext.KubernetesApiServer);- }+ ).catch((err) => {+ const tokenReviewerJwtSnippet = `${tokenReviewerJwt?.substring?.(0, 10) || ""}...${tokenReviewerJwt?.substring?.(tokenReviewerJwt.length - 10) || ""}`;+ const serviceAccountJwtSnippet = `${serviceAccountJwt?.substring?.(0, 10) || ""}...${serviceAccountJwt?.substring?.(serviceAccountJwt.length - 10) || ""}`;+ if (err instanceof AxiosError) {logger.error(- { error: err as Error, host, port, tokenReviewerJwtSnippet, serviceAccountJwtSnippet },- "tokenReviewCallbackRaw: Kubernetes token review request error (non-request error)"+ {+ response: err.response,+ host,+ port,+ tokenReviewerJwtSnippet,+ serviceAccountJwtSnippet,+ code: err.code+ },+ "tokenReviewCallbackRaw: Kubernetes token review request error (request error)");- if (isKnownError(err)) {- throw err;- }+ throw handleAxiosError(err, { host, port }, KubernetesAuthErrorContext.KubernetesApiServer);+ }- throw new BadRequestError({- name: "KubernetesTokenReviewError",- message: (err as Error).message || "Unexpected error during token review",- error: err- });+ logger.error(+ { error: err as Error, host, port, tokenReviewerJwtSnippet, serviceAccountJwtSnippet },+ "tokenReviewCallbackRaw: Kubernetes token review request error (non-request error)"+ );++ if (isKnownError(err)) {+ throw err;+ }++ throw new BadRequestError({+ name: "KubernetesTokenReviewError",+ message: (err as Error).message || "Unexpected error during token review",+ error: err});+ });return res.data;};@@ -516,10 +515,7 @@ export const identityKubernetesAuthServiceFactory = ({: ((identityKubernetesAuth.gatewayV2Id ?? identityKubernetesAuth.gatewayId) as string),gatewayPoolId: identityKubernetesAuth.gatewayPoolId ?? undefined,caCert: caCert || undefined,- verifyTlsCertificate: $resolveEffectiveVerifyTlsCertificate(- caCert,- identityKubernetesAuth.verifyTlsCertificate- ),+ verifyTlsCertificate: identityKubernetesAuth.verifyTlsCertificate,reviewTokenThroughGateway: true},tokenReviewCallbackThroughGateway@@ -553,13 +549,11 @@ export const identityKubernetesAuthServiceFactory = ({targetHost: k8sHost,targetPort: k8sPort ? Number(k8sPort) : 443,caCert: caCert || undefined,- verifyTlsCertificate: $resolveEffectiveVerifyTlsCertificate(- caCert,- identityKubernetesAuth.verifyTlsCertificate- ),+ verifyTlsCertificate: identityKubernetesAuth.verifyTlsCertificate,reviewTokenThroughGateway: false},- tokenReviewCallbackRaw+ (gatewayHost, gatewayPort) =>+ tokenReviewCallbackRaw({ host: gatewayHost, port: gatewayPort, isThroughGateway: true })): await tokenReviewCallbackRaw();} else {@@ -1268,9 +1262,7 @@ export const identityKubernetesAuthServiceFactory = ({} else if (caCert !== undefined && caCert.length > 0) {resolvedVerifyTlsCertificate = true;}- const effectiveVerifyTlsCertificate =- resolvedVerifyTlsCertificate ??- $resolveEffectiveVerifyTlsCertificate(effectiveCaCert, identityKubernetesAuth.verifyTlsCertificate);+ const effectiveVerifyTlsCertificate = resolvedVerifyTlsCertificate ?? identityKubernetesAuth.verifyTlsCertificate;if (effectiveVerifyTlsCertificate &&@@ -1486,7 +1478,6 @@ export const identityKubernetesAuthServiceFactory = ({...identityKubernetesAuth,caCert,tokenReviewerJwt,- verifyTlsCertificate: $resolveEffectiveVerifyTlsCertificate(caCert, identityKubernetesAuth.verifyTlsCertificate),orgId: identityMembershipOrg.scopeOrgId,gatewayId: identityKubernetesAuth.gatewayId ?? identityKubernetesAuth.gatewayV2Id};diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-validators.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-validators.tsindex fd00c77fc7..c9dc60a660 100644--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-validators.ts+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-validators.ts@@ -1,12 +1,16 @@import { AxiosError, AxiosResponse } from "axios";-import https from "https";-import { request } from "@app/lib/config/request";import { BadRequestError } from "@app/lib/errors";import { logger } from "@app/lib/logger";-import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";+import { safeRequest } from "@app/lib/validator/safe-request";import { handleAxiosError, KubernetesAuthErrorContext } from "./identity-kubernetes-auth-error-handlers";+import { getKubernetesServerName, withKubernetesHostScheme } from "./identity-kubernetes-auth-fns";++const VALIDATION_TIMEOUT_MS = 10_000;+// The /version and TokenReview responses are a few KB. Bounded so an operator-supplied host+// cannot make us buffer an arbitrary body.+const VALIDATION_MAX_RESPONSE_BYTES = 64 * 1024;export type GatewayRequestExecutor = <T>(method: "get" | "post",@@ -53,17 +57,13 @@ export const validateKubernetesHostConnectivity = async ({});}- const httpsAgent = new https.Agent({+ response = await safeRequest.get(`${withKubernetesHostScheme(kubernetesHost)}/version`, {ca: caCert || undefined,- rejectUnauthorized: verifyTlsCertificate ?? false- });-- await blockLocalAndPrivateIpAddresses(kubernetesHost);-- response = await request.get(`${kubernetesHost}/version`, {- httpsAgent,- timeout: 10000,- signal: AbortSignal.timeout(10000),+ rejectUnauthorized: verifyTlsCertificate ?? true,+ servername: getKubernetesServerName(kubernetesHost),+ timeout: VALIDATION_TIMEOUT_MS,+ signal: AbortSignal.timeout(VALIDATION_TIMEOUT_MS),+ maxContentLength: VALIDATION_MAX_RESPONSE_BYTES,validateStatus: () => true});}@@ -158,23 +158,23 @@ export const validateTokenReviewerPermissions = async ({});}- const httpsAgent = new https.Agent({- ca: caCert || undefined,- rejectUnauthorized: verifyTlsCertificate ?? false- });-- await blockLocalAndPrivateIpAddresses(kubernetesHost);-- response = await request.post(`${kubernetesHost}/apis/authentication.k8s.io/v1/tokenreviews`, tokenReviewBody, {- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${tokenReviewerJwt}`- },- httpsAgent,- timeout: 10000,- signal: AbortSignal.timeout(10000),- validateStatus: () => true- });+ response = await safeRequest.post(+ `${withKubernetesHostScheme(kubernetesHost)}/apis/authentication.k8s.io/v1/tokenreviews`,+ tokenReviewBody,+ {+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${tokenReviewerJwt}`+ },+ ca: caCert || undefined,+ rejectUnauthorized: verifyTlsCertificate ?? true,+ servername: getKubernetesServerName(kubernetesHost),+ timeout: VALIDATION_TIMEOUT_MS,+ signal: AbortSignal.timeout(VALIDATION_TIMEOUT_MS),+ maxContentLength: VALIDATION_MAX_RESPONSE_BYTES,+ validateStatus: () => true+ }+ );}if (response.status === 401) {